Download presentation
Presentation is loading. Please wait.
Published byPreston Robertson Modified over 9 years ago
1
Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction
2
Java: Review Sept. 2003Yangjun Chen 91.39022 Introduction What is Java? object-oriented language platform independent - JVM - two-phase execution Multi-threaded HelloWorld program
3
Java: Review Sept. 2003Yangjun Chen 91.39023 Java basics Java basics I Java basics II
4
Java: Review Sept. 2003Yangjun Chen 91.39024 Basics -I Basic concepts: class declaration class body, methods variables identifiers comments Primitive data types Operators arithmetic operators logic operators bitwise operators
5
Java: Review Sept. 2003Yangjun Chen 91.39025 The modulus (%) operator gives the remainder after integer division: 31%9 = 4. -5%3 = -2 5%-3 = 2 - 5%-3 = -2
6
Java: Review Sept. 2003Yangjun Chen 91.39026 Type Casting Example: class GoodAssignment { public static void main(String args[]) { byte b; int i=127; b=(byte) i; System.out.println(b); //display 127}} class GoodAssignment { public static void main(String args[]) { byte b; int i=258; b=(byte) i; System.out.println(b); //display 2}} 0 0110... 8 bits 16 bits
7
Java: Review Sept. 2003Yangjun Chen 91.39027 Bitwise Operators Number can be represented by a set of bits (a series of 0s and 1s) Binary digits take on the value of 0 or 1. Example: the binary number (110101) 2 represents the decimal number 53. OperatorMeaning &AND |OR ^XOR ~Bitwise complement >>Shift right with sign extension >>>Shift right with zero fill <<Shift left with zero fill
8
Java: Review Sept. 2003Yangjun Chen 91.39028 Bitwise Operators 110101 101010 100000 & 110101 101010 111111 | 110101 ^101010 011111 110101111010 >> 110101011010 >>> 110101101010 << |
9
Java: Review Sept. 2003Yangjun Chen 91.39029 import java.lang.*; //bit operations public class ShowBits { public static void main(String args[]) {byte b = -5; for (int i = 7; i>=0; i--) { if ((b & 0x80) == 0) System.out.println("bit " + i + "is 0"); else System.out.println("bit " + i + "is 1"); b <<= 1; }
10
Java: Review Sept. 2003Yangjun Chen 91.390210 Java Basics - II Modifiers (Specifiers) Statements Array Control flow -condition statements: if switch -loop structure: for while do others: String, print, new, constructor
11
Java: Review Sept. 2003Yangjun Chen 91.390211 Modifiers Modifiers are special keywords that modify the definition of a class, method, or variables. modifiers Modifiers for methods Modifiers for variables Modifiers for classes
12
Java: Review Sept. 2003Yangjun Chen 91.390212 Modifiers for Methods and Variables static final private protected public access modifiers
13
Java: Review Sept. 2003Yangjun Chen 91.390213 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.
14
Java: Review Sept. 2003Yangjun Chen 91.390214 Art of programming Computing factorials -simple -recursive -cache Sorting -simple -Quick sorting -Merge sorting Computing primes
15
Java: Review Sept. 2003Yangjun Chen 91.390215 Computing Factorials Recursive Factorials public class Factorial2 { public static long factorial(long x) { if (x == 1) return 1; else return x*factorial(x - 1); } public class ComputingFactorial { public static void main(String arg[]) { int a = Factorial.factorial2(Integer.parseInt(arg[0])); System.out.println(a);}}
16
Java: Review Sept. 2003Yangjun Chen 91.390216 Computing Factorials Caching factorials public class Factorial3 { //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++; }}
17
Java: Review Sept. 2003Yangjun Chen 91.390217 Sorting Numbers main idea: 1st step:3 1 6 5 4 8 10 7 2nd step: 3 2 1 5 8 9 10 7 3rd step: 3 2 1 4 5 6 8 9 10 7 centerto 29 64 Smaller than 5 greater than 5 i j The center element is 5. i = j = 5 Quick sort from
18
Java: Review Sept. 2003Yangjun Chen 91.390218 Sorting Numbers 4th step: 4 5 6 10 5th step: 1 2 3 4 center from to 3 7 from center i = 2 j = 2 8 9 2 1
19
Java: Review Sept. 2003Yangjun Chen 91.390219 6th step: 1 The sequence contains only one element, no sorting. 7th step: 3 4 i = j = 1 8th step: 4 fromto center The center element is 4. The sequence contains only one element, no sorting. 1 2 3 4 5
20
Java: Review Sept. 2003Yangjun Chen 91.390220 18, 19, 18, 3, 4, 6, 1, 10, 9, 5, 20, 19, 18, 17, 2, 1, 14, 13, 12, 11, 8, 16, 15 3, 4, 6, 1, 10, 9, 5,15, 19, 17, 2, 1, 14, 13, 12, 11, 8, 16,20 18,16,3, 4, 6, 1, 10, 9, 5, 15,17, 2, 1, 14, 13, 12, 11, 8, 20 3, 4, 6, 1, 10, 9, 5, 15, 16, 8,17, 2, 1, 14, 13, 12, 11,19, 20 i=17 j=16 3, 4, 6, 1, 10, 9, 5, 15, 16, 8,17, 2, 1, 14, 13, 12, 11 Sorting Numbers i j Quick sort
21
Java: Review Sept. 2003Yangjun Chen 91.390221 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); } }
22
Java: Review Sept. 2003Yangjun Chen 91.390222 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;
23
Java: Review Sept. 2003Yangjun Chen 91.390223 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);}
24
Java: Review Sept. 2003Yangjun Chen 91.390224 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]+" "); }
25
Java: Review Sept. 2003Yangjun Chen 91.390225 Sorting by merging Merging means the combination of two or more ordered sequence into a single sequence. For example, can merge two sequences: 503, 703, 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. 503703765 087512677 087 503703765 512677 087503 703765 512677
26
Java: Review Sept. 2003Yangjun Chen 91.390226 Merging algorithm Algorithm Merge(s1, s2) Input: two sequences: s1 - x1 x2... x m and s2 - y1 y2... y n Output: a sorted sequence: z1 z2... z m+n. 1.[initialize]i := 1, j := 1, k := 1; 2.[find smaller]if x i y j goto step 3, otherwise goto step 5; 3.[output x i ] z k.:= x i, k := k+1, i := i+1. If i m, goto step 2; 4.[transmit y j ... y n ] z k,..., z m+n := y j,..., y n. Terminate the algorithm; 5.[output y j ] z k.:= y j, k := k+1, j := j+1. If j n, goto step 2; 6.[transmit x i ... x m ] z k,..., z m+n := x i,..., x m. Terminate the algorithm;
27
Java: Review Sept. 2003Yangjun Chen 91.390227 - Merge-sorting Algorithm Merge-sorting(s) Input: a sequences s = Output: a sorted sequence. 1. If |s| = 1, then return s; 2. k := m/2 ; 3. s1 := Merge-sorting(x 1,..., x k ); 4. s2 := Merge-sorting(x k+1,..., x m ); 5. return(Merge(s1, s2));
28
Java: Review Sept. 2003Yangjun Chen 91.390228 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 4 357 68912141516182010 11131719
29
Java: Review Sept. 2003Yangjun Chen 91.390229 Computing Primes Import java.lang.*; public class Sieve { public static void main(String[] args) { int max = 100; //Assign a default value try {max = Integer.parseInt(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 that 0 and 1 are not prime. Make a note of it. isprime[0] = isprime[1] = false;
30
Java: Review Sept. 2003Yangjun Chen 91.390230 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); }}
31
Java: Review Sept. 2003Yangjun Chen 91.390231 Object-oriented programming What is OOP? Class, instance, field, method,... “this” key word Method Overloading Inheritance Method Overriding Abstract and Interface
32
Java: Review Sept. 2003Yangjun Chen 91.390232 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.
33
Java: Review Sept. 2003Yangjun Chen 91.390233 “this” in Constructors (Example for Method Overloading) To invoke a constructor from another constructor in the same class: class Car { String licensePlate; double speed, maxSpeed; public Car(String licensePlate, double speed, double maxSpeed) { this.licensePalte = licensePlate; this.speed = speed; this.maxSpeed = maxSpeed; } public Car(String licensePlate, double maxSpeed) { this(licensePlate, 0.0, maxSpeed); } void accTomax ( ) { … } void accelerate ( ) {…} }
34
Java: Review Sept. 2003Yangjun Chen 91.390234 Interface import java.util.*; import java.lang.*; interface CanFight { void fight ( );} interface CanSwim { void swim ( );} interface CanFly {void fly ( );} class ActionCharacter { public void fight( ) { }} class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly { public void fight ( ) {System.out.println(“Can fight!”);} public void swim ( ) {System.out.println(“Can swim!”); } public void fly ( ) {System.out.println(“Can fly!”);} }
35
Java: Review Sept. 2003Yangjun Chen 91.390235 Interface public class Adventure { static void t(CanFight x) { x.fight();} static void u(CanSwim x) { x.swim();} static void v(CanFly x) { x.fly();} static void w(ActionCharacter x) { x.fight();} public static void main (String[ ] args) { Hero h = new Hero( ); t(h); //Treat it as a CanFight u(h); //Treat it as a CanSwim v(h); //Treat it as a CanFly w(h); //Treat it as an ActionCharacter }
36
Java: Review Sept. 2003Yangjun Chen 91.390236 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); }
37
Java: Review Sept. 2003Yangjun Chen 91.390237 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()”); } Instrument Wind
38
Java: Review Sept. 2003Yangjun Chen 91.390238 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 }
39
Java: Review Sept. 2003Yangjun Chen 91.390239 Upcasting and Polymorphism Polymorphism: In Java, the principle that the actual type of the object determines the method to be called is called polymorphism. class Shape { void draw() {} void erase() {} } class Circle extends Shape { void draw() { System.out.println(“Circle.draw()”); } void erase() {System.out.println(“Circle.erase()”);}} Shape draw() erase() Square draw() erase() Triangle draw() erase() Circle draw() erase()
40
Java: Review Sept. 2003Yangjun Chen 91.390240 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()”);}} Upcasting and Polymorphism
41
Java: Review Sept. 2003Yangjun Chen 91.390241 public class Shapes { public static Shape randShape() { 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] = randShape(); //Make polymorphism method calls: for (int i = 0; i < s.length; i++) s[i].draw();}} Upcasting and Polymorphism
42
Java: Review Sept. 2003Yangjun Chen 91.390242 Applets and graphics Applet -HelloWorld Applet -import statement -Hypertext Mark Language (HTML) Graphic -line -rectangle -polygon -ovals -arcs -color -font
43
Java: Review Sept. 2003Yangjun Chen 91.390243 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 HelloWorld.html or input the URL address of your HTML file by internet explorer: H:\javaprog\EventTest1.html
44
Java: Review Sept. 2003Yangjun Chen 91.390244 HelloWorld Applet The HelloWorld applet: import java. applet.*; import java. awt.*; // A simple Java Applet public class HelloWorld extends Applet { public void paint( Graphics g) { g. drawString(“ HelloWorld!”, 20,10); }
45
Java: Review Sept. 2003Yangjun Chen 91.390245 HelloWorld Applet HelloWorld.html: <APPLET CODE = HelloWorld.class WIDTH = 200 HEIGHT=200> URL address: file://e:/javaprog/HelloWorld.html
46
Java: Review Sept. 2003Yangjun Chen 91.390246 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().
47
Java: Review Sept. 2003Yangjun Chen 91.390247 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:\ychen2\javaprog - The first statement in each class: package javaprog - in D:\ychen2, issue command: javac javaprog\*.java - set classpath = %classpath%;D:\ychen2
48
Java: Review Sept. 2003Yangjun Chen 91.390248 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. - import java. awt. Graphics;
49
Java: Review Sept. 2003Yangjun Chen 91.390249 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. - Pixels in Java are integer values only (0,0) (60,50) +X +Y (20,20)
50
Java: Review Sept. 2003Yangjun Chen 91.390250 Lines To draw a line onto the screen, use the drawLine() method: - void drawLine( int x1, int y1, int x2, int y2); -This draws a line from the point with coordinates (x1, y1) to the point with coordinates (x2, y2). -Example: import java. awt. Graphics; public class MyLine extends java. applet. Applet { public void paint( Graphics g) { g. drawLine( 25,25, 75,75); } -There is no way to change the line thickness in Java. So how do we make thicker lines?
51
Java: Review Sept. 2003Yangjun Chen 91.390251 Rectangles To draw a rectangle on the screen, use the drawRect() method: -void drawRect( int x, int y, int width, int height) Example: import java. awt. *; public class MyRect extends java. applet. Applet { public void paint( Graphics g) { g. drawRect(120,20, 60,60); g. setColor( Color. red); g. fillRect( 120, 20,60, 60); }
52
Java: Review Sept. 2003Yangjun Chen 91.390252 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 drawRoundRect( int x, int y, int width, int height, int arcWidth, int arcHeight) -void fillRoundRect( int x, int y, int width, int height, int arcWidth, int arcHeight)
53
Java: Review Sept. 2003Yangjun Chen 91.390253 3D 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 draw3DRect( int x, int y, int width, int height, boolean raised) -void fill3DRect( 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.
54
Java: Review Sept. 2003Yangjun Chen 91.390254 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 MyPolygon 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. drawPolygon( exes, whys, pts); }}
55
Java: Review Sept. 2003Yangjun Chen 91.390255 Polygons using the Polygon Class Example: import java. awt. Graphics; import java. awt. Polygon; public class MyPolygon2 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.drawPolygon(poly); g.fillPolygon( poly); }
56
Java: Review Sept. 2003Yangjun Chen 91.390256 Ovals Ovals are drawn with the drawOval() or fillOval() methods - void drawOval( int x, int y, int width, int height) -void fillOval( 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 MyOval extends java. applet. Applet { public void paint( Graphics g) { g. drawOval( 20, 20, 60,60); g. fillOval( 120, 20,60,60); }
57
Java: Review Sept. 2003Yangjun Chen 91.390257 Arcs An arc is basically part of an oval. Arcs are drawn using the method:— -void drawArc( int x, int y, int width, int height, int startAngle, int arcAngle) -void fillArc( int x, int y, int width, int height, int startAngle, int arcAngle) -This draws an arc within the rectangle specified starting from the startAngle argument for a duration of arcAngle. -Example: g. drawArc( 10,10,100,80,45,210);
58
Java: Review Sept. 2003Yangjun Chen 91.390258 Arcs Example: import java. awt. Graphics; public class MyArc extends java. applet. Applet { public void paint( Graphics g) { g. drawArc( 120,20, 60,60,90, 180); g. fillArc( 120,20,60, 60,90,180); }
59
Java: Review Sept. 2003Yangjun Chen 91.390259 The Color Class This class contains 13 constant values that can be used: -black, blue, cyan, darkGray, Gray, green, lightGray, 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. setColor(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 (128,128,128) is medium gray
60
Java: Review Sept. 2003Yangjun Chen 91.390260 The Color Class To declare a new color in Java, use the “new” operator -Color myColor = 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. setColor(myColor); -You can also define the color “on the fly” or in line with the setColor() method g. setColor( new Color( 255,0,128));
61
Java: Review Sept. 2003Yangjun Chen 91.390261 The Font Class There are five basic fonts in Java -SanSerif (Helvetica), Serif (Times Roman), Monospaced (Courier), Dialog, DialogInput 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 myFont = new Font(“Helvetica”, Font.BOLD, 12); - After creating a font, you have to set it before it can be used: g.setFont(myFont); -You can also do this in line with the setFont() method g.setFont(new Font(“Helvetica”, Font.BOLD, 12)); You can also combine styles by adding them together, for example Font myFont = new Font(“Helvetica”, Font.BOLD+ Font.ITALIC, 12)
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.