6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 1 Specific topics of...
-
Upload
morris-alexander -
Category
Documents
-
view
214 -
download
0
Transcript of 6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 1 Specific topics of...
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
1
Specific topics of the Java Language Related to This Class
Classes and objects (section 1.1) Methods (section 1.2) Variables and expressions (section 1.3) Control flow (section 1.4) Arrays (section 1.5) Input and Output (section 1.6) Packages (section 1.8) Exceptions (section 2.3) Interfaces (section 2.4) Casting (section 2.4.4)
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
2
Classes, Types and Objects
In Java, data structures and algorithms are implemented using classes and objects.
Every object is an instance of a class, which defines the type of data that the object stores, as well as the kinds of operations that can act on that data.
Members of a class in Java: Instant variables Methods
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
3
How Classes Are Declared
The syntax for a Java class definition:
[<class_modifiers>] class <class_name>
[extends <superclass_name> ]
[implements <interface_1>, <interface_2>,…] {
// class methods and instance variables definitions go here…
}
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
4
Example
http://ww3.java3.datastructures.net/source/ch01/Java/Gnome-Gnome.html
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
5
Class Modifier
abstract: describes a class that has abstract methods. A class that has nothing but abstract methods and has no instance variables is called an interface.
final: describes a class that has no subclasses. public: describes a class that can be instantiated or
extended by anything in the same package or by anything that imports the class. All public classes are declared in their own separate
file called <classname>.java . There can only be one public class per file!
friendly: describes a class that can be instantiated or extended by anything in the same package. This is the default class modifier.
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
6
Base Types (primitive type)
Not objectsboolean Boolean value: true or false
(different from c++) char 16-bit Unicode character
(different from c++)byte 8-bit signed integershort 16-bit signed integerint 32-bit signed integerlong 64-bit signed integerfloat 32-bit floating-point numberdouble 64-bit floating-point number
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
7
Objects
The new operator creates a new object from a specified class and returns a reference to that object. Allocate memory for new object and initialize all
instance variables. The appropriate constructor is called. new operator returns a reference ( a memory address)
to the object variable. Syntax:
<variable_name> = new <class_type>([param,param,…]);
Example: myGnome = new Gnome();
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
8
Number Objects
Base type numbers are not objects. What if we want to store numbers as objects?
Java defines a wrapper class for each numeric base type : number classes
Base Type Class Name Creation Example Access Example
byte Byte n= new Byte((byte) 34); n.byteValue();
short Short n= new Short((short) 100); n.shortValue();
int Integer n= new Integer(1045); n.intValue();
long Long n= new Long(10849L); n.longValue();
float Float n= new Float( 3.943F); n.floatValue();
double Double n= new Double( 3.934); n.doubleValue();
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
9
String Objects
A string is a sequence of characters that comes from some alphabet, which is a set of characters.
Each character in a string has index starting from 0. String P = “hogs and dogs”;P[2] = ‘g’
Primary operation for combining strings: concatenation (+)String s = “kilo” + “meters”; S is “kilometers” now.
Every object in Java is assumed to have a built-in method toString() that returns a string associated with the object.
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
10
Instance Variables Instance variables must have a type, which can either be a base
type or a class. Syntax for declaring an instance variable:
[<variable_modifier>] <variable_type> <variable_name> [=<initial_value>];
public class Gnome { // Instance variables: protected String name; protected int age; protected Gnome gnome_buddy; private boolean magical = false; public double height = 2.6; // in feet public static final int MAX_HEIGHT = 3; // maximum height // Method definition would go here…
}
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
11
Variable Modifiers public: anyone can access public instance variables. protected: only methods of the same package or of subclasses
can access protected instance variables. private: only methods of the same class (not methods of a
subclass) can access private instance variables. friendly: default, can be accessed by any class in the same
package. static: declare a variable that is associated with the class, not
with individual instances of the class. Static variables are used to store “global” information about
a class. Static variables exist even if no instance of their class is
created. final: must be assigned an initial value, and then can never be
assigned a new value after that. If it is a base type, then it is a constant. If it is an object variable, then it will always refer to the same
object.
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
12
Method
A method definition has two parts: Signature: name and parameters. Body: defines what the method does.
A method allows a programmer to send a message to an object. Syntax:
<method_modifiers>] <return_type> <method_name> ([params]) {// method body…}
Example:public void renameGnome(String s) {name = s; // Reassign the name instance variable of this gnome}
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
13
Method Modifiers public: anyone can access public methods. protected: only methods of the same package or of subclasses
can access protected method. private: only methods of the same class (not methods of a
subclass) can access a private method. friendly: default, can only be called by objects of classes in the
same package. abstract: no code. Abstract methods may only appear within an
abstract class.public abstract void setHeight (double newHeight);
static: is associated with the class, not with specific instances of the class. Static methods can be used to change the state of static
variables associated with a class. final: cannot be overridden by a subclass.
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
14
Parameters
All parameters in Java are passed by value. Any time we pass a parameter to a method, a
copy of that parameter is made for use within the method body.void f(int a) { int b = 1;
a = a+1; f(b);
}
b=?
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
15
Another Example
void f(Gnome a) {
a. renameGnome (“newname”);
}
Gnome b = new Gnome();
// b. getRealName() returns “Rumple“
f(b);
b. getRealName() returns ?
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
16
Constructor Methods
A constructor is a special kind of method that is used to initialize newly created objects.
Syntax is the same as that of any other method. But there are several differences: The name of the constructor must be the same as the
name of the class it constructs. A constructor has no return value; An abstract, static, or final constructor is not allowed. Constructors are invoked in a unique way: they must
be called using the new operator. A class can have many constructors, but each must
have a different signature.
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
17
The main Method
Classes that define stand-alone programs must contain the main method.
The main method must be declared as follows:public static void main(String[ ] args) {
//main method body …}
java Aquarium 45args[0] refers the string “45”
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
18
Statement Blocks and Local Variables
The body of a method is a statement block, which is a sequence of statements and declarations to be performed between the braces “{“ and “}”.
Statement blocks can contain declarations of local variables.
Local variables are similar to instance variables, but they only exist while the statement block is being executed.
Example: http://ww3.java3.datastructures.net/source/ch01/Java/Gnome-Gnome.html
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
19
Expressions
Variables and constants are used in expressions to define new values and to modify variables.
Expressions involve the use of literals, variables, and operators.
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
20
Literals
A literal is any “constant” value that can be used in an assignment or other expression. The null object reference (this is the only object literal) Boolean: true and false; Integer: 176, -52, 176L, -52L Floating point: 3.1415, 3.1415F, 2.14E2 Character: ‘a’ or ‘?’
Special character constants: ‘\n’, ‘\t’,’\b’, ‘\r’, ‘\f’, ‘\\’, ‘\’’, ‘\”’
String literals: “dogs all around” or “jump”
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
21
The Assignment Operator “=“
Syntax: <variable> = <expression>
i=j=25; // works because “=“ operators are evaluated right-to-left.
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
22
Dot Operator “.” Use dot operator to access the members of the object Syntax:
<object_reference>.<method_name>([<param>,<param>,…]);
overn.cookDinner(food); Or <object_reference>.<variable_name>
gnome.name If an object reference is not final, then it can appear on the left-
hand side of an assignment as well. gnome.name = “Professor Smythe”; gnome.age = 132;
The <object_reference> can also be any expression that returns an object reference. Gnome g = new Gnome(); String buddyName = (g.gnome_buddy).name;
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
23
Arithmetic Operators
+ addition - substraction * multiplication / division % modulo
n % m = r, such that n = mq + r, for an integer q and 0 <= r < n.
13 % 3 =? 3 % 13 = ?
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
24
Increment and Decrement Operators
++ increment operator -- decrement operator
int i = 8; int j = i++; int k = ++i; int m = i--; int n = 9 + i++; what is i, j, k, m, n now?
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
25
Logical Operators
< less than <= less than or equal to == equal to != not equal to >= greater than or equal to > greater than
Operators that operate on boolean values: ! not(prefix) && conditional and || conditional or
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
26
Bitwise Operators
~ bitwise complement (prefix unary operator)
& bitwise and | bitwise or ^ bitwise exclusive-or << shift bits left, filling in with zeros >> shift bits right, filling in with sign bit >>> shift bits right, filling in with zeros
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
27
Operational Assignment Operators
Syntax: <variable> <op> = <expression>; This is equivalent to <variable> = <variable> <op> <expression>;
i = 5; i += 5; i = ?
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
28
Operator Precedence
determine the order in which operations are performed when the absence of parentheses brings up evaluations ambiguities.
Table 1.3, p22 in the textbook What is: 5 + 21 / 4 % 3
= (5 + ((21 / 4) % 3))
= (5 + ( 5 % 3 ))
= (5 + 2)
= 7
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
29
Casting in Expressions
change the type of a variable. Syntax: (<desired_type>) <variable>;
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
30
Ordinary Casting
Possible among all integer and floating types, may lose precision
Possible among some class referencesdouble d1 = 3.2;
double d2 = 3.9999;
int i1 = (int) d1; // i1 has value 3
int i2 = (int) d2; // i2 has value 3
double d3 = (double) i2; // d3 has value 3.0
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
31
Casting with Operators
int i1= 3;
int i2 = 6;
dresult = (double) i1 /(double) i2; // dresult is 0.5
dresult = i1 / i2; //dresult is 0.0;
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
32
Implicit Casting
Applied automatically when no information lost float → double byte → short → int→ long int→ double
int iresult, i = 3;
double dresult, d = 3.2;
dresult = i / d; // dresult is 0.9375
iresult = i / d; // compilation error, loss of precision
iresult = (int) i/d; // iresult is 0
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
33
Implicit Casting with String Objects
Explicit casting of an object or base type to a string is not allowed.String s = (String) 4.5; //wrongString t = “Value =“ + (String) 13; //wrongString u = 22; //wrong
Use toString method or perform an implicit cast via the concatenation operation.String s = “” + 4.5; // correct, but poor styleString t = “Value = “ + 13;String u =Integer.toString(22);
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
34
Control Flow – if/else
Syntaxif (<boolean_expr>)
<true_statement>
[else if (<boolean_expr>)
<else_if_statement>]
[else
<else_statement>] Unlike C and C++, the expression in an if statement
in Java must be a Boolean expression. if ( i = 5) //wrong
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
35
Switch
int i = 3;
switch (i) {
case 3: System.out.println(“3”); break;
case 5: System.out.println(“6”); break;
default: System.out.println(“Default”); break;
}
What is printed? What if no break statements?
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
36
Loops
while (<boolean_expression>)<loop_body_statement>
for ([<initialization>];[<condition>];[<increment>])<body_statement>example: for(int i = 0; i < 100, i++) { ...}
do<loop_body_statement>
while (<boolean_expression>)
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
37
Explicit Control-Flow Statements
Returning from a Method If a Java method is declared with return type of void,
then flow of control returns when it reaches the last line of code in the method or when it encounters a return statement with on argument.
If a method is declared with a return type, it exits when it reaches a return statement.
public boolean checkBDay (int date){if (date == Birthdays.MIKES_BDAY) {
return true;}return false;
}
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
38
The break Statement It is used to “break” out of the innermost switch, for, while, or do-
while statement body. The break statement can also be used in a labeled form to jump
out of an outer-nested loop or switch statement.public static boolean hasZeroEntry (int[ ][ ] a) {
boolean foundFlag = false; zeroSearch:
for (int i=0; i<a.length; i++) { for (int j=0; j<a[i].length; j++) { if (a[i][j] == 0) { foundFlag = true; break zeroSearch; } }}return foundFlag;
}
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
39
The continue Statement Syntax: continue [<label>]; The continue statement can only be used inside loops. The continue statement causes the execution to skip over the
remaining steps of the loop body in the current iteration.public static boolean hasZeroEntry (int[ ][ ] a) {
boolean foundFlag = false; zeroSearch:
for (int i=0; i<a.length; i++) { for (int j=0; j<a[i].length; j++) { if (a[i][j] == 0) { foundFlag = true; continue zeroSearch; } }}return foundFlag;
}
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
40
Arrays
An array is a number collection of variables all of the same type.
Index starts from 0. <array_name>.length holds allocated number of
elements.
int [ ] myArray = new int[20];
myArray.length is 20 Two-dimensional array is actually an array of array:
float[ ][ ] x = new float[8][10];
x[4].length is 10
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
41
Simple Output Methods System.out is a built-in static object, that performs output to the
“standard output” device. Methods:
print(Object o):print the object o using its toString method. print(String s): print the string s. print(<base_type> b): print the base type value b. println(String s): print the string s, followed by the newline character. flush():print and empty the contents of the print buffer.
System.out.print(“Java values: “);System.out.print(3.1415);System.out.print (‘,’);System.out.print(15);System.out.print(“ (double,char,int). “);
Java values: 3.1415,15 (double,char,int).
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
42
Simple Input Methods System.in, perform input from the Java console window. System.in object is an instance of the java.io.InputStream class, which is defined to proceed one character
at time. java.io.BufferedReader and java.io.InputStreamReader processe input in a streaming and buffered way.
java.io.BufferedReader stndin; //standard input (buffered)String line;double sum, d = 0.0;int i = 0;stndin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));System.out.print(“Input a double: “);System.out.flush();if ((line = stndin.readLine() != null)
d = Double.valueOf(line).doubleValue();System.out.println(“Input an int: “);System.out.flush();if ((line = stndin.readLine()) != null)
i = Integer.valueOf(line).intValue();sum = d + i;System.out.println(“Their sum is “ + sum + “.”);
Input a double: 6.1078Input an int: 209Their sum is 215.1078.
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
43
Packages A set of related classes under a common subdirectory. Every file in a package starts with the line:
package <package_name>; The subdirectory containing the package must be named the same as the
package. Using other packages:
public boolean Temperature(TA.Measures.Thermometer thermometer, int temperature) { ....}
Import packages:import <packageName>.<classNames>;
package Project;import TA.Measures.Thermometer;import TA.Measures.Scale;
or import TA.Measures.*
public boolean Temperature(Thermometer thermometer, int temperature) { ....}
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
44
An Example Program
CreditCard http://ww3.java3.datastructures.net/source/ch01/Java/CreditCard-CreditCard.html
Test http://ww3.java3.datastructures.net/source/ch01/Java/Test-CreditTest.html
Output http://ww3.java3.datastructures.net/source/ch01/Java/output2-credit.html