CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 2 cludes materials provided by George Koutsogiannakis and Matt Bauer 1
Jan 18, 2018
CS 116: OBJECT ORIENTED PROGRAMMING II
LECTURE 2
*Includes materials provided by George Koutsogiannakis and Matt Bauer1
Review• In previous lectures we discussed:
– User defined Service classes• Default constructor/ non default constructor(s).• Accessor mutator methods.• toString() method.• Equals() method• Other methods as required by the specification.
– Client classes– How to use a static instance variable.
2
Agenda
• We review the following topics– Using the scanner object to read text files.– Scope of variables within the class.– Useful object methods (equals(), toString())– Enum data type– Java Packages– Javadoc
3
SCANNER CLASS
4
Reading Text Files with Scanner Object
• We need the services of the java.io package and specifically two classes out of that package:– File class– IOException class
• Therefore we need to import those library classes
• Note: Alternatively one can import all the library classes out of package java.io by typing:
import java.io.*;
5
import java.io.File;import java.io.IOException;
Reading Text Files with Scanner Object
• Trying to open a file for reading (or writing) can cause problems (called exceptions)
• What are exceptions?– “An exception is an event that occurs during the execution of a
program that disrupts the normal flow of instructions.”*• How do deal with exceptions?
– With Try-Catch statements• Reasons for exceptions with file read are:
– File does not exist.– File name was misspelled– File is corrupted.– etc.
6
Reading Text Files with Scanner Object
• Use try and catch to check for exceptions• Inside the try block:
7
try{ File myfile = new File(“NameOfTextFile.txt”); //where to find the file Scanner scan= new Scanner(myfile); //associates the scanner object with that file.
//Other code} catch (IOException ioe){ System.out.println(“Error Occurred”); }
Reading Text Files with Scanner Object
• Create a while loop inside the try block that keeps reading data until there is no more data to be read.
• The scanner class has methods that allow us to read one String at a time or one line at a time (as one String).– Look up the scanner class and its methods in the Java API.
8
Scanner Class hasNext MethodThis method detects the end of the input values one String at a time (one
token).
The hasNext method looks ahead for input.• An IOException may be generated if we encounter problems reading
the file. Java requires us to acknowledge that these exceptions may be generated.
• Note that there is another method called hasNextLine() which returns a boolean and can sense the end of data line by line.
Return type Method name and argument listBoolean hasNext( )
returns true if there is more data to read; returns false when the end of the file is reached
9
Example Reading From Fileimport java.io.File;import java.io.IOException;Import java.util.Scanner;public class ReadFile {
public static void main(String[] args) { String str=“ “; int count=0; try {
File myFile=new File(“text.txt”); Scanner scan=new Scanner(myFile);
while(scan.hasNextLine()){str=scan.nextLine();System.out. println(str);
count++;// Note that if we want the individual Strings (tokens) inside each line, we need to use the StringTokenizer object to tokenize the line
read during each iteration!!!! } } //end of try block of code!!!!!! catch(IOException ioe) { System.out.println(“The file can not be read”); }System.out.println(“The number of strings tokens read is:”+count);
}}
10
Scanner Class hasNext… Methods• Each method returns true if the next token in the
input stream can be interpreted as the data type requested, and false otherwise.Return type Method name and argument list
boolean hasNextInt( )
boolean hasNextDouble( )
boolean hasNextFloat( )
boolean hasNextByte( )
boolean hasNextShort( )
boolean hasNextLong( )
boolean hasNextBoolean( )
boolean hasNext( )11
StringTokenizer• In the previous example we captured one line of data at a time, from the
text file.• The String str has the value of the entire line during each cycle in the while
loop (its value changes to the next line during the next cycle).• Now, we may be interested in the individual Strings that make up the
entire line. Therefore when we capture the line we may want to break it up into individual tokens.
• To do that we use the StringTokenizer class
12
StringTokenizer• Modifying the program for the StringTokenizer:• First at the top we need to import the library package java.util which contains the
StringTokenizer class.• Then we modify the while loop as follows:
13
Import java.util.StringTokenizer;..while(scan.hasNextLine()) //use loop since we are not sure how many tokens in the line{
str=scan.nextLine();StringTokenizer strtok=new StringTokenizer(str, “,”); //, is the delimitorwhile(strtok.hasMoreTokens()){ String tokenstr=strtok.nextToken(); //Now, do what you want with the String tokenstr. You may have to
//parse it to another data type depending on what data type you expect.
}System.out. println(str);
count++;}
Using Split function
• StringTokenizer is a legacy class• Use Split function of the String class
14
public String[] split(String regex)
• Splits this string around matches of the given regular expression.
Practice Problem
• Write a program that will read from a text file and then print out the words, one in each line– E.g. output of a file containing a line “I love OOPs”
will be ILoveOOPs
• You can reuse the program given earlier in this lecture.
15
Formatting Numbers
• Two types of formatting:– Formatting a double data type to restrict the
number of decimal points.– Formatting a decimal number to convert it to a
particular currency like US dollars.• The first action is done with library class: DecimalFormat from package java.text(must import java.text.DecimalFormat)
16
Formatting Numbers– Create an object of DecimalFormat and in the constructor define the
pattern of decimal points as a String DecimalFormat df=new DecimalFormat(“0.00”); The object df can convert double data types to the accuracy of only
two decimal points in this example pattern.– Suppose we have the decimal data type double mydoubletype=10.00003; The code below converts the data type mydoubletype into a new data
type of double type but with a precision of only two decimal points: double newdoubletype= df.format(mydoubletype);
17
Formatting Numbers• The conversion to currency is done with library class
NumberFormat of package java.text (import java.text.NumberFormat;)
– For US dollars: create an object like this:NumberFormat form=NumberFormat.getCurrencyInstance();– Use the object form as follows:String strversionofdouble=form.format(mydoublenumber);– Notice that the double number held by identifier mydouublenumber is
converted into two decimal points and the $ sign is placed in front of it. It then it gets assigned to a String type.
– If we want the String strversionofdouble converted back to a double we need to parse it
18
SCOPE
19
Scope• Scope of a variable or method refers to the
region of the code where you can access it.– You will get a compile error if you try to access a
variable/method from beyond its scope
20
Scope: Example
21
public class ReadFile { public static void main(String[] args) { String str=“ “; int count=0; try {
File myFile=new File(“text.txt”); Scanner scan=new Scanner(myFile);
while(scan.hasNextLine()){str=scan.nextLine();System.out. println(str);
count++; } } //end of try block of code!!!!!! catch(IOException ioe){
System.out.println(“The file can not be read”); }System.out.println(“The number of strings tokens read is:”+count);
}}
• What is the scope of the variable str?
Scope
• In the previous example the String str was declared at the top of the main method.– Therefore we say that the String str has method
scope. That means that the value held by the identifier str can be seen anywhere from within the method.
– If, for example, we had declared str inside the while loop (next slide)
22
Scope: Example
23
public class ReadFile { public static void main(String[] args) { int count=0; try {
File myFile=new File(“text.txt”); Scanner scan=new Scanner(myFile);
while(scan.hasNextLine()){ String str=“ “;str=scan.nextLine();System.out. println(str);
count++; } } //end of try block of code!!!!!! catch(IOException ioe){
System.out.println(“The file can not be read”); }System.out.println(“The number of strings tokens read is:”+count);
}}
• What is the scope of the variable str?
Accessing the value of str outside the while loop would had caused an error, because the variable’ s str scope is limited to the while loop
Scope: Example
24
public class ReadFile { public static void main(String[] args) { String str=“ “; try {
int count=0; File myFile=new File(“text.txt”); Scanner scan=new Scanner(myFile);
while(scan.hasNextLine()){str=scan.nextLine();System.out. println(str);
count++; } } //end of try block of code!!!!!! catch(IOException ioe){
System.out.println(“The file can not be read”); System.out.println(“The number of strings tokens read is:”+count);}System.out.println(“The number of strings tokens read is:”+count);}
}
• What is the scope of the variable count?
Error?
Error?
Yes
Yes
Variables and Their Scope
• Types of variables and their scope– Parameter variables: accessible only within the method
(method scope)– Local variables: accessible only within the method or code
block (e.g. try and catch block, if..else block, etc)– Instance variables: have class scope
• Class scope: accessible by any method in the class– Access by other classes is controlled by the access modifier
25
Scope: Example• What if we declared the String str outside the main method?
26
public class ReadFile {String str=“ “;public static void main(String[] args) {try {
int count=0; File myFile=new File(“text.txt”); Scanner scan=new Scanner(myFile);
while(scan.hasNextLine()){str=scan.nextLine();System.out. println(str);
count++; } } //end of try block of code!!!!!! catch(IOException ioe){
System.out.println(“The file can not be read”); System.out.println(“The number of strings tokens read is:”+count);}System.out.println(“The number of strings tokens read is:”+count);}
}
Class Scope
• Notice that in this case we have included another method in the class besides the main.
• Since the String str is declared outside any method but inside the class , we say that the variable str has class scope:– That means that its value can be seen and it is accessible
by any method in the class!!– The main method can access it by first instantiating an
object for the class.
27
Class Scope
28
• Instance variables have class scope– Any constructor or method of a class can directly
refer to instance variables.• Methods also have class scope
– Any method or constructor of a class can call any other method of a class (without using an object reference).
Local Scope
29
• A method's parameters have local scope, meaning that: – a method can directly access its parameters.– a method's parameters cannot be accessed by other
methods.• A method can define local variables which also have
local scope, meaning that:– a method can access its local variables.– a method's local variables cannot be accessed by other
methods.
Example of Class vs local scopepublic class Person {
String firstName;static int I d;int currentid;
public Person(){ firstName="John"; id++; currentid=id;
}
public void method1(){ int currentid;
currentid = this.currentid*2;System.out.println("The local value of currentid is"+" "+currentid);System.out.println("The class scope of variable currentid is"+" "+this.currentid);
}}
30
Scope?
currentid defined in method1() has local scope
Example of Class vs local scopepublic class Person {
String firstName;static int I d;int currentid;
public Person(){ firstName="John"; id++; currentid=id;
}
public void method1(){ int currentid;
currentid = this.currentid*2;System.out.println("The local value of currentid is"+" "+currentid);System.out.println("The class scope of variable currentid is"+" "+this.currentid);
}}
31
Scope?
this.currentid defined as class attribute has class scope
Example of Class vs local scopepublic class Person {
String firstName;static int id;int currentid;
public Person(){ firstName="John"; id++; currentid=id;
}
public void method1(){ int currentid;
currentid = this.currentid*2;System.out.println("The local value of currentid is"+" "+currentid);System.out.println("The class scope of variable currentid is"+" "+this.currentid);
}}
32
public class PersonClient {
public static void main(String[] args) {
Person p1=new Person();Person p2=new Person();p1.method1();p2.method1();
}}
What is the output?
Example of Class vs Local scope
• ---------- for object p1 ----------– The local value of currentid is 2– The class scope of variable currentid is 1
• ---------- for object p2 ----------– The local value of currentid is 4– The class scope of variable currentid is 2
33
Default Initial ValuesIf the constructor does not assign values to the instance variables, they
receive default values depending on the instance variable data type.
Data Type Default Valuebyte, short, int, long 0
float, double 0.0
char space
boolean false
Any object reference (for example, a String)
null
34
USING OBJECT REFERENCE
35
Object Reference this
36
• Object Reference: refers to an object instance.– Used to reference the object’s variables and
methods• When a method refers to an instance variable
name, this is implied. Thus, variableName is understood to be this.variableName Example in the Auto class:
modelName is understood to be this.modelName
Using this in a Mutator Method
37
• To distinguish between method parameter and instance variable.
Example:public void setModel( String model ){ this.model = model;}
• this.model refers to the instance variable whose value is being set.
• model refers to the parameter.
Using this
• Suppose in AutoClient class (which uses class Auto) we instantiate an object:– Auto a1=new Auto(); (globally -outside any
method)– Suppose that we create a new method that it is
responsible for setting the instance fields of a1 and getting their values by using also a globally declared parameter i.e int x;
– We can call the value of x using this.x 38
Using thispublic class AutoClient{
Auto a1=new Auto("Ford", “Mario”, 100, 20); //parameters are model, owner, miles driven, gas mileageint x=300;
public static void main(String[] args) {AutoClient ac=new AutoClient();ac.usingThis();Auto a2=new Auto("Infinity", “Jim”, 150, 18);System.out.println(a2.toString());a2.setCurrentID(15);System.out.println(“the value of x is:”+ac.x);
}public void usingThis(){
a1.setCurrentID(15);int x=a1.getCurrentID();System.out.println("The current id for a1 is now"+" "+this.x);System.out.println("The value of the current id variable for object a1 is"+" "+x);
}}
39
??
?
30015
300
Using this• The output of the previous program is:C:\CS116\FALL2010\PracticeExercises\Lecture 2\ExampleUsingthis>javac -
d . AutoClient.javaC:\CS116\FALL2010\PracticeExercises\Lecture 2\ExampleUsingthis>java
folder1.folder2.AutoClientThe current id for a1 is now 300The value of the current id variable for object a1 is15The model is Infinity The owner is Jim The miles driven are 150.0 The gas
mileage is 18.0 The id is 2The value of x is:300
40
The equals Method used for objects
41
• Determines if the data encapsulated in another object is equal to the data encapsulated in this object.
• Example client code using Auto references auto1 and auto2:
if ( auto1.equals( auto2 ) ) System.out.println( "auto1 equals auto2" );
Return value Method name and argument list
boolean equals( Object obj ) returns true if the data in the Object obj is the same as in this object; false otherwise
The equals Method used for objects
• All java objects regardless if the class is user defined or pre defined get to use (the term is “inherit”) methods of a library class called Object.– All classes get to use (the term is “inherit”) the toString and
equals methods of the Object class.• We create (as we know) our own toString and equals
methods for objects of our user defined template class.– When we create our version of a method that already exists in
the library we call the technique “method overriding”.• Default implementation of equals() of Object class
compares memory location and only return true if two reference variable are pointing to same memory location
42
The instanceof Operator
43
• We can use the instanceof operator to determine if an object reference refers to an object of a particular class.
• Syntax: objectReference instanceof ClassName
– evaluates to true if objectReference is of ClassName type; false otherwise.
• Because the equals method’s parameter is of type Object, we need to determine if the parameter is an Auto object. (Object is general- we need to narrow it down to the specific type of Object).
Auto Class equals Method (method overriding of Object class’ equals method).
44
public boolean equals(Object o ){
// if o is not an Auto object, return falseif ( ! ( o instanceof Auto ) )
return false;else{
// type cast o to an Auto objectAuto objAuto = ( Auto ) o; if ( this.modelName.equals( objAuto.modelName) &&
this.milesDriven== objAuto.milesDriven && Math.abs( this.mileage - objAuto.mileage ) < 0.0001 )
return true;else
return false;}
}
See text Examples 7.10 Auto.java and 7.11 AutoClient.java
ENUM DATATYPE
45
enum Types
46
• Special data type that allows a variable to be a set of predefined constants– Variable’s value must be equal to one of the predefined
contants.• Built into java.lang (no import statement needed)• Syntax: enum EnumName { obj1, obj2,… objn };
• Example: enum Days { Sun, Mon, Tue, Wed, Thurs, Fri, Sat };
Example enum enum PersonType { ADULT_MALE, CHILD_MALE, ADULT_FEMALE, CHILD_FEMALE };
public class Persons {
PersonType pt;String firstName;static int id;int currentid;
public Persons(){ firstName="John"; id++; currentid=id;}
public void setPersonType(PersonType pertyp){ this.pt=pertyp;
}
public PersonType getPersonType(){ return pt;
}}
47
Example enum
enum PersonType { ADULT_MALE, CHILD_MALE, ADULT_FEMALE, CHILD_FEMALE };
public class Persons {
PersonType pt;String firstName;static int id;int currentid;
public Persons(){ firstName="John"; id++; currentid=id;}
public void setPersonType(PersonType pertyp){ this.pt=pertyp;
}
public PersonType getPersonType(){ return pt;
}}
48
public class PersonsClient {
public static void main(String[] args) {
Persons p1=new Persons();Persons p2=new Persons();
p1.setPersonType(PersonType.ADULT_FEMALE);
p2.setPersonType(PersonType.CHILD_MALE);System.out.println("p1 is of person
type:"+" "+p1.getPersonType());System.out.println("p2 is of person
type:"+" "+p2.getPersonType());
}}
What is the output?
Example enum
– ---------- Output ----------– p1 is of person type: ADULT_FEMALE– p2 is of person type: CHILD_MALE
49
Useful enum Methods
50
Return value Method name and argument list
int compareTo( Enum eObj ) compares two enum objects and returns a negative number if this object is less than the argument, a positive number if this object is greater than the argument, and 0 if the two objects are equal.
int ordinal( )returns the numeric value of the enum object. By default, the value of the first object in the list is 0, the value of the second object is 1, and so on.
boolean equals( Object eObj ) returns true if this object is equal to the argument eObj; returns false otherwise
String toString( ) returns the name of the enum constant
Textbook EX 7.17public class EnumDemo{ public enum Days { Sun, Mon, Tue, Wed, Thur, Fri, Sat };
public static void main( String [] args ) { Days d1, d2; // declare two Days object references d1 = Days.Wed; d2 = Days.Fri; System.out.println( "Comparing objects using equals" ); if ( d1.equals( d2 ) ) System.out.println( d1 + " equals " + d2 ); else System.out.println( d1 + " does not equal " + d2 ); if ( d1.compareTo( d2 ) > 0 ) System.out.println( d1 + " is greater than " + d2 ); else if ( d1.compareTo( d2 ) < 0 ) System.out.println( d1 + " is less than " + d2 ); else System.out.println( d1 + " is equal to " + d2 );
System.out.println( "\nGetting the ordinal value" );System.out.println( "The value of " + d1 + " is " + d1.ordinal( ) );
System.out.println( "\nConverting a String to an object" );Days day = Days.valueOf( "Mon" );System.out.println( "The value of day is " + day ); }}
51
C:>java EnumDemoThe value of d1 is WedThe value of d2 is FriComparing objects using equalsWed does not equal Fri
Comparing objects using compareToWed is less than Fri
Getting the ordinal valueThe value of Wed is 3
Converting a String to an objectThe value of day is Mon
Textbook EX 7.17public class EnumDemo{ public enum Days { Sun, Mon, Tue, Wed, Thur, Fri, Sat };
public static void main( String [] args ) { Days d1, d2; // declare two Days object references d1 = Days.Wed; d2 = Days.Fri; System.out.println( "Comparing objects using equals" ); if ( d1.equals( d2 ) ) System.out.println( d1 + " equals " + d2 ); else System.out.println( d1 + " does not equal " + d2 ); if ( d1.compareTo( d2 ) > 0 ) System.out.println( d1 + " is greater than " + d2 ); else if ( d1.compareTo( d2 ) < 0 ) System.out.println( d1 + " is less than " + d2 ); else System.out.println( d1 + " is equal to " + d2 );
System.out.println( "\nGetting the ordinal value" );System.out.println( "The value of " + d1 + " is " + d1.ordinal( ) );
System.out.println( "\nConverting a String to an object" );Days day = Days.valueOf( "Mon" );System.out.println( "The value of day is " + day ); }}
52
3==5? C:>java EnumDemoThe value of d1 is WedThe value of d2 is FriComparing objects using equalsWed does not equal Fri
Comparing objects using compareToWed is less than Fri
Getting the ordinal valueThe value of Wed is 3
Converting a String to an objectThe value of day is Mon
(3-5) > 0?
Evokes day.toString()
declaration
JAVA PACKAGES
53
Java Packages• A package is a collection of classes.
– Gives organization and structure to our application program• Packages can contain classes that are used by the package but are
not visible or accessible outside the package.• Different packages can have classes with the same name.• User defined packaging.
– Suppose that we created a package for our service class Auto :
54
package name1.name2.name3;import java.util.Scanner;
public class Auto{
………………………………}
Java Packages
• Compile using the switch “-d”:• >javac –d . Auto.javaNotice that there is space between javac and –d and also between –d and
the dot. There is also space between the dot and the name of the file.• This command tells the compiler to create sub-folders fror
placing the class files• It first creates sub-folder “name1” then “name 2” (inside
“name1” folder) and then “name3” (inside “name2” folder) with respect to the current directory
• and place Auto.class inside folder “name3”.
55
Java Packages
Current Directory (folder)
name1(folder)
name2 (folder)
name3 (folder) Auto.class
56
Source code files
Auto.java AutoClient.java are in Current
Directory
Java Packages• The service class Auto.class file is in folder “./name1/name2/name3” in our
example.• Suppose that we want to use the class Auto in the class AutoClient which is in
package name1.name2 • Place AutoClient class in the sub-folder name2 (not the same folder as the Auto
class):• You can use Auto class in AutoClient in two ways:
57
[Use the full name of the class]
package name1.name2;
public class AutoClient{
name1.name2.name3.Auto fiatCar = new name1.name2.name3.Auto();
………………………………}
Java Packages
• You can use Auto class in AutoClient in two ways (cont.)
58
[Use import statement]
package name1.name2;import name1.name2.name3.Auto;
public class AutoClient{
Auto fiatCar = new Auto(); ………………………………
}
– Note: If both classes reside in the same folder then there is no need to import the Auto class
Java PackagesCurrent Directory (folder) Auto.java , AutoClient.java
name1(folder)
name2 (folder)AutoClient.class
name3 (folder)
Auto.class
59
Java Packages
• How do we call the interpreter for class AutoClient from the current directory (folder)?
• We need to list the path to the AutoClass when we use the interpreter command:
i.e >java name1.name2.AutoClient• Notice that the reason we call the AutoClient class is
because this class has the main method. The Auto class will be called automatically.
60
Java Packages
• Pre defined library classes are grouped into packages according to their functionality:
i.e. package java.lang • Provides classes that are fundamental to the design
of the Java programming language.• Every java program automatically imports all the classes of
this package without the need for an import statement.– Includes such classes as :
• String, Math , System, Integer, Float and others.
61
Java Packages
package java.util– Must explicitly be imported with an import
statement.– Provides such classes as:
• Scanner, StringTokenizer, Vector, Calendar, Date and others.
java.text– Must imported explicitly.– Provides numeric formatting classes such as:
• Format, NumberFormat and others
62
Java Packages
• Import statements can include the entire package or a selective class out of the package
i.e. import java.util.*; imports all classes in package util or import java.util.Scanner; imports only the Scanner class (saves memory usage)
63
Java Packages
• There are over 200 packages in the java library– Number of classes varies in each package with
some having over 20 classes.– Remember that a package can include something
called “interfaces”.– For now let us think of an interface as a class whose
methods have no code (no implementation). We will come back to the subject of interfaces later.
64
JAVA DOCS
65
Javadocs
• Automatic generation of documentation for your user defined classes in html format.
• It is another tool available in the jdk (see bin subfolder in the installation folder of the jdk).
• To generate documentation use the command javadoc and the nam eof your class followed by the .java extension:– >javadoc Persons.java or– >javadoc *.java (means all files in the folder that end
with .java extansion).
66
Javadocs
• The tool reads all comments added (/** to */)• plus additional information that we add in the
source code file (i.e. describe method parameters and return using the symbol @) i.e.– @param id denotes the id number of a person advancing
for each new Person object instantiated.– @return method return a String
67
Javadoc Example/** This class describes Persons */public class Person { /** @param firstName provides the first name of a Person */
String firstName;static int id;int currentid;
public Person(){firstName="John";id++;currentid=id;}
}
68
Output html File• Package Class Tree Deprecated Index Help • PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes All Classes SUMMARY: NESTED | FIELD |
CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD • Class Person• java.lang.Object Person public class Person extends java.lang.Object This class describes Persons • Constructor Summary Person()
Method Summary void method1() Methods inherited from class java.lang.Object clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
• Constructor Detail Person• public Person() Method Detail method1• public void method1() Package Class Tree Deprecated Index Help • PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes All Classes SUMMARY: NESTED | FIELD |
CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
69