IT 114: Introduction to Java
Class 43
Topics
Review
Final Exam
The final exam will be given on Friday, May 22nd starting at 11:30.
It will consist of questions like those on the quizzes, along with questions
asking you to write short segments of Python code.
60% of the points on this exam will consist of questions from the Ungraded
Class Quizzes.
Today's will be a review of the material covered since the midterm.
You will only be responsible for the material in today's Class Notes and
the material in Class Notes 42.
The final will be an online exam.
At the moment I do not know the exact format that will be used,
but I will send you an email with details on May 17th, the Sunday
before the exam.
Review
Errors
- It is easy to get an error when writing programs
- But to fix errors it is important to recognize the different types
- There are three classes of errors
- Syntax errors
- Logic errors
- Runtime errors
Syntax Errors
Logic Errors
- A logic error
occurs when the code does not give the correct results
- When you have a syntax error the Python interpreter will tell you
- The error message it gives specifies the kind of error and prints the line
- But you get no warning with a logic error
- The code works and unless you check the results you will not know there is a problem
- This is why it is always important run tests on the scripts you write
- Even if you know there is an error it can be hard to find
- The problem could be anywhere in the code
- It is hard to spot your own errors
- That is why smart people ask others to proof read what they write
Runtime Errors
- Runtime errors
occur only when the the program is run
- They occur when a value in the program makes a statement fail
- If the program is run again with a different value no runtime error would occur
Exceptions Objects
- Many computer languages have a mechanism built into the language that deals with runtime errors
- It gathers information about what happened and where
- And uses that information to create an error message
- The error message describes the problem and where it occurred
- It does this by creating an
exception object
- When this happens we say that the interpreter has
raised an exception
Catching Exceptions
Data Validation Loops
Files
- A file is simply a linear arrangement of data on some long term storage device
- That storage medium might be a
- Hard disk
- Flash drive
- CD ROM
- SSD card
Types of Files
- All files consist of binary numbers
- But those numbers can be interpreted in two ways
- Text files have a simple structure
- Each file is a collection of lines
- A line is a series of characters followed by the newline character \n
- We will only be using text files in this course
Getting Data From a File in Java
- You can think of a program as code that deals with streams of data
- It takes data from an input stream
- And produces an output stream
- The input stream can come from the keyboard
- Or from a file
- The output stream can go to the screen
- Or to a file
- Previously we used Scanner object that we used to get
input to get input from the key
- A Scanner object can also be used with a file
- After all a file is just another data stream
Using a Scanner Object with a File
- To create a Scanner object for a file
we need to create a File object
- But first we have to import the File
class
import java.io.File;
- To create a file object from a
pathname
given at the command line we would write
File file = new File(args[0]);
- Now we can use file to create a
Scanner object
- Here is a small program to do this
import java.io.*;
import java.util.Scanner;
public class OpenFile {
public static void main (String[] args){
File file = new File(args[0]);
Scanner input = new Scanner(file);
}
}
- But when we try to compile this we get the following
$ javac OpenFile.java
OpenFile.java:7: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Scanner input = new Scanner(file);
^
1 error
- Note that the runtime did not occur when we created the file object
- It occurred when we tried to use this file object as an argument
when creating the Scanner object
- This means that we can create a file object for a file that does not exist
Two Kinds of Java Exceptions
Reading a File with Scanner
- A Scanner object has multiple
methods that return data
Method | Description |
next() |
Reads and returns the next
token
as a String
|
nextDouble() |
reads and returns a double value |
nextInt() |
reads and returns an int value |
nextLine() |
reads and returns the next line of input as a
String
|
- For every one of these methods there is another "next"
method that tells you whether there is more data in the file
- They are boolean methods that return true if
the next thing in the file is of the right type
- They will all return false when you reach the end of the file
Method | Description |
hasNext() |
Returns true if there is another token to be read |
hasNextInt() |
Returns true if there is another integer token to be read |
hasNextDouble() |
Returns true if there is another decimal token to be read |
hasNextLine() |
Returns true if there is another line of text to be read |
Reading a Text File
Parsing Files with a Scanner object
- Parsing is breaking up some kind of data stream into individual strings called
tokens
- The Scanner object has to know where one token ends
and the next begins
- It does this by looking for
delimiters,
special strings that mark off the individual tokens
- If you don't specify a delimiter, Scanner
will use whitespace
Records
- For any sporting event involving teams we have at least 5 pieces of information
- Date
- Home team
- Opposing team
- Home team score
- Opposing team score
- The collection of data about a specific event is called a
record
- The individual pieces of data within a record
are called fields
Reading Records from a File
- To work with a text file containing m any records on a line
we can use a
while
loop like this
Scanner input = new Scanner(file);
while (input.hasNextLine()){
System.out.println(input.nextLine());
}
- To break up the line into field values we can use
the split() string method on a line
import java.io.*;
import java.util.Scanner;
public class ReadFields {
public static void main (String[] args)
throws FileNotFoundException {
File file = new File(args[0]);
Scanner input = new Scanner(file);
String line;
String [] fields;
while (input.hasNextLine()){
line = input.nextLine();
fields = line.split(" ");
for (int i = 0; i < fields.length; i++)
System.out.print(fields[i] + " ");
System.out.println();
}
}
}
The Variables a Method Can See
- Every method gets its own section of RAM for its own variables
- No method can see the variables in another method's RAM space
- So you can have two variables with the same name in two
different methods with different value
ArrayLists
- An ArrayList object is dynamic so you do not have to specify a size when creating them
- The data contained in an ArrayList object is actually stored in a
an array
- When first created an ArrayList object contains
an array of a certain size
- But if the object needs more space it simply creates a bigger array
- Then is copies all the data in the original array into this new array
- This is all done automatically
Creating an ArrayList Object
Loading Values into an ArrayList
- When you first create an ArrayList object
it has no values
- The simplest way to load a value into an ArrayList object
is to use the add method
- This method adds a single value to the end of the list
- Here is an example
import java.util.ArrayList;
public class ArrayListString {
public static void main (String[] args){
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < args.length; i++){
list.add(args[i]);
}
System.out.println(list);
}
}
$ java ArrayListString foo bar blecth
[foo, bar, blecth]
Looping Through an ArrayList
Creating an ArrayList from a File
Other ArrayList Methods
- ArrayLists have a number of useful methods
- Below is a table of methods and what they do
Method |
Description |
add(value) |
Adds a value to the end of the list |
get(index) |
Returns the value at a given position |
remove(index) |
Remove the element at a given position |
set(index, value) |
Changes the value at a give position |
size() |
Returns the number of elements in the list |
The add(value) Method
- add(value) creates an element at the end of the list
- This operation is something you cannot do with an array
import java.util.ArrayList;
public class ListAdd {
public static void main (String[] args){
ArrayList<String> list = new ArrayList<>();
System.out.println(list.size());
list.add("one");
System.out.println(list.size());
list.add("two");
System.out.println(list.size());
System.out.println(list.size());
System.out.println(list);
}
}
$ java ListAdd
0
1
2
3
[one, two, three]
The get(index) Method
- The get(index) method returns the value of the
element at a given index
- It performs the same function as using square brackets
[ ], with an array
import java.util.ArrayList;
public class ListGet {
public static void main (String[] args){
ArrayList<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
System.out.println(list);
System.out.println("The value at index 1: " + list.get(1));
}
}
$ java ListGet
[one, two, three]
The value at index 1: two
The remove(index) Method
- The remove(index) method delete an entry
at a given index position
- Every element after the one removed is shifted one positon to the left
- Once again, this is an operation that cannot be performed on an array
import java.util.ArrayList;
public class ListRemove {
public static void main (String[] args){
ArrayList<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
System.out.println(list);
list.remove(1);
System.out.println(list);
}
}
$ java ListRemove
[one, two, three]
[one, three]
The set(index, value) Method
- The set(index, value) method changes the value
at a given position
import java.util.ArrayList;
public class ListSet {
public static void main (String[] args){
ArrayList<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
System.out.println(list);
list.set(1, "2");
System.out.println(list);
}
}
$ java ListSet
[one, two, three]
[one, 2, three]
ArrayList Search Methods
- ArrayList provides methods that can be used
to search the list
Method |
Description |
contains(value) |
Returns true if the value can be found in the list |
The contains(value) Method
Writing a Method to Read in Files
- Creating an ArrayList from the contents of a file is something
we might want to do often
- Any job you might often want to do is something that should be turned
into a method
- Here is an program that contains a method to create an ArrayList
from a file
import java.io.*;
import java.util.*;
public class FileToList {
public static void main (String[] args)
throws FileNotFoundException {
ArrayList<String> list = create_list_from_file(args[0]);
System.out.println(list);
}
public static ArrayList>String> create_list_from_file(String filename)
throws FileNotFoundException {
File file = new File(filename);
ArrayList>String> list = new ArrayList<>();
Scanner input = new Scanner(file);
while (input.hasNext()){
list.add(input.next());
}
return list;
}
}
$ java FileToList.java fruit.txt
[grapes, pears, oranges, cranberries, apples, melons, blueberries]
Stopping Execution of a Loop
- The loop header
determines how a loop
- In a
for
loop it tells the number of times the loop
will run
- In
while
and do
/while
loops
it gives the condition that will make the loop stop
- But sometimes there are special situations where you want another
way to stop running the loop code
- Java has two statements that can do this
The break
Statement
- Sometimes you will come across a situation where you simply
want a loop to stop running
- To jump completely out of he loop you would use a
break
statement
The continue
Statement
- Maybe you don't want to jump completely out of the loop
- You just want to stop running the loop code for one
iteration of the loop
- In that case you would use a
continue
statement
Object Oriented Programming
- The key idea behind object oriented programming is that certain variables naturally go together
- And certain methods are needed to operate on these variables
- To create an
object
you need to define a
class
- A class is a template that Java uses to create individual objects
- The objects are the things in memory
- But the class is the blueprint used to create individual objects
- The class defines all variable and methods inside the object
- Every class must have a special method which is used to create an object of the class
- This special method is called a
constructor
- The object of a given class created by the constructor is called an
instance
Objects and Values
- A variable
can only hold one value
- But objects can hold many values
- Putting all the variables describing one thing in a
single class makes it easier to work with these values
Classes and Objects
- There are two types of classes
- A static class cannot create objects
- There are two ways to use a static class
- The static class Math is an example of the first kind of static class
- Most Java classes are not static
- They are templates used to create objects
- Each class of this type has
- Variables to hold values
- Methods that work with those values
- Special methods to create an object of the class
- Real world Java programs have many classes
Point Objects
Defining a Class
Fields
- Fields
hold an object's values
- You can think of them as variables inside the object
- Fields are declared outside the object's methods
- That means they can be used by any of the methods in an object
- You declare a field the same way you declare a
local variable
inside a method
DATA_TYPE FIELD_NAME;
- Fields are at the top of the class right after the class header
The Implicit Parameter
- The code for an
instance method
knows about the fields in the object in which it lives
- So when you call such a method not have to specify the object in which the values are located
- The object is an
implicit parameter
of the instance method
- That means a method does not need a parameter to access the object's fields
Mutators and Accessors
- The translate method changes the values contained in
the object
- Methods that change one or more fields are called
mutators
- By convention, the names of mutators often begin with the word "set"
- For example setID or setTitle
- For this reason, mutators are often called
setters
- The return type of a mutator is usually void
- Mutators normally take parameters which are either the new values for the fields
- Or values which are used to modify the current value of the fields
- A second important category of instance methods are
accessors
- Accessors return the value of a field without changing that value
- The names of accessors sometimes begin with the word "get"
- For example getBalance
- Accessors are sometimes called
getters
- If the accessor returns a boolean value the name often begins with "is" ...
- For example isEmtpy
Classes for Other Programs To Use
- Classes such as Point are used to create objects
- A class that creates objects never a program that does something useful
- Instead it is used by static, driver classes to do their work
- These static classes are sometimes called client programs
- If you look at the classes that come with Java you will
sometimes find many methods
- And some of these methods look so similar that you wonder
why they were created
- The people who design these classes know that
the class will be used by many different programmers
- And individual programmers may approach their task in different ways
- So the designers tend to create many different methods
in the hope that each programmer will find the method they need
Printing Objects
- Printing is an operation that only works with text
- Every object has a special method called toString
- This method provides a text representation of the object
- println needs to turn its argument into text
- It knows how to do this for primitive types like
int
, double
and boolean
- But it uses toString to do the text conversion
with objects
Constructors
Scope
- When a method runs, it gets it own bit of RAM
- Inside that memory space it creates its own variables
- These variables disappear when the method finishes
- And the RAM space for the memory vanishes
- But can a method use variables found in other parts of the code?
- To answer this question, we need to learn about
scope
- Scope applies to the things in Java we declare
- Like variables and methods
- Scope is the part of a program in which a particular declaration of a thing is valid.
- Scope applies to both variables and methods
- And there a different rules for each
Scope Within Instance Methods
Scope Within the Same Method
- Within the same method, the scope rule for variables is simple
- The scope starts when the the variable is declared
- And ends with the right curly brace, }
closing the section of the code in which is is defined
- To use a variable inside a loop, we must define it before the loop
- It also means that you cannot use the loop variable in a
for
loop outside the loop
- Because it will not compile
- The scope rule applies wherever we have curly braces
Method Scope
- The scope rules for methods is simple
- The scope for a method is the entire class in which it is defined
- So it does not matter the order in which methods are defined
Shadowing
Multiple Constructors
Overloading
- Java lets us create two different constructors for a
class id they looked different to the Java compiler
- They looked different different by having different
signatures
- The signature is the combination of the method name
- And the data type of the parameter list
- When you create two different method of the same name but different
signatures it is called
overloading
- Overloading can be used for any methods, not just constructors
Encapsulation
- To keep programmers from mucking about with things they don't understand
many languages employ the principle of
encapsulation
- Encapsulation means hiding the details of how a class works from the clients that use the class
- A programmer who is writing a client class does not need to know how a class he or she is calling works
- The programmer only needs to know how the general idea of what the class does
- This important principle is called
abstraction
Data Hiding
Throwing an Exception
Hiding Methods
Time Accessors and Mutators
- Since we have made the fields private, there is no way client code
can get their values
- So we need to create
accessors
- We also need to create
mutators
Thinking about Objects
- There are two ways to think about objects
- How they appear in RAM
- How they represent some thing
- In RAM an object is a section of memory holding many values
- And methods that work on these values
- But an object also represents one particular thing
- Like an individual student
- The object holds particular information about a particular student or car
- The method let us see the characteristics of the thing they represent
- And do the things one does on that object
- Like change the major of a student
- Or sell a car
- There are two parts to solving any problem
- Deciding what to do
- Deciding how to do it
- In working on both parts, it is useful to think abstractly
- Objects help us do just that
Reusing Classes
- If you want to do something once and never do it again, classes are not worth the effort
- You only create a class if it holds data that you want to use again and again
- But there is another advantage to using classes
- You can use one class as the basis for another class that does something similar
- This feature is called
inheritance
Inheritance
- Inheritance lets you create new classes using the
fields and
methods
of another class
- Inheritance only works when there is an "is a" relationship between two things
- An animal is certainly an organism
- So we could create create an Animal class based on an Organism class
- Whenever we use one class as the basis of another class we call the original class the
superclass
- Or that base class
- The class which inherits from another class is called the
subclass
- Or the derived class
- A subclass inherits all the attributes and methods of its superclass
Attendance
Class Exercise