Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Java Language.

Similar presentations


Presentation on theme: "The Java Language."— Presentation transcript:

1 The Java Language

2 Topics of this Course Introduction to Java The Java Language
Object Oriented Programming in Java Exceptions Handling Threads Applet GUI Networking

3 Chapter 1 Introduction to Java Bibliography History What is Java?
Environments Security Memory Managment Java Syntax Introduction to Java

4 Bibliography The Java Programming Language – Ken Arnold,James Gosling
The Java Tutorial - Third Edition Mary Campione & Kathy Walrath Addison Wesley Online : Introduction to Java

5 History 1991 - language for consumer devices small, tight,efficient
OOP C++ ruled out named Oak, name collision, became Java Introduction to Java

6 History 1994 Browsers - static pages of html.
Gosling realized that Java could provide an architecture neutral browser with downloadable and executable content. J. Gosling, J. Payne, P. Naughton build HOTJAVA Demonstration of technology at SunWorld May 23, 1995 was “Hit” of show. Netscape releases Java interpreter in 2.0 Introduction to Java

7 Versions 1.0 initial release 1.1
major changes to fix event handling problems in 1.0 support new and needed methodologies (read that as beans) 1.2 , 1.3(AKA Java 2) mostly expanding capabilities. Introduction to Java

8 What is Java ? An Object-oriented Programming Language
A Virtual Machine Architecture (JVM) Platform independent and secure (portable bytecodes) A feature for dynamic WEB pages A program library Development tools Introduction to Java

9 Virtual Machine Java is both compiled and interpreted language
Java source turned into simple binary instructions C/C++ source is refined to native instructions for a particular processor Java compiled into a universal format - instructions for a virtual machine. Introduction to Java

10 Compiled Java byte-code (J-code) is executed by Java run-time interpreter in a safe, virtual environment . Executes stack-based instruction set, manages a storage heap, creates and manipulates primitive data types. Executes in accordance with a strictly defined open specification that can be implemented by anyone on any platform. Introduction to Java

11 Java Interpreter Java interpreter is lightweight and small.
Written in C/C++ Interpreter can be run as separate, self-standing, application embedded in another piece of software, such as Web browser Java code is implicitly portable Introduction to Java

12 Introduction to Java

13 Environments javac SomeName.java
a class named SomeName is defined in this file. java SomeName instantiates the SomeName.class and starts the static public void main(String[] x) {} method. appletviewer File.html file contains an applet. The browser loads the applet, calls the init(), then start() methods. If applet becomes invisible the stop() method is called. After a time the destroy() method is called. Introduction to Java

14 Environments package means directory.
package mechanism is a compile time (javac) visibility issue, not a #include, and does not mean the interpreter (java) will find the classes it needs. work in a directory and be sure your interpreter looks for classes in your current directory. CLASSPATH and PATH variables are sometimes required to fix visibility issues. Introduction to Java

15 Applet vs. Application Application - normal Java program
Applet - program to be executed by a WEB browser Applets typically loaded from some URL on the WEB before execution new thing which makes Java popular (dynamic pages) Introduction to Java

16 “Just in Time” Compilation
Interpreted languages slow Java is considered to be a fast interpreted language - interpreter executes compiled byte-code. Software implementations of the run-time system can optimize performance by compiling byte-code to native machine code on the fly. Introduction to Java

17 Security Java provides several layers of protection from dangerously flawed code, viruses and Trojan horses. Java virtual machine architecture assesses the safety of the code before it’s run. These features provide foundation for high-level security policies. Introduction to Java

18 Security language is essential when running applets over the net
three layers of security language bytecode (verified before execution) runtime (security manager to prevent unallowed IO and net operations) Introduction to Java

19 Language Security No direct memory addressing allowed
No pointer arithmetic Automatic storage release with a garbage collector. All casts checked at runtime. All array accesses checked at runtime. Introduction to Java

20 Memory Managment The most important differences between Java and C/C++ involve how Java manages memory. Java eliminates add hoc pointers adds garbage collection adds true arrays These features eliminate many problems related to safety, portability and optimization. Introduction to Java

21 Memory Managment Explicit memory allocation and deallocation are considered the largest source of programming errors in C/C++ Java maintains objects in memory as well as tracks all references to those objects. When an object is no longer in use, Java removes it from memory. Garbage collector runs in the background. This means that most garbage collection is done between events (mouse clicks, keyboard hits,…) Introduction to Java

22 Memory Managment Java does not have pointers as we know them in C/C++. However, Java provides references - safe pointer. A reference is a strongly-typed handle for an object. All objects, except primitive numeric types, are accessed through references. References can be used for building linked lists, trees and other data structures. Introduction to Java

23 Memory Managment Pointer arithmetic can’t be done using references.
References are passed by value. References can’t reference an object through more than a single level of indirection. Protection of references is one of the fundamental aspects of Java security. This means that references can’t examine memory locations that should not be examined. Introduction to Java

24 Java Syntax Java does not allow programmer-defined operator overloading as we know it in C++, for instance. The string concatenation operator + is the only system-defined, overloaded operator in Java. All methods in Java are like C++ virtual methods, so overridden methods are dynamically selected at run-time. Introduction to Java

25 Java Syntax Java does not have a preprocessor, so it doesn’t have
macros #define statements conditional source compilation Other languages need these constructs in order to address various system-dependent issues. Another use for conditional compilation is for debugging purposes. Introduction to Java

26 Java Syntax Debugging code in Java can be included directly in Java source code by making it conditional on a constant (static vs. final) variable. Java compiler takes care of this at compile time - it simply removes it when it determines that it will not be called. Java also provides a well-defined package structure for organizing class files. The compiler works with compiled Java classes (all the info is there). Introduction to Java

27 Arrays Arrays in Java are first-class citizens. Arrays...
can be dynamically allocated and assigned like other objects know their own size and type True arrays eliminate the need for pointer arithmetic. Introduction to Java

28 Classes Fundamental unit of Java
Class is an application component that holds executable code and data Java classes are distributed in a universal binary format that contains Java byte-code and other class information. Classes can be maintained discretely and stored in files or archives (local or net) Classes are located and loaded dynamically at run-time Introduction to Java

29 Error Handling Java was first written for the networked devices and embedded systems. This is why Java provides robustness and intelligent error management. Java has powerful exception-handling mechanism. Allows us to separate error-handling code from normal code - cleaner&readable code. Introduction to Java

30 MultiThreading Today’s apps require parallelism (unrelated tasks must execute, if possible, at the same time) Threads provide efficient multiprocessing and distribution of tasks. Java makes threads easy to use - support built into the language Synchronization of threads Java’s support of synchronization is based “lock and key system for accessing resources”. Introduction to Java

31 Chapter 2 The Java Language Hello World Application Hello World Applet
Java Language Features The Java Language

32 Hello Wolrd Application
class HelloWorld { /** * compile first via * javac HelloWorld * the main method is then executed by * java HelloWorld arg */ public static void main(String [] argv) { System.out.println(“Hello World!”); } Note that main denotes the function to execute for a given program, with type String -> void. The Java Language

33 Compiling and Executing
javac HelloWorld.java java HelloWorld The Java Language

34 Hello World Applet import java.applet.Applet; // import Applet class import java.awt.Graphics; // import Graphics class public class Welcome extends Applet { public void paint(Graphics g) { g.drawString(“Welcome World!”,25,25); } Web browser or appletviewer could execute code, but must be embedded in HTML file: The Java Language

35 Hello World Applet <html> <head>
<title> Sample HTML file for Welcome World</title> </head> <body> <applet code=“Welcome.class” width=275 height=35> </applet> </body> </html> The Java Language

36 Java Compilation & Exec.
appln.java compiler javac embed appln.class appln.html java appletviewer interpreter WEB browser The Java Language

37 Java Language Features
Comments Data Types primitive data types object data types (incl arrays) Operators Functions/Methods Expressions Control Structures Libraries The Java Language

38 Comments Three forms : /* comment */ // comment to end of line
/** documentation comment for javadoc tool */ The Java Language

39 Primitive Data Types Signed Integers: Characters: Floating point:
byte (8 bit, default: 0) short (16 bit, default: 0) int (32 bit, default: 0) long (64 bit, default: 0L) Characters: char (16 bit Unicode, default: 0) Floating point: float (32 bit, default: 0.0f) double (64 bit, default: 0.0d) Boolean: boolean (true/false, default: false) The Java Language

40 Arrays An array is a collection of variables of the same type
Card [] deck = new Card[52]; for (int i = 0; i < deck.length; i++) { deck[i] = . . . arrays are NOT container classes but an array does have some capabilities that appear as if they are objects: bounds checking, respond to messages double x[]= new double[12] ; int y = x.length; The Java Language

41 Arrays array indices start at 0;
if a programmer uses an index outside of the range an exception will be thrown. Programmer is not required to do all array access within a try block. The Java Language

42 Arrays Data Types Arrays are generated dynamically with new.
int[]A = new int[5];//allocates 5 items A[0]=11; A[1]=22; A[2]=33; A[4]=44; A[5]=55; Arrays are generated dynamically with new. int[] intvec = new int[100]; double [][] matrix1 = new doube[10][20]; double [][] matrix2 = new double[10][]; for(int i=0; i < 10; i++) matrix2[i] = new double[20]; An alternative way to create & initialize the array is: int[] A = {11,22,33,44,55}; The Java Language

43 Class Types In Java, all classes are actually subclasses of class Object. When we define a class: class MyClass { ..... } we are actually implicitly extending MyClass from class Object. The alternative way is : class MyClass extends Object The Java Language

44 Operators All computations performed with at least 32-bits precision.
==, !=, <, >, <=, >=, +, -, *, /, % (mod), ++, -- ,&& , || <<, >>, >>> (unsigned right shift), ~, &, |, ^ (xor) All computations performed with at least 32-bits precision. The Java Language

45 Type Hierarchy and Casting
Type hierarchy on primitive numeric types: byte<{short,char}<int<long<float<double Type casting From small to large possible but not necessary. long x = (long) 2 // (long) redundant From large to small necessary, but might lead to loss of precision. byte x = (byte) 257 // x == 1 No conversion from/to boolean. Use instead: b ? 1 : 0 and (x != 0) The Java Language

46 Methods/Functions Functions in Java are written in the form:
<type>fname(type1 para1 , .., typen paran ) { body } Consider sum-of-squares: sumSquares(m,n) = m2 + (m+1)2 + … + n2 In Java, can define function recursively as: int sumSquares(int m, int n) { if (m<n) { return m*m+sumSquares(m+1,n);} else {return m*m; } } Alternatively, using conditional expression: return ((m<n) ? m*m+sumSquares(m+1,n): m*m ) The Java Language

47 Expressions Variable and Array access : x, a[I]
Class and instance member access : C.x, obj.x Method calls : m(x,y), obj.m(x,y) Object creation : new C() Assignments : a=b Type-test : obj instanceof C Type-casts : (C) obj, (int) 1.0 Conditional expression : (x>0) ? 1 : -1; The Java Language

48 Control Flow & Operators
control statements mostly cloned from C++ differences: boolean type requires operands of &&, || etc. to be boolean while(1) not OK…while(true) is fine + is string concatenation I/O is not like C++ arrays are not like C++ The Java Language

49 Iteration (While Loop)
while (test) { // if test is true statements; // execute statement } // and repeat Example : int sumSquaresA(int m, int n) { int acc=0; while (m<n) { acc = acc+m*m; m++; } return acc; The Java Language

50 For Iterator Example : for (initialize; test; increment) { statements;
} Example : int sumSquares(int m, int n) { int acc; for (acc=0; (m<n); m++) { acc = acc+m*m; return acc; The Java Language

51 Do Loop It is possible to perform the body of a loop before its test
using a DO-loop: do { statements; } while (condition); The Java Language

52 Break & Continue To provide early exit from loop, we could use break, continue and return. break <label> - to exit from a loop continue <label>- to skip remaining statements and return to loop test return - to return to function’s caller Labelled breaks are allowed to exit over 2 or more loops. The Java Language

53 Other Control Struct. Blocks Selections of the form : {s1; s2; … ,sn}
In a given block, local variables can be declared whose scope is visible within the block. Selections if - else statement : if (condition) {statements} else {statements} Multi-way switch : switch (weekday) { case 0 : System.out.println(“Sunday”); break; case 1: case 2: case 3: case 4: case 5 : System.out.println(“Weekday”); break; case 6 : System.out.println(“Saturday”); break; default : System.out.println(“Invalid Days”); } The Java Language

54 Libraries Numerical types
The numerical data types all share some common methods, which their inherit from class Number. int intValue(); long longValue(); float floatValue(); double doubleValue(); Integer my_integer = new Integer(256); Long my_long = my_integer.longValue(); Float my_float = new Float(3.14); Double my_double = new Double (my_float.doubleValue()); System.out.println("Double : " + my_double); System.out.println("Integer: " + my_double.intValue() ); The Java Language

55 Character Type if (Character.isLowerCase( 'H' )) System.out.println ("Lowercase value detected"); else System.out.println("Uppercase value detected"); The character class offers a wide range of character comparison routines; the most useful are listed below : static boolean isDigit( char c ); static boolean isLetter( char c ); static boolean isLetterOrDigit( char c ); static boolean isLowerCase( char c ); static boolean isUpperCase( char c ); static char toUpperCase( char c ); static char toLowerCase( char c ); The Java Language

56 String Type Programmers who are familiar with C will understand a string as being an array of characters. Though Java has aspects of C/C++, the definition for a string differs strongly. Under Java, a string is a unique object, which has its own set of methods. Gone are the days of importing a string library, we simply invoke methods of a string object. Some of the more useful routines are listed : The Java Language

57 String Type // Returns the character at offset index
public char charAt(int index); // Compares string with another, returning 0 if there's a match public int compareTo(String anotherString); // Returns a new string equal to anotherString // appended to the current string public String concat(String anotherString); // Returns the length of the current string public int length(); // Returns true if the current string begins with prefix public boolean startsWith(String prefix); The Java Language

58 String Type // Returns true if the current string ends in suffix
public boolean endsWith(String suffix); // Returns the remainder of the string, starting from offset beginIndex public String substring(int beginIndex); // Returns a substring from offset beginIndex to offset endIndex public String substring(int bIndex, int eIndex); // Returns the current string, converted to lowercase public String toLowerCase(); // Returns the current string, converted to uppercase public String toUpperCase(); The Java Language

59 StringBuffer Type While strings are extremely useful, there are some tasks that require a more flexible sequence of characters. In cases where strings are being constantly modified, and appended to, it is not always efficient to simply recreate a string every time you wish to concatenate it with another. The StringBuffer class has an append method, which extends the capacity of the StringBuffer when required to accommodate varying lengths. The append method even allows you to add chars, booleans, integers, longs, floats & doubles. The Java Language

60 StringBuffer Type // Appends the string version of a boolean
public StringBuffer append(boolean b); // Appends a character to the buffer public StringBuffer append(char c); // Appends the string version of a integer public StringBuffer append(int i); // Appends the string version of a long public StringBuffer append(long l); // Appends the string version of a float public StringBuffer append(float f); // Appends the string version of a double public StringBuffer append(double d); // Appends the string version (toString method) of an object to the buffer public StringBuffer append(Object obj); The Java Language

61 StringBuffer Type // Appends the string to the buffer
public StringBuffer append(String str); // Returns the character at offset index public char charAt(int index); // Returns the current length public int length(); // Reverses the order of characters in the string buffer public StringBuffer reverse(); // Truncates, or pads with null characters, the buffer to a certain length public void setLength(int newLength); // Returns a string, representing the string buffer public String toString(); The Java Language

62 Class System The System class is perhaps one of the most important classes contained within the java.lang package, as this class provides us with the input and output streams. Without these, it would be very difficult to interact with the user! public static InputStream in; public static PrintStream out; public static PrintStream err; The Java Language

63 Class System The System class also has some interesting methods which are of use to Java programmers. public static void exit(int status) public static String getProperty(String key); The Java Language

64 System.exit Exit allows a Java programmer to immediately terminate execution of the program, and to return a status code. By convention, a non- zero status code indicates an error has occurred, and on PC systems, should set the appropriate DOS errorlevel. If your Java application has been run from a batch file, you can actually test to see if it has executed correctly. The Java Language

65 System.exit class Test { public static void main(String args[])
} @echo off REM Execute Test.class java Test if ERRORLEVEL 6 echo An error has occurred Please restart The Java Language

66 System.getProperty Another useful method from the System class is getProperty. Via the getProperty method, a Java application can gain information about the operating system under which it is running, the vendor and version of the Java virtual machine, and even the user name and home directory path of the current user under Unix based systems. Some of the more common system properties are listed in the table below: The Java Language

67 System.getProperty java.version - Java version number
java.vendor - Java-vendor-specific string java.vendor.url - Java vendor URL java.home - Java installation directory java.class.version - Java class format version number java.class.path - Java classpath os.name - Operating system name os.arch - Operating system architecture os.version - Operating system version The Java Language

68 System.getProperty file.separator - File separator ("/" on Unix)
path.separator - Path separator (":" on Unix) line.separator - Line separator ("\n" on Unix) user.name - User account name user.home - User home directory user.dir - User's current working directory The Java Language

69 System.getProperty Accessing the system properties is as simple as calling the static getProperty method and passing a key from the table as a parameter. An example is shown below, which displays the operating system of the computer it is running on. class GetPropertyDemo{ public static void main(String args[]) { // Display value for key os.name System.out.println(System.getProperty("os.name")) } The Java Language

70 Object Oriented Programming in Java
Chapter 3 Object Oriented Programming in Java Classes & Object Bank Account Example ADT Inheritance Overloading Interfaces Packages Object Oriented Programming in Java

71 Classes & Objects Fields are data variables associated with a class or with instances of the class primitive data (int, double, …) object data ( BigInteger r ) Methods provide execution behavior and operate on the data fields Classes and Interfaces can be members of other Classes or Interfaces. Object Oriented Programming in Java

72 Creating Objects Objects are primitive or user defined.
Primitive objects are by value, user defined objects are references. User defined Objects are created with constructors and the “new” keyword. Point center = new Point(4.0,5.9); Compiler provides a default constructor. Object Oriented Programming in Java

73 Constructor A call to new C() generates a new C-object.
The object is initialised by calling the constructor method C() in class C. The result is a reference to a new object of class C. Constructor method for a given class can be overloaded, but must use distinct parameter lists. Object Oriented Programming in Java

74 Destructor ? Formal Destructors not part of language but exist in two ways: finally blocks may follow try blocks to clean up regardless of how a try block is exited (exception or normally) finalize() methods invoked by the garbage collector thread. When there are no active references to an object storage is automatically reclamed by a garbage collector thread running in the background. Object Oriented Programming in Java

75 Methods and Parameters
methods operate on the data fields of a class. methods have zero or more parameters and may return values or be void. a methods name, number of parameters and their type make up the signature of the method. two methods may share a name if they have different signatures. Object Oriented Programming in Java

76 Storage and Methods storage should be private
methods “look” inline, but there is nothing meaningful about “inline” for uncompiled languages class ASimpleClass { int aVariable; // field boolean aMethod() { // method if (aVariable==0) { aVariable++; return true; } else { return false; } } ASimpleClass(){aVariable = 0;}//constructor Note there is nothing about visibility (yet) Object Oriented Programming in Java

77 Static Fields static fields in a class or interface belong to the class. If there are instances of a class with static data fields then all instances share the static data fields static methods are invoked using the class name. Object Oriented Programming in Java

78 Invoking a Method a non-static method is invoked using an object of the class and the “dot” operator. Point p = new Point(3.2,3.3); p.clear(); the object on which the method is invoked is the “receiver”. The method is a “message” to the object. Object Oriented Programming in Java

79 this the keyword “this” refers to the current receiving object.
public void clear() { this.x = 0.0; y = 0.0; // this is assumed } Object Oriented Programming in Java

80 Bank Account Example class BankAccount { protected int balance;
public int withdraw(int amount) { if (balance > = amount) balance = balance-amount; return balance; } public int deposit(int amount) { balance = balance+amount; return balance; BankAccount (int amount) { balance = amount; } BankAccount () { balance = 0; } Object Oriented Programming in Java

81 Abstract Data Type Procedure abstraction is achieved by:
treating function as black box Data abstraction is based on two key techniques Data Encapsulation - keeping data and operations together in one location Information Hiding - restricting visibility of implementation details to where needed. function as black box Why Information Hiding? Help manage software complexity Isolate dependencies for easier Software Maintenance Object Oriented Programming in Java

82 Complex Class Information can be hidden by private qualifier for both data and methods. class Complex { private float re; private float im; public void add(Complex a){re=re+a.re;im=im+a.re;} public void mult(Complex a) { ...;} Complex (float r, float i) { re = r; im =i; } } Can use as follows: Complex z = new Complex(1.0,2.0);//z = (1.0,2.0) z.add(new Complex(3.0,2.0));//z = z+(3.0,2.0) z.mult(new Complex(2.0,1.0));// z = z*(2.0,1.0) Object Oriented Programming in Java

83 Changing the Complex Class
class Complex { private float radius; private float angle; public void add(Complex a ) { .. .; } public void mult(Complex a) {...;} Complex (float r, float i) { .. } public static Complex makePolar(float rad, float ang) { Complex t = new Complex(); t.radius = rad; t.angle = ang; return t; } unchanged interface new implementation new constructor Object Oriented Programming in Java

84 Polymorphisms in Java Polymorphism means “many shapes” in Greek. In programming languages,they refer to the ability of code to be versatile/generic/reusable. Three types of polymorphisms in Java are: Overloading (ad-hoc) Overriding/Subtyping (class) Genericity via topmost Object & TypeCasting (parametric) Object Oriented Programming in Java

85 Inheritance Classes may extend other classes.
variables of a subclass with the same name as those of a superclass shadow the superclass storage. a method of a subclass with the same signature as that of a superclass overrides the superclass method. objects of a subclass may be used in superclass variables. Classes may extend only one class. If a class does not extend a class by default it extends the class Object. Object Oriented Programming in Java

86 Inheritance the keyword super refers to the superclass.
super() is an ancestor constructor call from within a class as in C++ variables are shadowed unlike C++ methods are polymorphically bound by default (that is, every method is virtual) overridden methods may be invoked as super.method() Object Oriented Programming in Java

87 Inheritance General form : No multiple inheritance.
class X extends Superclass No multiple inheritance. Every class (except : java.lang.Object) has exactly one superclass. If no extends clause is given, then Object is assumed. Extension has two effects: It creates a subtype It includes all declarations of the extended class (superclass) in the extending class (subclass), unless they are overriden. Object Oriented Programming in Java

88 Method Overriding An extending class inherits all fields and methods of the class it extends. It may redefine some inherited methods - this process is called overriding. class Base { print(Object x) { System.out.println(x); } } class Sub extends Base { PrintStream log = … ; print(Object x){log.println(x);} What is the effect of? Base x = new Sub(0); x.print(“hello”); Object Oriented Programming in Java

89 Inherit the Bank Account
class CurrentAcct extends BankAccount { private int overdraft; public void SetOD(int amt) {overdraft = amt } public int withdraw(int amount) { if (balance+overdraft > = amount) balance = balance-amount; return balance; } CurrentAcct(int amt, int d) {super(amt); overdraft = d; } CurrentAcct(){super(0);overdraft =0;} Object Oriented Programming in Java

90 Using Static fields/methods
class SavingAcct extends BankAccount { protected static float interest; public static SetInterest(float amt) {interest = amt }; public int AddInterest() { balance=balance+((balance*interest)/365); return balance; } SavingAcct (int amt) { super(amt); } SavingAcct () { super(0); } Note that static methods cannot access non-static class members Object Oriented Programming in Java

91 Final Class/Method/Object
Variables declared final cannot be modified, and must be initialized during declaration: final int luckynumber = 8; A method that is final cannot be overriden in a sub-class. This means that the function is statically bound and can be inlined. A class that is declared final cannot be s superclass. That is they cannot be inherited. Object Oriented Programming in Java

92 Abstract Method/Class
Objects of some classes, known as abstract classes, are not meant to be instantiated. Each such abstract class contains one or more abstract (uninstantiated) methods. abstract class shape { private Point center; abstract void draw () { }; } Even though a class is abstract, it may still contain instance data and non-abstract methods Object Oriented Programming in Java

93 Subtyping If class X extends class Y. X is said to be a subclass of Y.
By subtyping principle, an instance of X can be used wherever an instance of class Y is expected. Because of subclassing, the static (declared) type of a variable might differ from the dynamic type of the runtime value it contains. The dynamic type should be a subtype of the static type. class X extends Y { … } X anX; Y anY; aY = anX; // OK anX = (X)aY; // explicit type conversion needed Object Oriented Programming in Java

94 Procedure vs Subtyping
Programming with procedures draw (shape[] f) { for (i=0; i<=f.length; i++) { switch (f[i].kind) { case line: drawline(f[i]); break; case rectangle: drawrect(f[i]); break; case circle: drawcircle(f[i]); break; default: println (“Error “); } Problem - Need to change this procedure whenever a new shape is added Object Oriented Programming in Java

95 SubTypes Programming with Subtypes :
draw (shape[] f) { for (i=0; i<=f.length; i++) { f[i].draw() } Each shape can have its own draw procedure. Add new shape & procedure together as an encapsulated unit. Subtype Principle : An object of a subtype can appear wherever an object of a supertype is expected. Object Oriented Programming in Java

96 Typecasts & Typetests A type conversion (C) expr checks whether the dynamic type of expr is (a subtype of) class C. If not, a ClassCastException is raised (see Exception topic later). A type test expr instanceof C checks if the dynamic type of expr is (a subtype of) class C. Object Oriented Programming in Java

97 Typecasts & Typetests Example: class String { …
boolean equals(Object other) { if (other instanceof String) { String that = (String) other; if (this.len != that.len) return false; for (int i=0; i<this.len; i++) { if (this.charAt[i] != that.charAt[i]) return false; return true; } return false; Object Oriented Programming in Java

98 Overloading It is possible to use the same method name with different argument lists. void print (String x) { … } void print (Exception x) { … } void print (int x) { … } void print (int x, int precision) { … } Here, argument types will determine which method to use. Unlike overriding, overloading uses the static types of argument. Object Oriented Programming in Java

99 Generic Codes in Java ? Consider:
class Pair { int x; int y; Pair (int a, int b) {x = a;y = b;} void swap() { int temp; temp = x; x = y; y = temp; } Need to duplicate code if we have to deal with char, arrays, etc. Object Oriented Programming in Java

100 Answer : Objects Class Possible use: Potential Problem: class Pair {
Object x; Object y; Pair (Object a, Object b) {x = a; y = b; } void swap(){ Object temp; temp = x; x = y; y = temp; } Possible use: p = new Pair (new Integer(3),new Integer(5)); p.swap(); Potential Problem: Pair (new Integer(3), “IC102S”); Object Oriented Programming in Java

101 Interfaces Interfaces specify operations to be supported without implementing them. Components of interfaces: methods constants Unlike classes, no method implementation, nor variables. Object Oriented Programming in Java

102 Interfaces For example, can treat storage devices such as memory, tapes, disk through the following interface: interface Storable { int READ =0; int WRITE = 1; byte[] get(); put(byte[] data); int lastOp(); // returns READ or WRITE; } Write Only Object Oriented Programming in Java

103 Interfaces Interfaces define the methods that may be used but do not specify instance storage. interface ConstAccount { double getBalance(); } class Account implements ConstAccount { double d_ = 0.0; void setBalance(double d) {d_ = d;} double getBalance() { return d_;} Object Oriented Programming in Java

104 Interafces All methods in an interface are implicitly public and abstract. All constants are implicitly public, static, final. Interface can inherit from several other interfaces. The following is a convenient hack for accessing constants without the class qualifier. interface Colors { int Red =0; int Green = 1; int Blue = 2; } class C implements Colors ... Object Oriented Programming in Java

105 Multiple Ineritance (?)
One primary motivation for interface is to provide functionality of multiple inheritance, without the problem of name-clashes. Both FlyingMachine and FloatingVessel may have the navigate() methods, resulting in a name-clash. Interface can avoid this problem. class FlyingMachine class FloatingVessel class Seaplane Object Oriented Programming in Java

106 Solution by Interface interface FloatingVessel {
int navigate(Point f,Point t); void dropAnchor(); void liftAnchor(); } interface FlyingMachine { int navigate(Point f,Point t); void land(); void takeoff(double fuel); } class Helicopter implements FlyingMachine { int navigate(Point f,Point t){ … }; void land() { … }; void takeoff(double fuel) { … }; void hover() { … }; } class Seaplane implements FloatingVessel,FlyingMachine { int navigate(Point f,Point t) { … }; void land() { … }; void takeoff(double fuel) { … }; void dropAnchor() { … }; void liftAnchor() { … }; } Object Oriented Programming in Java

107 Interfaces vs Abstract Classes
abstract class X { public abstract int foo() { } } public interface X { public int foo(); Object Oriented Programming in Java

108 Packages packages are Java’s way to manage name spaces.
Packages are implemented as directories within a file system. When package names must span systems, the common practice is to reverse the internet domain name import COM.Sun.games; import is not inclusion and is only for the compiler. Class paths are used to find the class information at run time. Object Oriented Programming in Java

109 Packages Classes are organized into packages.
Most implementation let packages correspond to file directories A packages clause: package myGroup.myPackage at the beginning of a .java file declares all classes in the file to be members of that package Object Oriented Programming in Java

110 Import/Scope Rules Tedious to use fully qualified name all the time. Can use import clause to allows short names. import java.io.File import java.io.* Scope rules all variables need to be declared local variables visible from point of declaration until end of block class fields and methods visible everywhere in class let you use File instead of java.io.File makes available all files in java.io in the unqualified form. Object Oriented Programming in Java

111 Modifiers (summary) public - visible everywhere
protected - visible in all subclasses & in same package package(default)- visible in same package private - visible only in same class . static - once per class, rather than per object final - methods cannot be overridden, fields cannot be reassigned abstract - methods : implementation deferred synchronized - methods : for concurrency native - methods : non-Java code volatile - fields : might change from outside program Object Oriented Programming in Java

112 Data Structures ADT Examples
Chapter 4 Data Structures ADT Examples Stack Queue Trees Data Structures ADT Examples

113 Data structures in Java
Java provides a set of data structures… well, we can implement a set of data structures using Java. There is a major difference between C/C++ and Java dynamic data structures (C/C++ uses pointers) static data structures (no pointers, however this does not prevent us from implementing data structures in Java) Data Structures ADT Examples

114 Stack Class Stack (LIFO data structure) can be implemented as the following Class: class Stack { …. Stack() { … } boolean empty() { … } void push(Object o) { … } Object pop() { … } Object peek() { … } } An application - check if balanced parentheses, e.g. (a+sin(x)-A[i-j])/(cos(x)+{p-q}/{m-n}) Data Structures ADT Examples

115 An Application - Balanced Parenthesis Checking
class ParenMatcher { …. private boolean match(char c,char d) { switch(c) { case ‘(‘ : return (d==‘)’); case ‘[‘ : return (d==‘]’); case ‘{‘ : return (d==‘}’); default : return false; } Data Structures ADT Examples

116 ...Parenthesis Checking public void parenMatch() {
Stack s = new Stack(); int n = inputString.length(); int i= 0; char c,d; while (i<n) { d=inputString.charAT(i); if (d==‘(‘ || d==‘[‘ || d==‘{‘) s.push(new Character(d)); else if (d==‘)‘ || d==‘]‘ || d==‘}‘) if (s.empty()){ output(“More right parenthesis than left”); return;} else {c = ((Character)s.pop()).charValue(); if (!match(c,d)){ output(“Mismatched parenthesis”); return;}} ++i;} } Data Structures ADT Examples

117 Array Implementation (for Stack)
capacityIncr itemArray count capacity class Stack { private int count, capacity, capacityIncr; private Object[] itemArray; public Stack() { count=0; capacity=10; capacityIncr=5; itemArray = new Object[capacity]; } Data Structures ADT Examples

118 Stack Methdos public Object pop(){ if (count==0) return null;
public boolean empty() {return (count==0); } public Object pop(){ if (count==0) return null; else {return itemArray[--count];} } public Object peek(){ if (count==0) { return null; } else {return itemArray[count-1];} Data Structures ADT Examples

119 More Methods public void push(Object ob) { if (count==capacity){
capacity += capacityIncr; Object[] tempArray = new Object[capacity]; for (int i=0; i<count; i++) {tempArray[i] = itemArray[i];} itemArray=tempArray; } itemArray[count++]=ob; Data Structures ADT Examples

120 Linked-List Implementation (for Stack)
item link An Object class StackNode { Object item; StackNode link; } Data Structures ADT Examples

121 Stack Class class Stack { private StackNode topNode;
public Stack() { topNode=null; } public boolean empty() {return(topNode==null);} public Object pop() { if (topNode==null) { return null; } else { StackNode temp=topNode; topNode=topNode.link; return temp.item; } Data Structures ADT Examples

122 More Methods public Object peek() { if (topNode==null) return null;
else return topNode.item; } public void push(Object ob) { StackNode newNode = new StackNode(); newNode.item = ob; newNode.link = topNode; topNode = newNode; Data Structures ADT Examples

123 Queue Class Stack (LIFO data structure) can be implemented as the following Class: class Stack { …. Queue() { … } ; boolean empty() { … }; void insert(Object o) { … };// at back Object remove() { … };// from fornt } Useful for simulation, etc. Queue on a Circular Track Advance front & rear one, as follows: front=(front+1) % size; rear=(rear+1) % size; front rear A B C D E F G count 7 Data Structures ADT Examples

124 Circular Array Implementation (for Queue)
class Stack { private int front,rear,count,capacity, capacityIncr; private Object[] itemArray; public Queue() { front=0; rear=0; count=0; capacity=10; capacityIncr=5; itemArray = new Object[capacity]; } public boolean empty() {return (count==0); } public Object remove() { if (count==0) { return null; } else {Object tempitem = itemArray[front]; front=(front+1) % capacity; count--; return tempitem;} } Data Structures ADT Examples

125 More Methods public void insert(Object ob) { if (count==capacity){
capacity+=capacityIncr; Object[] tempArray = new Object[capacity]; ..copy to new array & assign to itemArray.. } itemArray[rear]=ob; rear=read+1 % capacity; count++; Data Structures ADT Examples

126 Trees Trees are useful for organising complex data & for representing expressions. root Level 0 * internal nodes Level 1 fact if Level 2 5 7 4 > Level 3 leaves n 5 Data Structures ADT Examples

127 Binary Trees A binary tree is either an empty tree, or a node whose left and right subtrees are binary trees. class TreeNode{ Object info; TreeNode left, right; TreeNode(Object ob, TreeNode l,r) {info=ob;left=l;right=r;} TreeNode(Object ob) {info=ob;left=null;right=null;} } data constructor Data Structures ADT Examples

128 Creating a tree: TreeNode t1=new TreeNode(“/”,new TreeNode(“6”),new
* + / 6 7 3 8 empty trees t2 t1 Data Structures ADT Examples

129 Tree Traversals There are three common ways of tree traversals
pre-order traversal in-order traversal post-order traversal Data Structures ADT Examples

130 preOrder(t2) * 8 + / 6 3 7 inOrder(t2) 8 * 6 / 3 + 7 post-Order(t2)
void preOrder(TreeNode t) { if (t!=null) { process(t.info); preOrder(t.left); preOrder(t.right); } preOrder(t2) * 8 + / 6 3 7 void inOrder(TreeNode t) { if (t!=null) { inOrder(t.left); process(t.info); inOrder(t.right); } inOrder(t2) 8 * 6 / 3 + 7 void postOrder(TreeNode t) { if (t!=null) { postOrder(t.left); postOrder(t.right); process(t.info); } post-Order(t2) 8 6 3 / 7 + * Data Structures ADT Examples

131 Data for Binary Search Tree
Node and BST declarations. class TreeNode{ CompareKey key; TreeNode left; TreeNode right; } class BinarySearchTree { private TreeNode rootNode; public BinarySearchTree() {TreeNode = null} … // methods static TreeNode find(TreeNode t, CompareKey k) {…} void insert(CompareKey k) {…} Data Structures ADT Examples

132 CompareKey Interface For polymorphism, BST stores Objects. However their keys need to be comparable. Hence, we should define an interface of the following . interface CompareKey { // if k1 & k2 are CompareKeys, then k1.compareTo(k2) // returns either // 0, +1, -1 according to k1==k2, k1>k2, or k1<k2 in the // ordering defined int compareTo(CompareKey value); } Data Structures ADT Examples

133 IntegerKey class IntegerKey implements CompareKey{
private Integer key; … //additional data possible IntegerKey(Integer value) {key=value); IntegerKey(int value) {key=new Integer(value)); public int compareTo(CompareKey val){ int a = this.key; int b = ((IntegerKey)val).key; if (a.intvalue == b.intvalue) return 0; else return (a.intvalue < b.intvalue) ? -1 : +1 ; } Data Structures ADT Examples

134 BST Method : Find a Node To find a node in a BST, we have:
static TreeNode find(TreeNode t, CompareKey k) { if (t==null) return null; else if ((result=k.compareTo(t.key))==0) return t; if (result >0) return find(t.right,k); return find(t.left,k); } Data Structures ADT Examples

135 BST Method : Insert a Node
a recursive insertion function: void insert(CompareKey k) { rootNode = insertKey(rootNode,k); } private static TreeNode insertKey(TreeNode t,CompareKey k) { if (t==null) { TreeNode n = new TreeNode(); n.key = k; return n; } else if (k.compareTo(t.key)>0 { t.right = insertKey(t.right,k); return t; } else { t.left = insertKey(t.left,k); Data Structures ADT Examples

136 Exceptions Handling Chapter 5 What is Exceptions Exceptions Clause
Exceptions Hierarchy Exceptions Handling

137 What is Exceptions Exceptions signal uncommon situations, such as divide-by-zero, arrays-subscript-out-of-bound. In Java, exceptions are objects which need to be created explicitly. IOException myFault = new IOException(“write error”); Exception types inherit from: java.lang.Exception. Throwing an exception aborts execution. Example : throw myFault; Often, creating and throwing an exception can be combined. throw new IOException(“write error”); Exceptions Handling

138 Why Exceptions Provides safer programming by providing distinct paths to deal with errors. Allows separation of error-handling, from its occurrence. Useful for separately developed components. Main use is getting decent error message out. It is a bit too much to expect recovery. Graceful degradation is often a more realistic expectation. Throwable class consist of : Throwable Exception Error Exceptions Handling

139 Exceptions Clause Exceptions can be caught and handled by a try statement. try { } catch (Exception1 e1) { … } catch (Exception2 e2) { … } Catch clauses are tried in sequence. The first clause that matches the thrown exception is executed. Exceptions Handling

140 Finally An optional finally section in the try statement contains code that will be executed whether an exception is raised or not. try { A; } finally { B } The above is equivalent to : try { A; B; } catch (Throwable ex) { throw ex; } Note the use of Throwable to capture all exceptions/errors, and the re-throw of ex after performing B. Exceptions Handling

141 Throws To explicit declare exceptions which may escape from a method, Java requires that each method must either (i) catch the exception it throws, or (ii) declares it as part of its throws clause. A throws clause thus lists the exceptions that can be thrown (but not handled) by a method. int g(float h) throws a, b, c { … // method body } Exceptions Handling

142 Throws If an exception raised is not from its throws list (or their subclasses) or caught by a try-block, a syntax error is reported. For example, in the above: int g(float h) throws a, b, c { … throw d … //syntax error if d is not covered by a,b,c or //caught by a try-block within g } Exceptions Handling

143 Exceptions Hierarchy A sample of the possible types of exceptions
ClassNotFoundException InterruptedException RuntimeException ArithmeticException IndexOutofBoundsException ArrayIndexOutofBoundsException StringIndexOutofBoundsException NegativeArraySizeException NullPointerException IOException EOFException FileNotFoundException InterruptedIOException exceptions which could be avoided Exceptions Handling

144 Useful Methods Two useful methods inherited from Throwable class are:
String getMessage() {}; To print message associated with exception void printStackTrace() {}; To cause call chain where exception is thrown to be printed Exceptions Handling

145 Example class exeptionTest { static int slice0[] = {0,1,2,3,4};
public static void main(String[] a) { try { letsDoSomeNuts(); } catch (Exception e) { System.out.println(“caught exception in main()”); e.printStackTrace(); } static void letsDoSomeNuts() { try { slice0[-1] = 4; } catch (NullPointerException e) { System.out.println(“caught a different exception”); Exceptions Handling

146 The Output: exception detected call chain trace at the
caught exception in main() java.lang.ArrayIndexOutOfBoundsException: -1 at exceptionTest.letsDoSomeNuts(exceptionTest.java:19) at exceptionTest.main(exceptionTest.java:9) call chain trace at the point the exception is raised (not where it is handled)

147 Chapter 6 Applets and HTML Overview HTML tags for Applets
Applet Life Cycle Applet Class JAR files

148 Overview application: A class containing a method that is declared:
static public void main(String [] args) applet: A class derived from java.applet.Applet java.lang.Applet is not an interface. Thus single inheritance says that your applet may not extend any other classes. Intent of applet design was to give dynamic content to Web pages by running on a virtual machine built into a web browser.

149 Overview Web browser’s VM uses a security manager to deny any machine operations that could do anything harmful, and restricts access within the applet to the web server (to dynamically download classes as needed) Web servers/clients : client requests browser to receive a page using a URL that specifies the protocol (http), a location (ext-studies.haifa.ac.il), a port, and a page index.html is a page indicating presentation formatting (html) to a browser.

150 HTML Tags for Applet Line breaks and indentation in a web page have no meaning and exist solely for human readability. Browsers format web pages using tags which are indicated by surrounding a name in <name > and closed with a tag </name> tags such as <P> indicate a new paragraph (no </P> required since the next <P> tag closes the previous <P>) Tags <A href=“some url here”> visible link </a> allow a web page to request the download of yet another page.

151 HTML Tags for Applet For our purposes, we are interested only in putting java programs on HTML pages. Applet tags were introduced into HTML to indicate the inclusion of a java program. A minimal HTML page containing an applet would be: <HTML><BODY> <APPLET code=“name.class” height=value width = value> </APPLET> </BODY></HTML>

152 More Tags <HTML><HEAD>
<TITLE>Slide Viewer Applet</TITLE> <!-- Changed by: Bina, Aug > </HEAD> <CENTER> <H2> Images </H2> </CENTER> <BODY BGCOLOR="#000000" text="#ffffff" link="#00caFF"> <APPLET CODE=SlideProjector.class WIDTH=250 HEIGHT=450 ALIGN=TOP> <PARAM NAME=width VALUE=250> <PARAM NAME=height VALUE=450> <PARAM NAME=SLIDE0 VALUE="3.JPEG"> <PARAM NAME=SLIDE1 VALUE="4.JPEG"> <PARAM NAME=SLIDE2 VALUE="6.JPEG"> <PARAM NAME=SLIDE3 VALUE="8.JPEG"> </APPLET><BR>

153 Applet Life Cycle the browser downloads the class in the applet tag and calls an init() method. This is where you initialize your program the browser calls the start() method. This method starts your program running, and will be called whenever the applet needs restarting. The stop() method is called when the web page is replaced by another page. Before a browser terminates an applet it will call the destroy() method of the applet. It is not required that methods of your applet override any of these methods.

154 Applet Class Your applets extend Applet which has methods other than start, stop….methods providing functionality that is useful to programs in web pages. Every Applet is a Panel which is a Container which is a Component which is an Object meaning that applets inherit methods from these classes as well (e.g. paint() )

155 Applet Useful Methods Those that interact with browser
URL getDocumentBase() returns a URL object that has methods that allow you to deal with the base of the web page. URL getCodeBase() contains the URL of the applet, which could differ from the Document base. String getParameter(String name) returns the value of a parameter in the applet tag.

156 More Methods Those that provide Media Support Image getImage(URL)
Image getImage(URL,name) AudioClip getAudioClip(URL url), .. void play(URL), …

157 More Methods Those that interact with the browser environment
AppletContext getAppletContext() returns an instance of the AppletContext class that allows an applet to affect its environment in limited ways void showDocument(URL) replaces the current web page with the URL. ...

158 More Methods Those that provide applet information
String getAppletInfo() Of the methods in ancestor classes, the paint(Graphics g) method is probably the most useful, as overriding this method gives the programmar a Graphics object that can be used to draw in the applet.

159 Current Applet Issues Classes used in applet programs are loaded individually in order as needed. This is both a strength (don’t need 100 Mbytes of class so never loaded) and a weakness ( loading a class when needed takes a performance hit)

160 Solutions load a basic collection of classes to get started, and while the user is interacting with the basic interface,other classes in another thread with lower priority can download other classes. When you wish to load a large number of classes at one time, use JAR files.

161 JAR Files Utility named jar creates a gzipped file of classes. (Jar files can be dealt with by utilities such as winzip) but have the command line semantics of “jar” in the command line : jar cf name.jar *.class image.gif sound.au in the HTML file: <applet archive=“name.jar” code=“whatever.class” height= width= >

162 Threads Chapter 7 Threads & Processes Multi Threading Class Thread
Synchronized Methods Wait & Notify

163 Threads A thread is a single sequential flow of control within a program. A Thread A Program

164 Processes A process refers to a single sequential flow of control with its own resources. Thread s shares the same data segment. Also referred to as execution context or a lightweight process. Two Thread A Program

165 Multi threads Applications
A server providing services to others. One thread for each client. (network server) A real-time control computer controlling a factory. One thread for each device that needs monitoring. Graphical interfaces. Create a more responsive GUI. A separate thread to react to user events. A separate thread to do intense computation.

166 MultiThreaded Code in Java
Subclassing Thread class and overriding run Public class SimpleThread extends Threads { public SimpleThread(String str){super(str);} public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) { } } System.out.println("DONE! " + getName()); } … }

167 Running it public static void main (String [ ] a) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); } 0 Jamaica 0 Fiji 1 Jamaica 1 Fiji 2 Jamaica 3 Jamaica 2 Fiji 4 Jamaica 3 Fiji 5 Jamaica 4 Fiji 5 Fiji 6 Jamaica 6 Fiji 7 Jamaica 7 Fiji 8 Fiji 9 Fiji 8 Jamaica DONE! Fiji 9 Jamaica DONE! Jamaica

168 Implementing Runnable
Most times you need to subclass a class other than thread. applet Implement runnable implement run method create object create a new Thread using the constructor that expects a runnable object start the thread

169 Another Version Implementing runnable Public class SimpleRun implements Runnable { public void run() { for(int i = 0; i < 10; i++){ System.out.println(i + " " Thread.currentThread().getName()); try { Thread.sleep((int)(Math.random()*1000)); }catch (InterruptedException e) { } } System.out.println("DONE! " Thread.currentThread().getName()); } … }

170 Running it public static void main (String [] a){ new Thread(new SimpleRun(),"Jamaica").start(); new Thread(new SimpleRun(),"Fiji").start(); } 0 Jamaica 0 Fiji 1 Jamaica 1 Fiji 2 Jamaica 3 Jamaica 2 Fiji 4 Jamaica 3 Fiji 5 Jamaica 4 Fiji 5 Fiji 6 Jamaica 7 Jamaica 6 Fiji 7 Fiji 8 Fiji 9 Fiji 8 Jamaica 9 Jamaica DONE! Jamaica DONE! Fiji

171 States of a Thread sleep,suspend ,wait methods The Thread is blocking on I/O Calling a sychronized method running yield() same as the schedulers action start New Thread Blocked Runnable The run method terminates. The stop method ... Dead

172 Class Thread Constructors Control Threads
Thread(String),Thread(Runnable), Thread(Runnable, String) Control Threads start( ), yield( ), sleep(long millis) getName( ) Debugging Threads - toString(), countStackFrames( ), dumpStack() Warning --- Java 1.2 has deprecated stop( ), suspend( ), resume( ) and destroy( )

173 Synchronized Methods Consider A Bank account program:
class Account { int balance = 0; … void withdraw (int w) { int temp = balance; balance = temp - w; } void deposit (int d) { int temp = balance; balance = temp + d; } int balance(){ return balance; } }

174 The Easy Way to get Rich Same account referenced by two "tellers". race hazard or race condition: Balance = 100 a = getAccount("123"); b = getAccount("123"); a.withdraw(10); b.withdraw(5); temp = balance; temp = balance; balance = temp - 10; balance = temp - 5; The value of balance could be 90,95, or 85

175 The Race Condition The race condition happens because threads have their own program counter and runtime stack BUT share the process address space and "global" variables. Eliminating this condition is called the mutual exclusion problem. Monitors are the built-in synchronization primitives in Java.

176 Use Synchronized Methods
If in the code for Account, the methods “withdraw,” “deposit” and “balance” were all synchronized synchronized void withdraw(…) synchronized void deposit(…) synchronized void balance(…) The data would be protected and work as follows:

177 Obtaining the lock Thread call deposit account object t
When a synchronized method is called, the caller has to obtain the object’s lock before the method is executed: If the lock is not free, the calling thread waits. Thread call deposit account object t

178 The Lock is Free If the lock is free the thread continues and executes the code in the method: Thread call deposit account object t

179 The Lock was Free... Thread account executing object deposit code t
As soon as the call starts the lock is closed: When you have obtained the lock and are executing one synchronized method, you are able to call other synchronized methods from that one, without deadlock… because you have the lock ! Thread account object executing deposit code t

180 The Lock is Closed Thread account object finished executing deposit t
Any other threads that call a synchronized method of the “account object” have to wait Thread account object finished executing deposit t

181 The Lock Become Free Thread account object start deposit code t
When the thread that has the lock completes execution of “deposit,” the lock becomes free When the lock opens one of the waiting threads will begin Thread account object start deposit code t

182 Synchronized Blocks A “critical section” is the part of the code of a method where shared data is accessed in mutual exclusion The “critical section” of a method may only be a small part of the code in the method Small parts of a method may be synchronized on the object’s lock class onLineTicketing { void reserveTicket { … //fill date/price info synchronized(this){…//reserve the seat} … //sell ticket, get money synchronized(this){…//confirm reservation} }

183 Synchronizing on other Objects
There is no limitation on which objects can be used for synchronization void aMethod { … synchronized(obj){ …//use lock of “obj” } …}

184 wait() and notify() When a method executes wait(), it gives up the lock of this object, i.e. the one executing the method In a block synchronized on “obj” the call obj.wait() gives up the lock of “obj” synchronized <type> methM { …//we have the lock try{ wait();//give up the lock //“wait()” = “this.wait()” }catch(InterruptedException e){} …

185 Cold Storage The compiler makes sure you only call wait() in code that has the lock You can only call wait() in a synchronized method or a synchronized block If you go into the storage using wait(), you stay there until someone else calls notify() or notifyAll() for THAT lock

186 notify(), notifhyAll()
If several threads are waiting in the same storage, a single notify() only frees one of them You do not know which one is freed After being freed, the thread has to get the lock back to continue processing If it makes sense to do that, you can call notifyAll( ) to free ALL the threads currently waiting in storage In that case you cannot know the order in which the freed threads will run

187 Drawbacks of Multithreading
Complexity introduced starvation racing deadlock Waiting for shared resources could slow execution Managing threads require additional CPU overhead

188 GUI in JAVA - The AWT Chapter 8 Goals AWT Components Layout Managers
Frame Example Applet Example GUI in Java - The AWT

189 Goals First learn about the different objects that you can put on the screen Second address their associated events and provide event handling Almost all visual components are ultimately residing in a frame or panel Frame - for application; Panel - for applet. GUI in Java - The AWT

190 Goals Understand event handling for AWT components
Understand the widgets available in Java Understand how widgets must be attached to containers Understand how “layout managers” support positioning

191 AWT - Abstract Windowing Toolkit
AWT can be used by both, applets and self-standing applications. Is a standard component of the Java Development Kit (JDK) Support for mouse keyboard event handling

192 AWT Components Button - pushbutton, Label Canvas - blank for drawing
Checkbox - togglebutton Choice - Drop-down list, option menu Component - root of the hierarchy (can be subclassed in 1.1) FileDialog - supports browsing and selecting files List - a list of selectable items

193 More Components Scrollbar - slider for scrolling
TextArea - a multi-line area for displaying and editing text TextField -a single-line text area CheckboxMenuItem - toggle button in a menu Menu - pulldown(or tear-off menu) MenuBar - component to hold pulldown menues MenuComponent - root of the menu component hierarchy MenuItem - a menu button PopupMenu - (1.1 only)

194 Container Components Container - root of hierarchy (abstract - not displayable) Dialog - suitable for dialog boxes Frame - top-level window that can contain a menubar Panel - empty toplevel container (parent of applet) ScrollPane (1.1container that scrolls contents) Window - no border. no menubar- parent of Frame and Dialog.

195 Layout Managers Layout managers specify a policy for widget arrangement BorderLayout - max of 5 components NORTH,SOUTH,EAST,WEST,CENTER default layout for Windows and its subclasses Frame and Dialog FlowLayout - components are placed centered and left to right in a row new row started when previous row is full default layout for Panels and subclass Applet.

196 More Layout Managers GridLayout - an n by m grid of components placed left to right, top to bottom. GridBagLayout - components can take up adjacent grid positions through use of a GridBagConstraints object. CardLayout - only one component is seen at a time with the ability to pull a component into view.

197 Application vs Applet An applet is a subclass of panel. Thus it has a display area in which to draw graphics or display. An application must create its own window done with a Frame object. Application programming should register the Frame with a WindowListener to handle a closing event. Only frames may contain menubars, but in 1.1 popup menues are not restricted to frames.

198 Swing a collection of new components in a package called the Java Foundation Classes (JFC) Support “tool tips” as pop-up labels that describe purpose of a component Provide new high demand widgets such as “tabbed panes” as sub panes each with a folder type tab trees to display nested directory structures with a ‘+ ‘ to expand the tree tables to display information returned from database access


Download ppt "The Java Language."

Similar presentations


Ads by Google