Lecture 6: More Java Advanced Programming Techniques Summer 2003.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Portability and Safety Mahdi Milani Fard Dec, 2006 Java.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 More on Inheritance Overview l Object: The father of all classes l Casting and Classes l Object Cloning l Importance of Cloning.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
Lecture 221 CS110 Lecture 22 Tuesday, April 20, 2004 Announcements –hw10 due Thursday, April 22 –exam next Tuesday, April 27 Agenda –Questions –Error handling.
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Lecture 231 CS110 Lecture 23 Thursday, April 22, 2004 Announcements –hw10 due tonight –exam next Tuesday, April 27 –final exam Wednesday, May 20, 8:00.
From C++ to Java A whirlwind tour of Java for C++ programmers.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Chapter 18 Java Collections Framework
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Programming in Java Dr. M. Ahmadzadeh. Course Outline (subject to tiny changes) I will cover the following but not necessarily in this order. –Strings.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
Programming in Java CSCI-2220 Object Oriented Programming.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
1 Chapter 4 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
CSC Java Programming, Fall, 2008 Week 3: Objects, Classes, Strings, Text I/O, September 11.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Chapter 2 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
OOP Basics Classes & Methods (c) IDMS/SQL News
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Sixth Lecture ArrayList Abstract Class and Interface
University of Central Florida COP 3330 Object Oriented Programming
Programming in Java Text Books :
Java Programming Language
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Strings in Java.
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
CMPE212 – Reminders Assignment 2 due next Friday.
Review for Midterm 3.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

Lecture 6: More Java Advanced Programming Techniques Summer 2003

API Best reference is online:

Garbage Collection All memory allocated on the heap that is no longer referenced is freed up by the Garbage Collector There is no telling when that will happen There is a way to force garbage collection if needed (System.gc())

Java procedures are mainly call by reference This means that procedures can easily alter objects passed to them as parameters.

Building your own exceptions. Class ArgumentNegativeException extends Exception{};

Programming with exceptions. class Factorial{ Public static int compute(int k) throws ArgumentNegativeException, other exceptions { if (k<0) throw new ArgumentNegativeException(); else return 1; } (and later in a program) …. try { System.out.println (“answer is: “ + Factorial.compute(n)); } catch(ArgumentNegativeException e) { System.err.println(e + “oops”); continue; }; ….

super used to call the parent class's constructor, with arguments if desired, using the syntax super(arg0, arg1,...). must be the very first line in every constructor unless omitted, in which case it will be automatically inserted without arguments super.xxx( ) to call methods of the parent only goes one level up (no super.super)

Java lacks some C++ features No templates. But superclass is Object. Could program a stack class with Objects, and then cast into an object of another class. Exception: primitive data types such as int, float are not subclasses of Object. However, there are wrapper classes Integer, Double, etc. No overloading of operators (although function overloading is okay). No i/o operators >. No general multiple inheritance.

No environment variables in Java No such thing as environment variables as there are with C/C++ and Unix because this is not OS independent. There’s a system property setting mechanism that accesses properties declared in the command line invocation called System.getProperty()… read about it in the Java documentation.

instanceOf can upcast and downcast, but wrong cast can cause exceptions during runtime To check whether a certain object is of a particular class use instanceOf

keyword this To invoke one method from another in the same class an object must send a message to itself this.methodName( ) does the job To refer to a field, use this.fieldName When no ambiguity is possible, this is optional private String text; public Greeting(String text) { this.text = text; }

Object equals(Object e) finalize() hashCode() toString()

Java Arrays Objects, but not built with new Array C like syntax Size must be known at instantiation Homogeneous (all elements of same type) Can contain primitive types

Array Syntax, Idioms // declare & initialize (allocate from heap) int[] a = new int[3]; // stylish Java int b[] = new int[6]; // like C, less good // note scope of i in for loop (like C++) for (int i = 0; i < a.length; i++) System.out.println(“a[” + i + “] =” + a[i]); b = a; // a, b reference same array // old b can be garbage collected String[] colors={"red","blue","green"};

Command line arguments class CommandLineArgsDemo.java public static void main( String[] args ){ for (int i = 0; i < args.length; i++) System.out.println('|' + args[i] + '|'); } % java CommandLineArgsDemo foo bar "b q" |foo| |bar| |b q| args[0] isn’t program name

Java 2D Arrays char[][] board = new char[8][8]; for(int y=0; y < board.length; y++) { for(int x=0; x < board[y].length; x++) System.out.print(board[x][y]); System.out.println(); }

Collections in Java Manipulate grouped data as a single object Java provides List, Set, Map add, contains, remove, size, loop over, sort, … Insulate programmer from implementation array, linked list, hash table, balanced binary tree Like C++ Standard Template Library (STL) Can grow as necessary Contain only Objects (reference types) Heterogeneous Can be made thread safe (simultaneous access) Can be made unmodifiable

List Like an array elements have positions indexed 0…size( )-1 duplicate entries possible Unlike an array can grow as needed can contain only Objects (heterogeneous) easy to add/delete at any position API independent of implementation (ArrayList, LinkedList)

Set Like a List can grow as needed can contain only Objects (heterogeneous) easy to add/delete API independent of implementation (HashSet, TreeSet) Unlike a List elements have no positions duplicate entries not allowed

Collection API methods (some) int size(); boolean add( Object obj ); returns true if Collection changes as a result of the add (it always will for List, may not for Set) boolean contains( Object obj ); to see the rest, study the API (warning: look at List, not List (a GUI class)

Iterator Interface // suppose Collection of Programmer objects Iterator iter = engineers.iterator(); while (iter.hasNext()) { Programmer p = (Programmer)iter.next(); p.feed("pizza"); } Note cast (Programmer) since Collection and Iterator manage anonymous objects When collection has a natural ordering, Iterator will respect it Supports safe remove() of most recent next

StringTokenizer Like an Iterator for a String Elements are (white space delimited) words StringTokenizer st = new StringTokenizer(“now is the time …”); while (st.hasMoreTokens()) { String word = st.nextToken();... } Should implement Iterator interface (hasNext, next)

Map Table lookup abstraction void put( Object key, Object value) Object get( Object key) can grow as needed any Objects for key and value (keys tested for equality with.equals, of course) API syntax independent of implementation (HashMap, TreeMap) Iterators for keys, values, (key, value) pairs

Conversions String Object String s = “I am ” + obj; invokes obj.toString() s = String.valueOf(Object obj); ditto, and overloaded for primitive types char[], boolean, char, int, long, float, double int Integer.valueOf(String s); // Integer is wrapper class for int Integer Integer.parseInt(String s);

Equality (reminder) for objects, == tests pointer, not contents Object class implements public boolean equals(Object obj) { return this == obj; } public int hashCode(); // probable unique id String class overrides if (g.equals(“goodbye”))... // not == if “goodbye”.equals(g))... // ok too Strings hash as they should for deep copy, override Object clone() // field by field copy

String matches and searches boolean equalsIgnoreCase(String anotherString); int compareTo(String anotherString); // +,-,0 boolean startsWith(String prefix); boolean endsWith(String suffix); boolean regionMatches(int toffset, String other, int ooffset, int len); int indexOf(int ch); int indexOf(String str); int indexOf(..., int fromIndex); int lastIndexOf(...);

Methods Returning/Constructing New Strings concat(String str); // Can also use + replace(char old, char new); // Not in place! substring(int beginIndex); // New string! substring(int beginIndex, int endIndex); toLowerCase(); // New string! toLowerCase(Locale locale); toUpperCase(); toUpperCase(Locale locale); trim();

Class StringBuffer mutable size and content StringBuffer str = new StringBuffer("World"); str.insert(0, "Jello, "); str.append("!"); str.setCharAt(0,'H'); // now "Hello, World!" str.reverse(); // now "!dlroW,olleH" String s = str.toString();

public class File Information about files, not their contents Constructors File(String path) or (String path, String name) or (File dir, String name) Methods boolean exists(), isFile(), isDirectory(), canRead(), canWrite(); long length(), lastModified(); boolean delete(), mkdir(), mkdirs(), renameTo(File dest); String getName(), getParent(), getPath(), getAbsolutePath()

Useful System Constants final, static, portable? WindowsUnix File.pathSeparator;";"":" File.separator;"\""/” System.getProperty ("line.separator")"\n\r""\n" // System.getProperty gets other properties too public static final FileDescriptor in; public static final FileDescriptor out; public static final FileDescriptor err;

Keyword final final class can’t be extended final field can’t be modified final method can’t be overrridden public final class Integer { public static final int MAX_VALUE; // }

Keyword finally try { } catch() { { finally { code here runs whether or not catch runs }

Optimization -O option used to direct compiler to optimize code

JIT Just-In-Time compiler If present, can speed things up How does this work?

What features of Java would you like to talk about?