CS Programming Language Java. Fall 2004 Sept. 29

Similar documents
CONTAİNERS COLLECTİONS

5/23/2015. Core Java Syllabus. VikRam ShaRma

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

Fundamentals of Object Oriented Programming

15CS45 : OBJECT ORIENTED CONCEPTS

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students. Collections. Play with problem set 1

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Index COPYRIGHTED MATERIAL

Java Object Oriented Design. CSC207 Fall 2014

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

Generics. IRS W-9 Form

CS Programming Language - JAVA. Fall 2004 Sept. 15th

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS

Introduction to Programming Using Java (98-388)

Fundamental language mechanisms

Core Java Syllabus. Overview

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Programming II (CS300)

JAVA MOCK TEST JAVA MOCK TEST III

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

Inheritance and Interfaces

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Lecture 16: Case Study: The Java Collections API

Today. Instance Method Dispatch. Instance Method Dispatch. Instance Method Dispatch 11/29/11. today. last time

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Chapter 6 Introduction to Defining Classes

COP 3330 Final Exam Review

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

CS 11 java track: lecture 3

20 Most Important Java Programming Interview Questions. Powered by

Programming II (CS300)

Java: exceptions and genericity

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

CMSC 132: Object-Oriented Programming II

Exception-Handling Overview

CSE 143. More ArrayIntList; pre/post; exceptions; debugging. Computer Programming II. CSE 143: Computer Programming II

Adam Blank Lecture 3 Autumn 2016 CSE 143. Computer Programming II

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Object-Oriented Programming

CS 251 Intermediate Programming Inheritance

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References

Compaq Interview Questions And Answers

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

JAVA. Duration: 2 Months

Absolute C++ Walter Savitch

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

CS 231 Data Structures and Algorithms, Fall 2016

Announcements/Follow-ups

Selected Java Topics

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

CS112 Lecture: Exceptions and Assertions

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Programmieren II. Polymorphism. Alexander Fraser. June 4, (Based on material from T. Bögel)

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Classes, interfaces, & documentation. Review of basic building blocks

CS260 Intro to Java & Android 03.Java Language Basics

Abstract Classes, Exceptions

Java Overview An introduction to the Java Programming Language

1 Shyam sir JAVA Notes

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics

Building Java Programs

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Java Collections Framework

EXCEPTION HANDLING. Summer 2018

Full file at Chapter 2 - Inheritance and Exception Handling

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel)

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 10 Classes Continued. Fundamentals of Java

Objects and Iterators

Highlights of Last Week

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

PIC 20A Collections and Data Structures

Java Language Features

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

CS159. Nathan Sprague

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Core Java Contents. Duration: 25 Hours (1 Month)

CS 221 Review. Mason Vail

Java classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Exceptions and Design

CS/ENGRD 2110 SPRING 2018

Transcription:

CS3101-3 Programming Language Java Fall 2004 Sept. 29

Road Map today Java review Homework review Exception revisited Containers I/O

What is Java A programming language A virtual machine JVM A runtime environment JRE Predefined libraries Portable, but slow Interpreter JIT helps

Object and class A class is a blueprint An object is an instance created from that blueprint All objects of the same class have the same set of attributes Every Person object have name, weight, height But different value for those attributes ke.name=ke Wang, sal.name=sal Stolfo

Class Person: illustration Name: Ke Wang ke height: 0 weight: 0 sal Name: Salvatore J. Stolfo height: 0 weight: 0

Reference Person ke; //only created the reference, not an object. It points to nothing now (null). ke = new Person(); //create the object (allocate storage in memory), and ke is initialized. ke.name= Ke Wang ; //access the object through the reference Can have multiple reference to one object No reference means the object is inaccessible forever goes to garbage collector

Class Person: variables Name: Ke Wang ke height: 0 weight: 0 x sal Name: Salvatore J. Stolfo height: 0 weight: 0 references objects

Arrays in Java: declaration Declaration int[] arr; Person[] persons; Also support: int arr[]; Person persons[]; (confusing, should be avoided) Creation int[] arr = new int[1024]; int [][] arr = { {1,2,3}, {4,5,6} }; Person[] persons = new Person[50];

Arrays in Java: safety Cannot be accessed outside of its range ArrayIndexOutOfBoundsException Guaranteed to be initialized Array of primitive type will be initialized to their default value Zeroes the memory for the array Array of objects: actually it s creating an array of references, and each of them is initialized to null.

Arrays in Java: second kind of reference types in Java int[] arr = new int [5]; arr int[][] arr = new int [2][5]; arr arr[0] arr[1]

Reference vs. primitive Java handle objects and arrays always by reference. Java always handle values of the primitive types directly differ in two areas: copy value compare for equality

Visibility of fields and methods Generally make fields private and provide public getfield() and setfield() accessor functions O-O term: encapsulation Private fields and methods cannot be accessed from outside of the class.

Static vs. non-static Static: class variable/method Non-static: instance variable/method Static ones are associated with class, not object. Can be called using class name directly main() is static Even though it s in a class definition, no instance of the class exist when main starts executing

Static vs. non-static (cont.) Instance fields define an object; the values of those fields make one object distinct from another Instance method operates on an instance of a class (object) instead of operating on the class itself. Class methods can only use class fields; while instance methods can use both instance fields and class fields

Keyword this Invisible additional parameter to all instance methods Value is the instance through which it was called tc.instancemethod(); -> this=tc Three common usage Same name variable Passing the object myself Call another constructor

Constructor Method with same name as class No return type Called automatically by new() Java provides a default one No parameter, default initialization (0/null) User can define their own The default one is gone

Method overloading Same method name and return type, different parameter list Different type, order, number Return type is NOT enough

Inheritance Child class can extend parent class Gets all the parent s fields and methods Private vs. protected Can use child for anything that s expecting parent (upcasting) But not vice-versa Can only extend one class No multiple inheritance

Inheritance Class Foo extends Bar { Can override parent s implementation Other classes that only know Bar can use Foo as well, but not any extra methods Foo added

polymorphism We have an array of Shapes, and we ask each Shape to draw() itself The correct method will be called The Circle s draw() method if the Shape object is actually Circle, Square s draw() if it s actually a Square O-O term: polymorphism

The Master Class All Classes extend Object class Thus Object references are universal references Like void * tostring()

Abstract classes and interfaces Don t provide implementation for some/all methods Can not be instantiated Subclasses that wish to be instantiable must implement all abstract/interface methods Allows us to provide a contract without a default implementation Can have references to abstract classes and interfaces Can implement as many interface as we want

Encapsulation keywords Public: everyone Private: same class only Protected: self and subclasses Control visibility

Keyword final Like C++ const Field: value cannot be changed once set Does not be to initialized blank final Convention: make name all CAPS, e.g. Math.PI Method: cannot be overridden Class: cannot be extended

Command line arguments Show up in that String[] args array passed to main() Note the first parameter is args[0] Not the name of the class/program Java Foo param1 param2 All in String object, parse if necessary Can check args.length to see the number of parameters

Homework review HW1: MyDate.java Validity check Leap year HW2: AccountTest.java

Explosions void method1() { method2()} void method2() { method3()} void method3() { x=5/0} //BOOM!! method3 method2 method1

Error handling Java philosophy: badly formed code will not be run Ideal time to catch error: compile Not all errors can be detected at compile time; the rest must be handled at run time Java: exception handling The only official way that Java reports error Enforced by compiler

Unexpected situation User input errors Device errors Physics limits Programmer errors

Exceptions are objects throw new IOException(); throw new IOException( file not open ); Exception IOException SQLException RuntimeException IllegalArgumentException NumberFormatException

Catching an exception Guarded region Try block Exception handler try{ //code that might generate exceptions } catch (Type1 id1){ // handle exception for Type1 } catch (Type2 id2){ // handle exception for Type2 } Only the first catch block with matching exception type will be execute

Create your own exception Create your own to denote a special problem Example: ExceptionTest.java

RuntimeException Always thrown automatically by Java You can only ignore RuntimeException in coding, all other handling is carefully enforced by compiler RuntimeException represents programming error NullPointerException ArrayIndexOutOfBoundsException NumberFormatException

Finally clause clean up Always execute, regardless of whether the body terminates normally or via exception Provides a good place for required cleanup Generally involves releasing resources, for example, close files or connections try{ //code that might throw A or B exception } catch (A a){ // handler for A } catch (B b){ //handler for B } finally { //activities that happen every time, do cleanup }

When to use Exception 90% of time: because the Java libraries force you to Other 10% of the time: your judgement Software engineering rule of thumb Your method has preconditions and postcondition If preconditions are met, but you can t fulfill your postcondition, throw an exception

Containers Hold a group of objects Significantly increase your programming power All perform bound checking array: efficient, can hold primitives Collection: a group of individual elements List, Set Map: a group of key-value object pairs HashMap Misleading: sometimes the whole container libraries are also called collection classes

array Most efficient way to do random access Size is fixed and cannot be changed for the lifetime If run out of space, have to create a new one and copy everything Advantage: can hold primitives

Other containers Can only take object Have to wrap primitives int -> Integer, double-> Double Have to cast or unwrap on retrieval Slow, error prone, tedious. Fixed by JDK1.5, hopefully Advantage: automatic expanding

Arrays class In java.util, a wrapper class for array A set of static utility methods fill(): fill an array with a value equals(): compare two arrays for equality sort(): sort an array binarysearch(): find one element in a sorted array All these methods overload for all primitive types and Object

Arrays.fill() Arrays.fill(arrayname, value) Assigns the specified value to each element of the specified array Arrays.fill(arrayname, start, end, value) Assigns the specified byte value to each element of the specified range of the specified array Value s type must be the same as, or compatible with the array type

Arrays.fill() Example import java.util.*; int[] a1=new int[5]; Arrays.fill(a1, 0, 2, 2); // [2, 2, 0, 0, 0] Arrays.fill(a1, 4); // [4, 4, 4, 4, 4] Arrays.fill(a1, 2, 4, 5); //[4, 4, 5, 5, 4] String[] a2 = new String[5]; Arrays.fill(a2, 1, 5, hi ); // [null hi hi hi hi] Arrays.fill(a2, 0, 6, columbia ); //error! IndexOutOfBound

System.arraycopy() Overloaded for all types Shallow copy only copy reference for objects, copy value for primitives (src_array, src_offset, dst_array, dst_offset, num_of_elements) int[] a1=new int[5]; Arrays.fill(a1, 2, 4, 4); // [0, 0, 4, 4, 0] int[] a2 = new int[7]; Arrays.fill(a2, 6); // [6, 6, 6, 6, 6, 6, 6] System.arraycopy(a1, 0, a2, 2, 5); //a2= [6, 6, 0, 0, 4, 4, 0]

Arrays.sort() Sorts the objects into ascending order, according to their natural ordering This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort You can specify a range. The range to be sorted extends from index fromindex, inclusive, to index toindex, exclusive. The objects need to comparable or there is a special comparator

Arrays.sort() cont. sort(array), sort(array, fromindex, toindex) All elements in the array must implement the Comparable interface sort(array, comparator) sort(array, fromindex, toindex, comparator) All elements in the array must be mutually comparable by the specified comparator

Comparable interface With a single method compareto() Takes another Object as argument And returns: Negative value if this is less than argument Zero value if this is equal to argument positive value if this is greater than argument

Comparator interface Two methods: compare(), equals() Only need to implement compare() Takes two Object as argument: compare(object o1, Object o2) And returns Negative value if o1 is less than o2 Zero value if o1 is equal to o2 positive value if o1 is greater than o2

Sort example: compareexp.java

Array.binarySearch() Only usable on sorted array! Otherwise, result unpredictable If there are multiple elements equal to the specified object, there is no guarantee which one will be found. Return: Location if find the key (positive number) (-(insertion point) - 1) if not find key (negative)

search example: compareexp.java

Collection: hold one item at each location List: items in order Set: no duplicates, no ordering ArrayList List LinkedList Vector Collection Preserve the insertion of the elements Set HashSet LinkedHashSet TreeSet

Map: key-value pairs, fast retrieval no duplicate keys, no ordering HashMap LinkedHashMap Map Hashtable TreeMap Preserve the insertion of the elements

Disadvantages of container Cannot hold primitives Have to wrap it Lose type information when put object into container Everything is just Object type once in container Have to do cast when get it out You need to remember what s inside Java do run time type check ClassCastException

ArrayList An array that automatically expand itself Put objects using add() Get out using get(int index) Need to cast type Method size() to get the number of objects Similar to.length attribute of array Example: CatsAndDogs.java

Iterator object Access method regardless of the underlying structure Generic programming Can change underlying structure easily light-weight object Cheap to create Can move in only one direction

Iterator constraints Container.iterator() returns you an Iterator, which is ready to return the first element in the sequence on your first call to next() Get the next object in the sequence with next() Set there are more objects in the sequence with hasnext() Remove the last element returned by the iterator with remove() Example: revisit CatsAndDogs.java

ArrayList vs. LinkedList ArrayList Rapid random access Slow when inserting or removing in the middle LinkedList Optimal sequential access Fast insertion and deletion from the middle addfirst(), addlast(), getfirst(), removefirst() Easy to be used as queue, stack

Set interface Each element add to the Set must be unique, otherwise won t add. Objects added to Set must define equals() to establish object uniqueness Not maintain order

Set HashSet Fast lookup time by hashing function TreeSet Ordered Set backed by a tree (red-black tree) Can extract ordered sequence LinkedHashSet Has the lookup speed of a HashSet Maintain the insertion order by linked list

Set example revisit CatsAndDogs.java

Map interface Key-value associative array Look up object using another object Array use index put(object key, Object value) Object get(object key) containskey(), containsvalue()

Map HashMap Based on a hash table Constant time for insertion and locating pairs Most commonly used LinkedHashMap Like HashMap When iterate through, get pairs in insertion order TreeMap Based on red-black tree, can viewed in order Need to implement Comparable or Comparator

Map example MapExample.java