Title: 3902 Chapter 1
1Java
Java basics
Introduction
Applets and graphics
Art of programming
Object-oriented programming
2What is Java? object-oriented language platform
independent - JVM - two-phase
execution Multi-threaded HelloWorld program
Introduction
3Java basics I Java basics II
Java basics
4Basics -I
- Basic concepts
- class declaration
- class body, methods
- variables
- identifiers
- comments
- Primitive data types
- Operators
- arithmetic operators
- logic operators
- bitwise operators
5- The modulus () operator gives the remainder
after integer division 319 4. - -53 -2
- 5-3 2
- - 5-3 -2
6Type Casting
- Example
-
- class GoodAssignment
- public static void main(String args)
- byte b
- int i127
- b(byte) i
- System.out.println(b) //display 127
-
- class GoodAssignment
- public static void main(String args)
- byte b
- int i258
- b(byte) i
- System.out.println(b) //display 2
8 bits
0
0
1
1
0
...
...
16 bits
7Bitwise 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. - Operator Meaning
- AND
- OR
- XOR
- Bitwise complement
- gtgt Shift right with sign extension
- gtgtgt Shift right with zero fill
- ltlt Shift left with zero fill
8Bitwise Operators
110101 101010 011111
110101
111010
9import java.lang. //bit operations public class
ShowBits public static void main(String
args) byte b -5 for (int i 7 igt0
i--) if ((b 0x80) 0) System.out.printl
n("bit " i "is 0") else
System.out.println("bit " i "is 1") b
ltlt 1
10Java Basics - II
- Modifiers (Specifiers)
- Statements
- Array
- Control flow
- - condition statements
- if
- switch
- - loop structure
- for
- while
- do
- others String, print, new, constructor
11Modifiers
- Modifiers are special keywords that modify the
definition of a class, method, or variables.
modifiers
Modifiers for methods
Modifiers for variables
Modifiers for classes
12Modifiers for Methods and Variables
- static
- final
- private
- protected
- public
-
access modifiers
13Modifiers 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.
14Computing factorials - simple - recursive - cac
he Sorting - simple - Quick sorting - Merge
sorting Computing primes
Art of programming
15Computing Factorials
- Recursive Factorials
-
- public class Factorial2
- public static long factorial(long x)
- if (x 1) return 1
- else return xfactorial(x - 1)
-
-
- public class ComputingFactorial
- public static void main(String arg)
- int a Factorial.factorial2(Integer.parseInt(a
rg0)) - System.out.println(a)
16Computing Factorials
- Caching factorials
-
- public class Factorial3
- //create an array to cache values 0! Through
20! - Static long table new long21
- Static table0 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 lt x)
- table last 1 tablelast(last 1)
- last
-
-
17Sorting 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
The center element is 5.
from
to
2
9
j
i
6
4
i j 5
greater than 5
Smaller than 5
18Sorting Numbers
from
to
4th step 4 5
6 10 5th
step 1 2 3 4
from
to
8
2
1
7
9
3
i 2
j 2
196th step 1
The sequence contains only one element, no
sorting.
from
to
center
The center element is 4.
7th step 3 4
i j 1
8th step 4
The sequence contains only one element, no
sorting.
1 2 3 4 5
20Sorting Numbers
3, 4, 6, 1, 10, 9, 5, 20, 19,
17, 2, 1, 14, 13, 12, 11, 8, 16, 15
18,
j
i
17, 2, 1, 14, 13, 12, 11, 8, 16,
20
18,
19,
3, 4, 6, 1, 10, 9, 5,
15,
19,
20
18,
16,
3, 4, 6, 1, 10, 9, 5, 15,
17, 2, 1, 14, 13, 12, 11, 8,
18,
8,
17, 2, 1, 14, 13, 12, 11,
19, 20
3, 4, 6, 1, 10, 9, 5, 15, 16,
i17
8,
17, 2, 1, 14, 13, 12, 11
3, 4, 6, 1, 10, 9, 5, 15, 16,
j16
21- 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 lt 2)) return
- int i from -1, j to 1
- int center a(from to)/2
- do i j--
- while ((i lt to) (ai lt center)) i
- while ((j gt from) (aj gt center)) j--
- if (i lt j) int tmp ai a i aj
aj tmp - while (i lt j)
- if (from lt j) sort(a, from, j)
- if (i lt to) sort(a, i, to)
-
22import java.lang. public class sort public
static void sort (int a, int from, int to)
int tag 0
if ((a null) (a.length lt 2))
return int i from, j to int center
a(from to)/2 do while ((i lt to)
(ai lt center)) i while ((j gt from)
(aj gt center)) j-- if (j gt i) tag
1 else if (j i) tag 0 else tag
-1
23switch (tag) case 1 int tmp ai
a i aj aj tmp
i j--
break case 0 i j--
break default while (i lt
j)
if (from lt j) sort(a, from, j)
if (i lt to) sort(a, i, to)
24public static void main(String args) int
arraynew int20 for(int i 0 i lt 20 i)
//Generate random numbers arrayi
(int)(Math.random()100)
sort(array,0,19) System.out.println("the final
answer is") for (int i0iltarray.lengthi)
System.out.print(arrayi" ")
25- 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.
503 703 765 087 512 677
503 703 765 512 677
087
703 765 512 677
087 503
26- Merging algorithm
- Algorithm Merge(s1, s2)
- Input two sequences s1 - x1 ? x2 ... ? xm and
s2 - y1 ? y2 ... ? yn - Output a sorted sequence z1 ? z2 ... ? zmn.
- 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 k1, i i1. If
i ? m, goto step 2 - 4.transmit yj ? ... ? yn zk, ..., zmn yj,
..., yn. Terminate the algorithm - 5.output yj zk. yj, k k1, j j1. If
j ? n, goto step 2 - 6.transmit xi ? ... ? xm zk, ..., zmn xi,
..., xm. Terminate the algorithm
27- Merge-sorting Algorithm Merge-sorting(s)
Input a sequences s lt x1, ..., xmgt Output
a sorted sequence. 1. If s 1, then return
s 2. k ??m/2? 3. s1 Merge-sorting(x1,
..., xk) 4. s2 Merge-sorting(xk1, ...,
xm) 5. return(Merge(s1, s2))
28Computing 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 gt p then p must
be larger m. - than m.
1
4
6
8
9
12
14
15
16
18
20
10
2
3
5
7
11
13
17
19
29Computing Primes
Import java.lang. public class Sieve public
static void main(String args) int max
100 //Assign a default value try max
Integer.parseInt(args0) catch (Exception e)
//Silently ignore exceptions. //Create an
array that specifies whether each number is prime
or not. boolean isprime new
booleanmax1 //Assume that all numbers are
primes, until proven otherwise. for (int i 0
lt max i) isprimei true //We know that
that 0 and 1 are not prime. Make a note of
it. isprime0 isprime1 false
30Computing 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 lt
n i) if (isprimei) int k 2 for
(int j ki j lt max j (k )i)
isprimej false int largest for
(largest max - 1 !isprimelargest
largest--) //empty loop body System.out.println(
The largest prime less than or equal to max
is largest)
31What is OOP? Class, instance, field, method,
... this key word Method Overloading Inheritance
Method Overriding Abstract and Interface
Object-oriented programming
32What 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. -
33this 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 ( )
-
34Interface
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 implement
s 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!)
35Interface
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
36Upcasting 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)
37Upcasting 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
38Upcasting 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) //Upcast
ing
39Upcasting 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())
40Upcasting 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())
41Upcasting and Polymorphism
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 Shape9 for
(int i 0 i lt s.length i) si
randShape() //Make polymorphism method
calls for (int i 0 i lt s.length i)
si.draw()
42- Applet
- - HelloWorld Applet
- - import statement
- - Hypertext Mark Language (HTML)
- Graphic
- - line
- - rectangle
- - polygon
- - ovals
- - arcs
- - color
- - font
Applets and graphics
43Applets
- 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
44HelloWorld 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)
-
-
45HelloWorld Applet
- HelloWorld.html
- ltHTMLgt
- ltBODYgt
- ltAPPLET CODE HelloWorld.class
- WIDTH 200
- HEIGHT200gt
- lt/ APPLETgt
- lt/BODYgt
- lt/HTMLgt
- URL address file//e/javaprog/HelloWorld.html
46Life 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().
47import 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 classpathD\ychen2
48Graphics
- 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 dont have to create an instance of the
Graphics class - because in the applets 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
49The Coordinate System
- Javas 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
50Lines
- 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?
51Rectangles
- 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)
-
-
52Rounded 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)
533D Rectangles
- You can also draw three dimensional rectangles in
Java - - Warning They really dont 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.
54Polygons
- 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)
-
55Polygons 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)
-
-
56Ovals
- 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)
-
-
57Arcs
- 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)
58Arcs
- 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)
-
-
59The 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
60The 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))
61The 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)