Anda di halaman 1dari 91

Final Exam Review

Appointments will be happening


Monday Afternoon and before final
on Wednesday
Java Program Structure
Java Program Structure
Everything must always be in a class

Java applications must have a main()


method in one of the classes, with
following signature:

public static void main(String[] args)


Running a Java Program
Each class is implemented in its own
source file

Name of Java file is the same as the


class name
Running a Java Program
Comments
Java supports two commenting styles:
Java's primitive types
primitive types: Java's built-in simple data types
for numbers, text characters, and logic.
Java has eight primitive types total.
Types that are not primitive are called object types.

We'll use these four primitive types in this class


primarily:
Name Description Examples
intintegers (whole numbers) 42, -3, 0, 926394
double real numbers 3.14, -0.25, 9.0
char single text characters 'a', 'X', '?', '\n'
boolean logical values true, false
Strongly Typed Languages
Variables
Variables
Reference Variables
Reference Variables
Reference semantics
If two object variables are assigned the same object, the object is NOT copied;
instead, the objects address is copied.

As a result, both variables will point to the


same object.
Calling a method on either variable will modify
the same object.
Example: p1 x 1
3 8
y 2
Point p1 = new Point(3, 8); : :
Point p2 = p1;
p2.setLocation(1, 2);
p2

13
Assignment
Conditionals
Conditional logic in Java is performed with the
if statement

Boolean data types true or false

Building compound conditional statements:


&& (and), || (or), ! (Not), <, >, ==, !=, <=, >=, etc.
Loops:
Java Exception Handling
An exception is an object that
defines an unusual or erroneous
situation

An exception is thrown by a program


or runtime environment and so can
be caught and handled
Java Exception Handling
Exception handling allows a
programmer to divide a program into
a normal execution flow and an
exception execution flow

If an exception is not handled the


program will terminate abnormally
Java Exception Handling
Finally clause
A try statement may have a finally
clause

The finally clause defines a section of


code that is executed regardless of
how the try block is executed
Classes
Classes protect data with functions (methods)
that safely operate on the data

Classes are created with the new keyword

The new keyword returns a reference to an


object that represents an instance of the class
Methods
Methods are like functions
Methods are defined inside of a class
definition
Methods are visible to all other methods
defined in the class
Methods can be overridden by a subclass
Method lookup is done at run-time
Anatomy of a Method
Visibility identifier:
Public: accessible anywhere by anyone
Private: Accessible only from within the class
where they are declared
Protected: Accessible only to subclasses or
classes in the same package
Unspecified: access is public in the classs
package and private elsewhere.
Return Methods
Must specify a data type of the data that the
method returns

Use the return keyword

Use void if the method does not return any data

Argument: can take in a list of parameters


Class (Instance) Variables
In Java, we declare variables that are global
to the object

Define class variables at the top of the class

May be defined as public, private, or


protected
Class (Instance) Variables
Class variables for each instance of the class
Thus, each object gets its own copy. Can use the
static keyword to make a data element common
among all class instances.

Class variables may be initialized. They are set


to 0 or null otherwise. Local variables must be
initialized before they can be used.
Class Variables
this
Inside a method, the name this
represents the current objects

When a method refers to its instance


variables or methods, this is implied
Method Overloading
In Java, we may create methods with
the same
Parameter lists must be different. Not
enough to have a different return type

Allows for the method to be used based


on the called parameters
Method Overloading
Class Constructors
Each class may have one or more
constructors
A constructor is a method (cannot
invoke, does not return anything)
Has same name as its class
A constructor is automatically called when
an object is created using new
Packages
A package is a loose collection of classes
Packages are like libraries
Packages may be created using the package
keyword
Packages are located by the CLASSPATH
environment variable
In order to use a package, you use the import
keyword
Strings are not a primitive
type
We have been using Strings to
communicate with the user
Hello, World!

As part of review, we are not talking


about how to manipulate characters
inside of string.
String Concatenation
Putting two strings together, we can use the + and weve done that
before in class and in hw assignments

The String class exports a method called concat() to signify


concatenations, but its almost never used because we can use +

If you use + with numeric operands, it signifies addition. If at least


one of its operands is a string, Java interprets + as concatenation.
When it is used in this way, Java performs the following steps:
If one of the operands is not a string, convert it to a string by applying the toString
method for that class.
Apply the concat method to concatenate the values.
publicclassJavaStringConcat{ STRING
CONCATENATION
publicstaticvoidmain(Stringargs[]){
/*
* String concatenation can be done in several ways in Java.
*/

Stringstr1="Hello"; Output of Java String concat example


Stringstr2=" World";
would be:
String concat using + operator : Hello
World
//1. Using + operator
Stringstr3=str1+str2;
System.out.println("String concat using + operator : "+str3);
Extracting Substrings
The substring method makes it possible to extract a
piece of a larger string by providing index numbers
that determine the extent of the substring.
str.substring(i1, i2);
where i1 is the first index position in the desired
substring and i2 is the index position immediately
following the last position in the substring.

If you only specify the first index, then substring


goes until the end of the string:
str.substring(i1);
Extracting Substrings
Example: from Hello, World! if you wanted to
select the substring "ell, you would make the
following call:
str.substring(1, 4);

Example: from Hello, World! if you wanted to


select just World!, you would make the following
call:
str.substring(7); //goes till the end of string
OR
str.substring(7, 13)
Checking Strings for
Equality
Many applications will require you to test whether two strings
are equal, in the sense that they contain the same characters.

Although it seems natural to do so, you cannot use the ==


operator for this purpose. While it is legal to write
if(s1==s2){}
The if test will not have the desired effect.

== checks whether the objects are identical, aka does the


reference in memory point to the same address (which would
be true for primitive types)
To check if two strings are equal:
if( s1.equals(s2) ) {}
Searching a String
Javas String class includes several methods for searching
within a string for a particular character or substring.

The method indexOf takes either a string or a character


and returns the index within the receiving string at which
the first instance of that value begins.

If the string or character does not exist at all, indexOf


returns -1. For example, if the variable str contains the
string "hello, world":
ARRAYS
An array is an indexed list of
values.
You can make an array of any type
int, double, String, etc.
All elements of an array must have
the same type.
ARRAYS
Array Initialization
double [] a = new double[5];
OR
double [] a = {1, 2, 3, 4, 5}

Default values:
The default initial value is:
zero for numbers
false for type boolean
null for String (and other non-primitive type)
Dont go out of bounds!
Read or writing any index outside the
valid range will throw an
ArrayIndexOutOfBoundsException
Combining
Loops &
Arrays
ArrayLists
Dynamically Changing Sized Arrays

Same basic functionality that comes with a standard array


Stores an ordered collection of values
allows access to the values via an index

Has an additional functionality:


Grows or shrinks dynamically by inserting and deleting elements
at any specified location
How to create & use
ArrayLists
ArrayList is defined in the Java APIs java.util package
So you must import:
importjava.util.ArrayList;
ArrayList is a class that is part of the Java standard library - Just like Scanner

To initialize, see syntax:


ArrayList<elementtype>NAME=newArrayList<>();

So:
ArrayList<String>grades=newArrayList<>();
Arrays vs. ArrayLists
ArrayList Generic Types
To get around this problem, Java defines a wrapper class for
each of the primitive types:
boolean Boolean
byte Byte
char Character
double Double
float Float
int Integer
long Long
short Short
ArrayList Example
ArrayList<String>myArr=newArrayList<String>();
myArr.add("ItalianRiviera");
myArr.add("JerseyShore");
myArr.add("PuertoRico");

ArrayListcanholdelementsofdifferenttypes

TocheckthesizeofanArrayList
Youdosize()so:
myArr.size();
Removing Elements from a list
We need to be careful removing
elements from an ArrayList
Remember when we remove
elements, the entire ArrayList shifts
into the position of the removed
element:
remove(6);
Removing Elements from a list
COMMON MISTAKES
Arrays vs. ArrayLists

ACTION Arrays ArrayLists


Capacity Fixed at Creation Flexible
How to get capacity grades.length grades.size()
Getting an element grades[i] grades.get(i)
Creation new double[30] new
ArrayList<Double>()
Setting an element grades[3] = 90.0; grades.set(3, 90.0);

For setting an element:


NOT grades.get(3) = 90.0;
Recursion
Can simply be thought of as
when a method calls on itself
Recursion
recursion: The definition of an operation in terms of itself.
Solving a problem using recursion depends on solving
smaller occurrences of the same problem.

recursive programming: Writing methods that call


themselves to solve problems recursively.

An equally powerful substitute for iteration (loops)


Particularly well-suited to solving certain types of problems
Recursions Three Steps
1.Decide how to take one step.

2.Know when to stop.

3.Break the journey down into the step


plus a smaller, similar journey.
Recursion and cases
Every recursive algorithm involves at least 2
cases:
base case: A simple occurrence that can be
answered directly.

recursive case: A more complex occurrence of the


problem that cannot be directly answered, but can
instead be described in terms of smaller occurrences
of the same problem.
Java Language Features
Exercises
Recursion Exercises
Exercise
Write a recursive method pow accepts an
integer base and exponent and returns the
base raised to that exponent.
Example: pow(3, 4) returns 81

Solve the problem recursively and without using


loops.
pow solution
// Returns base ^ exponent.
// Precondition: exponent >= 0
public static int pow(int base, int exponent) {
if (exponent == 0) {
// base case; any number to 0th power is 1
return 1;
} else {
// recursive case: x^y = x * x^(y-1)
return base * pow(base, exponent - 1);
}
}
Exercise
Write a recursive method isPalindrome accepts a String
and returns true if it reads the same forwards as backwards.
isPalindrome("madam") true
isPalindrome("racecar") true
isPalindrome("step on no pets") true
isPalindrome("able was I ere I saw elba") true
isPalindrome("Java") false
isPalindrome("rotater") false
isPalindrome("byebye") false
isPalindrome("notion") false
Exercise solution
// Returns true if the given string reads the same
// forwards as backwards.
// Trivially true for empty or 1-letter strings.
public static boolean isPalindrome(String s) {
if (s.length() < 2) {
return true; // base case
} else {
char first = s.charAt(0);
char last = s.charAt(s.length() - 1);
if (first != last) {
return false;
} // recursive case
String middle = s.substring(1, s.length() - 1);
return isPalindrome(middle);
}
}
Exercise solution 2
// Returns true if the given string reads the same
// forwards as backwards.
// Trivially true for empty or 1-letter strings.
public static boolean isPalindrome(String s) {
if (s.length() < 2) {
return true; // base case
} else {
return s.charAt(0) == s.charAt(s.length() - 1)
&& isPalindrome(s.substring(1, s.length() - 1));
}
}
Exercise
Write a recursive method reverseLines that accepts a file Scanner and
prints the lines of the file in reverse order.
Example input file: Expected console output:
Roses are red, Are belong to you.
Violets are blue. All my base
All my base Violets are blue.
Are belong to you. Roses are red,

What are the cases to consider?


How can we solve a small part of the problem at a time?
What is a file that is very easy to reverse?
Reversal pseudocode
Reversing the lines of a file:
Read a line L from the file.
Print the rest of the lines in reverse order.
Print the line L.

If only we had a way to reverse the rest of the lines of the file....
Reversal solution
public static void reverseLines(Scanner input) {
if (input.hasNextLine()) {
// recursive case
String line = input.nextLine();
reverseLines(input);
System.out.println(line);
}
}

Where is the base case?

Anda mungkin juga menyukai