COSC1030 COSC1030 DATA STRUCTURES IN JAVA
Jan 13, 2016
COSC1030COSC1030
DATA STRUCTURES IN JAVA
Important NotesImportant Notes
Final drop date – July 13Web site is our information center Check web site before raising questionsEnrollment or change session – go to officeRead Ch. 1 before next lecture
Course PlanCourse Plan
11 1/2 Lectures– May have quiz in class
4 Assignments worth 5% each– Expect Reports plus programs
Midterm Exam worth 30%– Common Midterm
Final 50%– Common Final
LecturesLectures
May 29 – Java Review June 5 – SE Concepts & Comp Complexity June 12 – Object Reference (A1 Due) June 19 – Recursion June 26 – Linear Data Structure (A2 Due) July 3 – Midterm July 10 – Modularity & Data Abstraction
July 17 – List, String and DMA (A3 Due)
Lecture (continued)Lecture (continued)
July 24 – TreesJuly 31 – Hash Table (A4 Due)August 7 – Sorting 1August 14 – Sorting (2) Final Exam
JAVA ReviewJAVA Review
Main Features of JAVA JAVA Language entities Name and Scope Data Types Operations & Expression Control Flows Classes and Objects Fields and Methods
Main Features of JAVAMain Features of JAVA
JAVA Platform– Portable, Byte Code, Interpreter
Network Enabled– Applets, URL
Security– Signed Jars, Sandbox Model
Multi Thread– Concurrent, Synchronized Method
Main Features of JAVAMain Features of JAVA
Strong Typed – Type Checking at Compilation Time – Dynamic Checking for Casting
Exception HandlingGarbage CollectionThin Core + Expandable Library OOP
JAVA Language EntitiesJAVA Language Entities
Literatures Variables Expressions Statements Labels Methods Types Classes and Interfaces Packages
LiteralLiteral
Atomic values without a name– 27, 033, 0x1B, 1L – 3.1415 1. .1 1.0E-10 10F– ‘A’, ‘á’,‘\n’– “This is a literature.”– true, false
static final int ZERO = 0– ZERO is not a literature, it’s a named constant
IdentifierIdentifier
A simple name of a– package, type, variable or method
Declaration – Specifies the kind of entity that the Id denotes
Definition– Implements the entity it specifies
Declare before use
package com.ibm.anything;
public interface IFace { // com.ibm.anyting.IFace
public static final int ZERO = 0;
public void foo();
}
import com.ibm.anything.IFace;
public class Biz implements IFace {
private int i = 0;
private Object obj = new String(“A string object”);
public Biz() { i = (obj == “A String object”) ? 0 : 1; }
public void foo() { System.out.print(“foo()”); }
public void main(String args) {…}
}
NamesNames
Denote to a language entity Simple Form and Dot-form Duplicated Names
– Have the same dot-form– Not allowed
Variable names – field, local, formal parameter Method Names Type names – Primitive, Class & Interface Package Names
Scope of namesScope of names
Scope – a part of a program text in which the entity can be referenced by its simple name
Hidden Scope Due to Overridden A Name May Visible Outside Its Scope Use its dot-name notation.
– a.b.c;– this.c; super.c;– …foo().c;
class Test extends Base { // public int var = 0 is defined in Base
int var = 1;
public Test foo(int var) {
var = 2; // Which var is changed?
try {
int var = 3; // Is this legal?
} catch (Throwable ex) {
int var = 4; // No, both are syntax errors
}
// What are values of super.var, this.var, and var respectively?
// They are 0, 1 and 2 respectively.
}
public void bar() { int var = 5; }
}
Scope of name
VariablesVariables
Field variables– Class Fields– Instance Fields
Local variables Formal Parameters Variable Attributes
– Public, Protected, Private– Static,– Final, Transient, Volatile
Visibility of VariablesVisibility of Variables
Visibility – where it can be referencedA variable is visible within its scope.Field variables
– The scope is the whole class– Public field is visible via object reference– Protected field is visible in sub-classes– Private field can only be accessed in the class
ExpressionExpression
Expression calculates valueEach expression has a static typeThe value generated is of the (sub) typeCreate a new object – constructor Method call is an expression of the return
type
Precedence of OperatorsPrecedence of Operators
Postfix ops : . [exp] (args)exp++ exp-- Unary ops: ++exp –exp +exp –exp !exp ~exp Creation and typecast: new exp (type)exp Multiplicative: * / % Additive ops: + - Shifting ops: << >> >>> Relational ops: < > >= <= instanceof Equality ops: == != Bitwise and, or, and xor: & ^ | Logical and && Logical or || Conditional operation: ? :
Assignment ops: = += -= *= /= %= >>= <<= >>>=
Control FlowControl Flow
Atomic statement – assignmentComposition – S1; S2Branching – if-then-else, switchLooping – for, while, do-whileException handling – try-catch-finalCommunication between objects – Method
invocation
TypeType
Primitive Types– void, int, long, float, double, char, boolean
Reference Types– Array – hosts indexed elements of the same type– String – non mutable sequence of characters– Interface – contract– Class – implementation of a type– Abstract class – customizable common structure,
partially implemented
Array TypeArray Type
Initialize an array int[] ia = new int[3]; System.out.println(ia[0]); // what is the output Shape[] shapes = new Shape[3]; System.out.println(shapes[0]); // what is the output for( int i = 0; i < shapes.length; i++ ) { shapes[i]= new Rectangle(……); } One dimensional array in Java int[][] iaa = new int[3][]; for (int i = 0; i < iaa.length; i++ ) { iaa[i] = new int[i+1]; }
String & StringBufferString & StringBuffer
String is non-mutableString abc = “abc”;
abc = “aBc”; // did not change the string “abc”
String def = “This is ” + abc + “ string”;
StringBuffer sBuff = new StringBuffer();StringBuffer sBuff = new StringBuffer();
sBuff.append(“This is ”);
sBuff.append(abc);
sBuff.append(“ string”);
sBuff.setCharAt(8, ‘A’);
ClassClass
Building block of Java One class one file Extends super class – Object the root of all classes Implements interfaces Template of objects constructed from it A class may declare:
– Fields– Constructors– Methods– Static initialization block
ConstructorsConstructors
Rectangle(int x1, int y1, int x2, int y2) {…} Default constructor – no parameter new Rectangle(0.0, 0.0, 1.0,1.0) Implementation of a constructor
– Initialize all field variables– Call another constructor – this(…)– Call super constructor – super(…) as its first statement– Canonical constructor – do the real job– Other constructors transform parameters and then call
the canonical
Class Rectangle extends Shape {
Point upLeft, buttomRight;
Rectangle (int x1, int y1, int x2, int y2) {
Point p1 = new Point(x1, y1);
Point p2 = new Point(x2, y2);
this(p1, p2); // call canonical constructor
}
Rectangle(Point anUpLeft, Point aButtomRight) {
super(); // call super first
upLeft = anUpLeft; buttomRight = aButtomRight;
}
}
Methods Methods
Method header - Signature– Return type– Method name– Parameters– Exceptions
Overloading methods – same name but different parameters
Overriding methods – defined in subclass with the same signature in the super
Abstract method Canonical method
Summary of Java ReviewSummary of Java Review
Features of Java– Platform independent, network enabled, multi threaded,
interpret, object oriented programming language
Language entities– Name and scope– Primitive & reference types– Classes – Methods, Constructors, Fields & Static block– Arrays – one dimensional array– String and string buffer
Object vs. ClassObject vs. Class
Class is a description of objects – static Class specifies behavior of objects
Object only exists at run time – dynamicObjects differ in types – construction classObjects differ in state – value of their fields
InterfaceInterface
A contract between user and implementerLoosen couple between components Different Implementations from different
vendorsHide implementation details to usersParallel development of a project
Abstract ClassAbstract Class
Partial implementationProvide important conceptsHide implementation detailsCustomizable StructureCustomize by sub-classingA sub-class only needs to implement
unfinished parts
InheritanceInheritance
class SubClass extends SuperClassThe SubClass inherits all fields and
methods from the superFields and methods can be overriddenOverridden fields and methods still visible
via superAdd subclass specific fields and methodsReuse super class
Overloading & OverridingOverloading & Overriding
Overloading– A name used for different meanings– 3 + 5 and “A string” + “another”– Methods with different signatures
Overriding – Re-implement method in sub class– Overridden the method in super class– The method in super still visible– Dynamic binding and polymorphism
class Shape {……
void draw() { // be overridden in sub classes
System.out.println(“Don’t know how to draw a shape”);
}
}
class Rectangle extends Shape { ……
void draw() { // overriding
drawLine(…); drawLine(…); drawLine(…); drawLine(…);
}
void draw(Device device) { // overloading method
drawLine(…, device); …
}
PolymorphismPolymorphism
Select method to be invoked at run time based on dynamic type of the requesting object.
The actual behavior of a name denoted is dynamically determined
Most specific method is invoked
class Shape { void draw() {…} }
class Rectangle extends Shape{
void draw(){…}}
class Circle extends Shape {
void draw() {…}}
Shape myShape = null;
myShape = new Rectangle();
myShape.draw(); // draw rectangle
myShape = new Circle();
myShape.draw(); // draw circle
Important OO ConceptsImportant OO Concepts
Interface and class– Contract vs. implementation
Inheritance– Single inheritance in Java
Method overloading– Different signatures to the same method (name)
Method overriding– Provide specific method implementation in subclass
Polymorphism– Determine which method to invoke at run time