Lecture slides

Download Report

Transcript Lecture slides

CSC 243 - Java Programming,
Spring, 2014
Week 3: Objects, Classes, Strings,
Text I/O
Methods within Classes
• Constructor has same name as class.
• It may be overloaded, like any method. Each
variant has a different set of parameter types.
• Constructor initializes a new object of the
class when new is invoked on the Constructor.
• An Access Method retrieves data.
• A Mutator Method modifies an object.
• There are no Destructors in Java!
Objects and References
• An object is accessed via a reference, which
acts like a pointer in C++.
• String a = new String(“A”); String b = a ;
a
String object
b
• Assignment copies the reference.
• == compares references (exactly the same object when
true)
• object.equals() compares two objects using an objectspecific equals operation.
Reference equality !=
Object equality
public class main {
public static void main(String [] args) {
String a = new String("A") ;
String b = a ;
System.out.println("after pointer copy a == b -> “ + String.valueOf(a == b) +
", a.equals(b) -> " + String.valueOf(a.equals(b)));
a = new String("A") ;
System.out.println("after reconstruction a == b -> “ + String.valueOf(a == b) +
", a.equals(b) -> " + String.valueOf(a.equals(b))); } }
$ java strings.PtrCompare
after pointer copy a == b -> true, a.equals(b) -> true
after reconstruction a == b -> false, a.equals(b) -> true
chars, Characters and Strings
• A char is a primitive type.
• A Character is a wrapper class for char.
• A String is a class known to the compiler.
• String objects are immutable.
• “abc” compiles as an interned (unique) String object.
• StringBuffer is a mutable string class.
• StringBuilder is a non-multithread-safe, efficient variant
of StringBuffer.
• Conversion methods abound!
A StringBuilder object can
serve as a text template
• String editing operations
•
•
•
•
•
indexOf() to search
delete from start to end-1
replace from start to end – 1
insert before start index
replaceCharAt for individual characters
• /export/home/faculty/parson/JavaLang/strings
• cp ~parson/JavaLang/strings.zip ~/JavaLang
• cd ~/JavaLang ; unzip strings.zip ; cd ./strings
• gmake clean test
Text File I/O
• import java.io.PrintWriter ;
• PrintWriter output = new PrintWriter(filepath);
• print, println and printf (formatted output) methods
• Just like System.out and System.err.
• import java.util.Scanner ;
•
•
•
•
•
java.io.File(filepath) gets at directory information.
Scanner input = new Scanner(new File(filepath));
Scanner input = new Scanner(System.in);
hasNextTYPE() controls looping over input items.
nextTYPE() scans and returns these items.
Programming practices
• Always handle exceptions!
• We may handle some by explicitly ignoring them.
•
•
•
•
Always use { curly braces } for control blocks.
Use coding standards that we discuss in class.
Write Javadoc documentation.
Use both healthy and degenerate tests.
» Ignoring these rules will cost you points.