Java Review Java Applets and graphics Objectoriented programming
Java: Review Java Applets and graphics Object-oriented programming Art of programming Java basics Introduction 1 91. 3902 Yangjun Chen Sept. 2003
Java: Review What is Java? object-oriented language platform independent Introduction - JVM - two-phase execution Multi-threaded Hello. World program Sept. 2003 Yangjun Chen 91. 3902 2
Java: Review Java basics II Sept. 2003 Yangjun Chen 91. 3902 3
Java: Review Basics -I • Basic concepts: class declaration class body, methods variables identifiers comments • Primitive data types • Operators arithmetic operators logic operators bitwise operators Sept. 2003 Yangjun Chen 91. 3902 4
Java: Review • The modulus (%) operator gives the remainder after integer division: 31%9 = 4. -5%3 = -2 5%-3 = 2 - 5%-3 = -2 Sept. 2003 Yangjun Chen 91. 3902 5
Java: Review Type Casting • Example: class Good. Assignment { public static void main(String args[]) { byte b; int i=127; b=(byte) i; System. out. println(b); //display 127}} class Good. Assignment { public static void main(String args[]) { byte b; int i=258; b=(byte) i; System. out. println(b); //display 2}} Sept. 2003 Yangjun Chen 91. 3902 8 bits. . . 1 0 0. . . 1 0 16 bits 6
Java: Review Bitwise Operators • Number can be represented by a set of bits (a series of 0 s and 1 s) • Binary digits take on the value of 0 or 1. • Example: the binary number (110101)2 represents the decimal number 53. Operator Meaning & | ^ ~ >> >>> << AND OR XOR Bitwise complement Shift right with sign extension Shift right with zero fill Shift left with zero fill Sept. 2003 Yangjun Chen 91. 3902 7
Java: Review Bitwise Operators & 1101010 | 100000 110101 Sept. 2003 1101010 111111 >> >>> << ^ 1101010 011111 | 111010 01101010 Yangjun Chen 91. 3902 8
Java: Review import java. lang. *; //bit operations public class Show. Bits { public static void main(String args[]) {byte b = -5; for (int i = 7; i>=0; i--) { if ((b & 0 x 80) == 0) System. out. println("bit " + i + "is 0"); else System. out. println("bit " + i + "is 1"); b <<= 1; } } } Sept. 2003 Yangjun Chen 91. 3902 9
Java: Review Java Basics - II • • Modifiers (Specifiers) Statements Array Control flow - condition statements: if switch - loop structure: for while do • others: String, print, new, constructor Sept. 2003 Yangjun Chen 91. 3902 10
Java: Review Modifiers • Modifiers are special keywords that modify the definition of a class, method, or variables. modifiers Modifiers for methods for variables Sept. 2003 Yangjun Chen 91. 3902 Modifiers for classes 11
Java: Review Modifiers for Methods and Variables • • • static final private protected public Sept. 2003 access modifiers Yangjun Chen 91. 3902 12
Java: Review Modifiers for Classes • There are three modifiers for classes in Java. - public This makes a class accessible to outside of the package. final This prevents a class from being extended. abstract In an abstract class, some abstract methods (with only method signature; no implementation) are defined. Therefore, an abstract class can not be instantiated. Sept. 2003 Yangjun Chen 91. 3902 13
Java: Review Computing factorials Art of programming - simple - recursive - cache Sorting - simple - Quick sorting - Merge sorting Computing primes Sept. 2003 Yangjun Chen 91. 3902 14
Java: Review Computing Factorials • Recursive Factorials public class Factorial 2 { public static long factorial(long x) { if (x == 1) return 1; else return x*factorial(x - 1); } } public class Computing. Factorial { public static void main(String arg[]) { int a = Factorial. factorial 2(Integer. parse. Int(arg[0])); System. out. println(a); }} Sept. 2003 Yangjun Chen 91. 3902 15
Java: Review Computing Factorials • Caching factorials public class Factorial 3 { //create an array to cache values 0! Through 20! Static long[] table = new long[21]; Static {table[0] = 1; } //factorial of 0 is 1 //Remember the highest initialized value in the array static int last = 0; public static long factorial(int x) { while (last < x) { table [last + 1] = table[last]*(last + 1); last++; }} Sept. 2003 Yangjun Chen 91. 3902 16
Java: Review Sorting Numbers • Quick sort The center element is 5. main idea: from 1 st step: 3 center 9 1 6 to 5 4 8 2 10 j i 2 nd step: 3 2 1 6 5 4 8 9 10 7 3 rd step: 3 2 1 4 5 6 8 9 10 7 Smaller than 5 Sept. 2003 7 i=j=5 Yangjun Chen 91. 3902 greater than 5 17
Java: Review Sorting Numbers from center 4 th step: 3 5 th step: 1 3 to 910 7 to 2 41 2 center 5 6 8 4 i=2 j=2 Sept. 2003 Yangjun Chen 91. 3902 18
Java: Review 6 th step: 1 The sequence contains only one element, no sorting. center from to 7 th step: The center element is 4. 3 4 i=j=1 8 th step: 4 The sequence contains only one element, no sorting. 1 Sept. 2003 2 3 4 5 Yangjun Chen 91. 3902 19
Java: Review Sorting Numbers • Quick sort 3, 4, 6, 1, 10, 9, 5, 20, 19, 18, 17, 2, 1, 14, 13, 12, 11, 8, 16, 15 j i 3, 4, 6, 1, 10, 9, 5, 19, 18, 17, 2, 1, 14, 13, 12, 11, 8, 16, 20 3, 4, 6, 1, 10, 9, 5, 16, 18, 17, 2, 1, 14, 13, 12, 11, 8, 19, 20 3, 4, 6, 1, 10, 9, 5, 16, 8, 17, 2, 1, 14, 13, 12, 11, 18, 19, 20 i=17 3, 4, 6, 1, 10, 9, 5, 16, 8, 17, 2, 1, 14, 13, 12, 11 j=16 Sept. 2003 Yangjun Chen 91. 3902 20
Java: Review • Another Java program for the quick sort: public class Sorter { public static void sort (int[] a, int from, int to) { if ((a == null) || (a. length < 2)) return; int i = from -1, j = to + 1; int center = a[(from + to)/2]; do {i++; j--; while ((i < to) && (a[i] < center)) i++; while ((j > from) && (a[j] > center)) j--; if (i < j) { int tmp =a[i]; a [i] = a[j]; a[j] = tmp; } }while (i <= j); if (from < j) sort(a, from, j); if (i < to) sort(a, i, to); } } Sept. 2003 Yangjun Chen 91. 3902 21
Java: Review import java. lang. *; public class sort { public static void sort (int[] a, int from, int to) { int tag = 0; if ((a == null) || (a. length < 2)) return; int i = from, j = to; int center = a[(from + to)/2]; do { while ((i < to) && (a[i] < center)) i++; while ((j > from) && (a[j] > center)) j--; if (j > i) tag = 1; else if (j == i) tag = 0; else tag = -1; Sept. 2003 Yangjun Chen 91. 3902 22
Java: Review switch (tag) { case 1: int tmp =a[i]; a [i] = a[j]; a[j] = tmp; i++; j--; break; case 0: i++; j--; break; default: } }while (i <= j); if (from < j) sort(a, from, j); if (i < to) sort(a, i, to); } Sept. 2003 Yangjun Chen 91. 3902 23
Java: Review public static void main(String args[]) { int array[]=new int[20]; for(int i = 0; i < 20; i++) //Generate random numbers array[i] = (int)(Math. random()*100); sort(array, 0, 19); System. out. println("the final answer is: "); for (int i=0; i<array. length; i++) System. out. print(array[i]+" "); } } Sept. 2003 Yangjun Chen 91. 3902 24
Java: Review • Sorting by merging Merging means the combination of two or more ordered sequence into a single sequence. For example, can merge two sequences: 503, 765 and 087, 512, 677 to obtain a sequence: 087, 503, 512, 677, 703, 765. A simple way to accomplish this is to compare the two smallest items, output the smallest, and then repeat the same process. 503 087 703 512 765 677 087 Sept. 2003 Yangjun Chen 503 91. 3902 503 512 703 677 765 677 25
Java: Review • Merging algorithm Algorithm Merge(s 1, s 2) Input: two sequences: s 1 - x 1 x 2. . . xm and s 2 - y 1 y 2. . . yn Output: a sorted sequence: z 1 z 2. . . zm+n. 1. [initialize] i : = 1, j : = 1, k : = 1; 2. [find smaller] if xi yj goto step 3, otherwise goto step 5; 3. [output xi] zk. : = xi, k : = k+1, i : = i+1. If i m, goto step 2; 4. [transmit yj . . . yn] zk, . . . , zm+n : = yj, . . . , yn. Terminate the algorithm; 5. [output yj] zk. : = yj, k : = k+1, j : = j+1. If j n, goto step 2; 6. [transmit xi . . . xm] zk, . . . , zm+n : = xi, . . . , xm. Terminate the algorithm; Sept. 2003 Yangjun Chen 91. 3902 26
Java: Review - Merge-sorting Algorithm Merge-sorting(s) Input: a sequences s = < x 1, . . . , xm> Output: a sorted sequence. 1. If |s| = 1, then return s; 2. k : = m/2 ; 3. s 1 : = Merge-sorting(x 1, . . . , xk); 4. s 2 : = Merge-sorting(xk+1, . . . , xm); 5. return(Merge(s 1, s 2)); Sept. 2003 Yangjun Chen 91. 3902 27
Java: Review Computing Primes • Finding the largest prime number smaller than a specified integer: Input integer m, find p m such that p is a prime and if there is prime p’ > p then p’ must be larger m. than m. 1 2 Sept. 2003 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Yangjun Chen 91. 3902 28
Java: Review Computing Primes Import java. lang. *; public class Sieve { public static void main(String[] args) { int max = 100; //Assign a default value try {max = Integer. parse. Int(args[0]); } catch (Exception e) {} //Silently ignore exceptions. //Create an array that specifies whether each number is prime or not. boolean[] isprime = new boolean[max+1]; //Assume that all numbers are primes, until proven otherwise. for (int i = 0; < max; i++) isprime[i] = true; //We know that 0 and 1 are not prime. Make a note of it. isprime[0] = isprime[1] = false; Sept. 2003 Yangjun Chen 91. 3902 29
Java: Review Computing Primes //To compute all primes less than max, we need to rule out multiples of all //integers less than the square root of max. int n = (int) Math. ceil(Math. sqrt(max)); for (int i = 0; i <= n; i++) { if (isprime[i]) { int k = 2; for (int j = k*i; j < max; j = (k ++)*i) isprime[j] = false; } } int largest; for (largest = max - 1; !isprime[largest]; largest--); //empty loop body System. out. println(“The largest prime less than or equal to “ + max + “is ” + largest); }} Sept. 2003 Yangjun Chen 91. 3902 30
Java: Review What is OOP? Class, instance, field, method, . . . Object-oriented programming “this” key word Method Overloading Inheritance Method Overriding Abstract and Interface Sept. 2003 Yangjun Chen 91. 3902 31
Java: Review What is OOP? • Procedural programming is where you would try to solve a problem using pre-determined types: int, floats, strings and arrays. • In OOP, you create a model that best represents the problem. • The programmer defined model is known a class. • A class is a programmer defined type, together with a lot of procedures manipulating over it. Such a type can be used as template for instance of the class. Sept. 2003 Yangjun Chen 91. 3902 32
Java: Review “this” in Constructors (Example for Method Overloading) • To invoke a constructor from another constructor in the same class: class Car { String license. Plate; double speed, max. Speed; public Car(String license. Plate, double speed, double max. Speed) { this. license. Palte = license. Plate; this. speed = speed; this. max. Speed = max. Speed; } public Car(String license. Plate, double max. Speed) { this(license. Plate, 0. 0, max. Speed); } void acc. Tomax ( ) { … } void accelerate ( ) {…} } Sept. 2003 Yangjun Chen 91. 3902 33
Java: Review Interface import java. util. *; import java. lang. *; interface Can. Fight { void fight ( ); } interface Can. Swim { void swim ( ); } interface Can. Fly {void fly ( ); } class Action. Character { public void fight( ) { }} class Hero extends Action. Character implements Can. Fight, Can. Swim, Can. Fly { public void fight ( ) {System. out. println(“Can fight!”); } public void swim ( ) {System. out. println(“Can swim!”); } public void fly ( ) {System. out. println(“Can fly!”); } } Sept. 2003 Yangjun Chen 91. 3902 34
Java: Review Interface public class Adventure { static void t(Can. Fight x) { x. fight(); } static void u(Can. Swim x) { x. swim(); } static void v(Can. Fly x) { x. fly(); } static void w(Action. Character x) { x. fight(); } public static void main (String[ ] args) { Hero h = new Hero( ); t(h); //Treat it as a Can. Fight u(h); //Treat it as a Can. Swim v(h); //Treat it as a Can. Fly w(h); //Treat it as an Action. Character } } Sept. 2003 Yangjun Chen 91. 3902 35
Java: Review Upcasting and Polymorphism • Upcasting: Taking an object reference and treating it as a reference to its base type is called upcasting, because of the way inheritance trees are drawn with the base class at the top. class Note { private int value; private Note(int val) {value = val; } public static final Note middle_c = new Note(0), c_sharp = new Note(1), b_flat = new Note(2); } Sept. 2003 Yangjun Chen 91. 3902 36
Java: Review Upcasting and Polymorphism class Instrument { public void play(Note n) { System. out. println(“Instrument. play()”) } } class Wind extends Instrument { public void play(Note n) { System. out. println(“Wind. play()”); } } Sept. 2003 Yangjun Chen 91. 3902 Instrument Wind 37
Java: Review Upcasting and Polymorphism public class Music { public static void tune(Instrument i) { // … i. play(Note. middle_c); } public static void main(String[] args) { Wind flute = new Wind(); tune(flute); //Upcasting } } Sept. 2003 Yangjun Chen 91. 3902 38
Java: Review Upcasting and Polymorphism • Polymorphism: In Java, the principle that the actual type of the object determines the method to be called is called polymorphism. Shape draw() erase() class Shape { void draw() {} void erase() {} } Circle draw() erase() class Circle extends Shape { void draw() { System. out. println(“Circle. draw()”); } void erase() {System. out. println(“Circle. erase()”); }} Sept. 2003 Yangjun Chen 91. 3902 Square draw() erase() Triangle draw() erase() 39
Java: Review Upcasting and Polymorphism class Square extends Shape { void draw() { System. out. println(“Square. draw()”); } void erase() {System. out. println(“Square. erase()”); }} class Triangle extends Shape { void draw() { System. out. println(“Triangle. draw()”); } void erase() {System. out. println(“Triangle. erase()”); }} Sept. 2003 Yangjun Chen 91. 3902 40
Java: Review Upcasting and Polymorphism public class Shapes { public static Shape rand. Shape() { switch((int) (Math. random()*3)) { case 0: return new Circle(); case 1: return new Square(); case 2: return new Triangle(); default : return new Circle(); }} public static void main(String[] args) { Shape[] s = new Shape[9]; for (int i = 0; i < s. length; i++) s[i] = rand. Shape(); //Make polymorphism method calls: for (int i = 0; i < s. length; i++) s[i]. draw(); }} Sept. 2003 Yangjun Chen 91. 3902 41
Java: Review • Applet - Applets and graphics Sept. 2003 Hello. World Applet import statement Hypertext Mark Language (HTML) • Graphic - line rectangle polygon ovals arcs color font Yangjun Chen 91. 3902 42
Java: Review Applets • There are two types of Java programs: - Applications and Applets • An applet is a subclass of Applet class defined in “applet” package. • Using appletviewer to run a HTML file that contains an applet class; or invoke it through an internet browser. appletviewer Hello. World. html or input the URL address of your HTML file by internet explorer: H: javaprogEvent. Test 1. html Sept. 2003 Yangjun Chen 91. 3902 43
Java: Review Hello. World Applet • The Hello. World applet: import java. applet. *; import java. awt. *; // A simple Java Applet public class Hello. World extends Applet { public void paint( Graphics g) { g. draw. String(“ Hello. World!”, 20, 10); } } Sept. 2003 Yangjun Chen 91. 3902 44
Java: Review Hello. World Applet • Hello. World. html: <HTML> <BODY> <APPLET CODE = Hello. World. class WIDTH = 200 HEIGHT=200> </ APPLET> </BODY> </HTML> URL address: file: //e: /javaprog/Hello. World. html Sept. 2003 Yangjun Chen 91. 3902 45
Java: Review Life Cycle of an Applet • An Applet executes within an environment provided by a Web browser or a tool such as the applet viewer. • It does not have a main() method • There are four methods that are called during the life cycle of an applet: init(), start(), stop(), destroy(). Sept. 2003 Yangjun Chen 91. 3902 46
Java: Review import Statements • import statements must appear before any of the names defined in the import are used. • It is a strong recommendation that all imports appear at the beginning of your program. import java. applet. *; import. java. awt. *; • Package construction: - Assume that there are classes in D: ychen 2javaprog - The first statement in each class: package javaprog - in D: ychen 2, issue command: javac javaprog*. java - set classpath = %classpath%; D: ychen 2 Sept. 2003 Yangjun Chen 91. 3902 47
Java: Review Graphics • The java. awt package contains all the necessary classes you need to create graphical user interfaces (GUIs). • Most of the graphics operations in Java are methods defined in the Graphics class. • You don’t have to create an instance of the Graphics class because in the applet’s paint() method, a Graphics object is provided for you. By drawing in that object, you draw onto your applet which appears on the screen. • The Graphics class is part of the java. awt package, so make sure you import it into your Java code. Sept. Yangjun Chen 91. 3902 48 - 2003 import java. awt. Graphics;
Java: Review The Coordinate System • Java’s coordinate system has the origin (0, 0) in the top left corner of the applet. - Positive x values are to the right and positive y values are downward • The coordinate system is represented by pixels. +X (0, 0) - Pixels in Java are integer values only (20, 20) +Y Sept. 2003 (60, 50) Yangjun Chen 91. 3902 49
Java: Review Lines • To draw a line onto the screen, use the draw. Line() method: - void draw. Line( int x 1, int y 1, int x 2, int y 2); - This draws a line from the point with coordinates (x 1, y 1) to the point with coordinates (x 2, y 2). - Example: import java. awt. Graphics; public class My. Line extends java. applet. Applet { public void paint( Graphics g) { g. draw. Line( 25, 75, 75); } } - There is no way to change the line thickness in Java. So how do we make thicker lines? Sept. 2003 Yangjun Chen 91. 3902 50
Java: Review Rectangles • To draw a rectangle on the screen, use the draw. Rect() method: - void draw. Rect( int x, int y, int width, int height) • Example: import java. awt. *; public class My. Rect extends java. applet. Applet { public void paint( Graphics g) { g. draw. Rect(120, 60, 60); g. set. Color( Color. red); g. fill. Rect( 120, 60, 60); } } Sept. 2003 Yangjun Chen 91. 3902 51
Java: Review Rounded Rectangles • These are rectangles with the corners rounded according to the values of the arguments. • Like the rectangle, there are two methods for round rectangles: - void draw. Round. Rect( int x, int y, int width, int height, int arc. Width, int arc. Height) - void fill. Round. Rect( int x, int y, int width, int height, int arc. Width, int arc. Height) Sept. 2003 Yangjun Chen 91. 3902 52
Java: Review 3 D Rectangles • You can also draw three dimensional rectangles in Java - Warning: They really don’t look too good though • There are two methods as well: - void draw 3 DRect( int x, int y, int width, int height, boolean raised) - void fill 3 DRect( int x, int y, int width, int height, boolean raised) - The argument “raised”, when true, will paint the rectangle as if it were raised from the surface. - If it is false, the rectangle will appear as if it were depressed. Sept. 2003 Yangjun Chen 91. 3902 53
Java: Review Polygons • Polygons are shapes with an unlimited # of sides. • To draw a polygon, you need a set of x and y coordinates. • The polygon is then drawn by drawing a series of straight lines from the first point to the second, to the third and so on. import java. awt. Graphics; public class My. Polygon extends java. applet. Applet { public void paint( Graphics g) { int exes[]={ 39, 94, 97, 142, 53, 58, 26}; int whys[]={ 33, 74, 36, 70, 108, 80, 106}; int pts= exes. length; g. draw. Polygon( exes, whys, pts); }} Sept. 2003 Yangjun Chen 91. 3902 54
Java: Review Polygons using the Polygon Class • Example: import java. awt. Graphics; import java. awt. Polygon; public class My. Polygon 2 extends java. applet. Applet { public void paint( Graphics g) { int exes[]={ 39, 94, 97, 142, 53, 58, 26}; int whys[]={ 33, 74, 36, 70, 108, 80, 106}; int pts= exes. length; Polygon poly= new Polygon( exes, whys, pts); g. draw. Polygon(poly); g. fill. Polygon( poly); } } Sept. 2003 Yangjun Chen 91. 3902 55
Java: Review Ovals • Ovals are drawn with the draw. Oval() or fill. Oval() methods - void draw. Oval( int x, int y, int width, int height) - void fill. Oval( int x, int y, int width, int height) - This draws an oval within the bounding rectangle specified by the arguments - Example: import java. awt. Graphics; public class My. Oval extends java. applet. Applet { public void paint( Graphics g) { g. draw. Oval( 20, 60, 60); g. fill. Oval( 120, 60, 60); } } Sept. 2003 Yangjun Chen 91. 3902 56
Java: Review Arcs • An arc is basically part of an oval. • Arcs are drawn using the method: — - void draw. Arc( int x, int y, int width, int height, int start. Angle, int arc. Angle) - void fill. Arc( int x, int y, int width, int height, int start. Angle, int arc. Angle) - This draws an arc within the rectangle specified starting from the start. Angle argument for a duration of arc. Angle. - Example: g. draw. Arc( 10, 100, 80, 45, 210); Sept. 2003 Yangjun Chen 91. 3902 57
Java: Review Arcs • Example: import java. awt. Graphics; public class My. Arc extends java. applet. Applet { public void paint( Graphics g) { g. draw. Arc( 120, 60, 90, 180); g. fill. Arc( 120, 60, 90, 180); } } Sept. 2003 Yangjun Chen 91. 3902 58
Java: Review The Color Class • This class contains 13 constant values that can be used: - black, blue, cyan, dark. Gray, green, light. Gray, magenta, orange, pink, red, white, yellow • To address them we have to reference them through the Color class - eg. Color. black - Too set the current color to blue: g. set. Color(Color. blue) • Colors in Java are described by the RGB (Red, Green, Blue) model. - This model specifies the amount of red, green, and blue in a color. - The intensity of each component is measured as an integer between 0 and 255, with 0 representing no light. (0, 0, 0) is black Sept. 2003 (128, 128) is Yangjun Chengray 91. 3902 59 medium
Java: Review The Color Class • To declare a new color in Java, use the “new” operator - Color my. Color = new Color( 255, 0, 128); - We now have a new color and since we know it is an object of the Color class we can use it directly g. set. Color(my. Color); - You can also define the color “on the fly” or in line with the set. Color() method g. set. Color( new Color( 255, 0, 128)); Sept. 2003 Yangjun Chen 91. 3902 60
Java: Review The Font Class • There are five basic fonts in Java - San. Serif (Helvetica), Serif (Times Roman), Monospaced (Courier), Dialog. Input • There are some constant values associated with the Font class as well. - Font. BOLD, Font. PLAIN, Font. ITALIC • Create a Font object by using the “new” operator - Font my. Font = new Font(“Helvetica”, Font. BOLD, 12); - After creating a font, you have to set it before it can be used: g. set. Font(my. Font); You can also do this in line with the set. Font() method g. set. Font(new Font(“Helvetica”, Font. BOLD, 12)); - • You can also combine styles by adding them together, for example Sept. 2003 Font Yangjun Chen 91. 3902 my. Font = new Font(“Helvetica”, Font. BOLD+ Font. ITALIC, 12) 61
- Slides: 61