Download Computer Science 1 Review Handout

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Computer Science 1A Review
August 2014
25
26
File input and output
And
Exceptions
** Samples on T drive
27
28
Formatting
Work on
Sep. 1
2
No School
Work Matrix
Programs
(2 magic square
programs)
3
Work on Magic
Square Programs
Handouts
Lab rules
Issue KHS CS
accounts / passwords.
Review through
matrices
Variance Program
29
Array Quiz
Work on program
4
5
Matrix Quiz
Regular Expressions
String Review
Work on Program:
Censored
Regular Expressions
8
9
10
11
12
String Quiz
Finish programs
Review for Test
TEST:
Arrays, Matrices &
Strings, formatting
and files
Work on Program:
ArrayList of Teachers
18
19
Work on Programs
Begin Graphics
Review
Work on Program
Review ArrayList
15
16
17
ArrayList Quiz
Work on Programs
Class Quiz
review classes
programs:
complex class
todo w/ interface
Work on Programs
Work on Graphics
programs
Starters on T drive
22
Review for test
Work on Graphics
programs
23
TEST:
ArrayLists and
Classes
24
25
26
Data Types / Declarations:
int
char
double
boolean
String
Imports:
import static java.lang.System.*;
import java.util.ArrayList;
import java.io.*;
import java.awt.*;
import java.util.*;
for output shortcuts (out.println())
for ArrayLists
for file handling
for colors
for Scanner
Input:
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
ignores leading white space; reads int up to but not
including next white space
double d = sc.nextDouble();
ignores leading white space; reads double up to but
not including next white space
String s = sc.nextLine();
reads all data through enter
String s2 = sc.next();
reads up to next white space (stores one word,
leaves pointer at white space)
char c = sc.nextLine().charAt(0);
reads all data through enter, but returns first
character only. If more data is entered, it is trashed
boolean b = sc.nextBoolean();
converts “true” or “false” to true or false
Output:
out.print(x);
out.println(x);
Math Operations:
+ - / * ++ -- % += -= *= /= %=
int by int is always int!!!
Conditionals:
Relational operators:
== >= <= != < >
Logical operators:
Simple if:
if (x > 5)
out.print(“x is greater than 5”);
else out.print(“x is not greater than 5”);
//NO SEMICOLON
Extended if:
if (x > 5)
out.print(“x is greater than 5”);
else if (x >= 0)
out.print(“x is greater than or equal to 0”);
else out.print(“x is negative”);
Nested if:
if (x >= 0)
if (x > 5)
out.print(“x is greater than 5”);
else out.print(“x is greater than or equal to 0”);
else out.print(“x is negative”);
Ternary operator:
result = a > b ? x : y;
if (a > b)
result = x;
else result = y;
switch (value)
{
case 1:
case 2:
default:
}
value must be int, char, boolean or enumerated
out.println(“value is 1”);
out.println(“values is 2”);
out.println(“value is not one or two”);
break;
break;
! && ||
Math Methods:
** All math methods are static methods (associated with class)
Math.sqrt
Math.abs
Math.max
Math.min
Math.pow
Math.random
Loops:
for (int x = 1; x <= 10; x++)
out.println(x);
int x = 1;
while (x <= 10)
{
out.println(x);
x++;
}
int x = 1;
do
{
out.println(x);
x++;
}
while (x <= 10);
//do while loops are like while loops except they are
//evaluated at end of loop (post-test)
//This means that all do while loops are executed
//at least one time.
*****************************************************************
Enhanced for loop
Traditional example:
Enhanced equivalent:
int x[] = {1,2,3,4,5};
int sum = 0;
for (int j = 0; j < 5; j++)
sum += x[j];
out.print(sum);
int x[] = {1,2,3,4,5};
int sum = 0;
for (int someName : x)
sum += someName;
out.print(sum);
In the enhanced for loop, someName takes on the value of x[whatever]. This loop works for all collections – thus
you can use it on ArrayList and other collections you will learn this year. The enhanced for loop is read-only, so it
is somewhat limited – meaning you cannot change the value of any collection element when using the enhanced
for loop.
*****************************************************************
Arrays:
int list [] = new int[5];
double numbers [] = new double[100];
String word [] = new String[50];
char letters [] = new char[1000];
5 zeros to begin
100 zeros to begin
50 strings empty strings (null)
1000 spaces
All indexes are from zero to one less than the length of the array.
Inserting an element:
public static void insert (int array[], int logicalSize, int num)
{
int index = 0;
/*
The following loop simply walks through the array while the number to be inserted
is greater than the value at the location. This insert assumes that the array is
in sorted order. Note that there are no curlies; only the index is incremented.
Also note the short-circuiting; the index is compared to the array length BEFORE the
value to be inserted is compared to the array value. If the value to be inserted
is greater than all values in the array, the value will be inserted at the end of
the array.
*/
while (index < logicalSize && num > array[index])
index++;
if (logicalSize +1 > array.size)
out.println("Insertion aborted; insufficient capacity");
else
{
/*
This loop starts at the back end of the array and moves all values one to the
right until the index of the value to be inserted is reached. At that point, the
new value can be added to the array without losing any previous data.
*/
for (int k = logicalSize; k > index; k--)
array[k] = array[k-1];
array[index] = num;
}
}
Deleting an element:
public static boolean delete(int array[], int logicalSize, int num)
{
boolean found = false;
// If the number is not in the array, it cannot be deleted.
// This allows us to notify the user if the value was not found,
int index = 0;
/*
This loop runs until the element to be deleted is found, or the we have reached the logical size.
The comparison to the length of the logical size prevents us from going past the end of the array
wasting execution time for non-existent elements.
*/
while (index < logicalSize && !found)
{
if (array[index] == num)
found = true;
//We are done – element to be deleted is at position index.
else
index++;
}
/*
If the element was found, we begin processing at the deleted element’s position and bump from right to left.
*/
if (found)
{
for (int k = index; k < logicalSize-1; k++)
array[k] = array[k+1];
}
return found;
}
File Input and Output
Creating a text file:
To create a text file, you can simply type in data as needed in JCreator, saving it as .txt or .dat. Be sure to press enter or
leave spaces, just as you would for keyboard input.
Reading and writing files:
The following sample will read the contents of the file, numbers.dat and print them into two separate files, evens.dat and
odds.dat.
import java.io.*;
import java.util.*;
public class InputAndOutput
{
public static void main(String[] args) throws IOException
{
int number = 0;
int list[] = new int[100];
String line;
int i = 0;
FileOutputStream EvensOut = new FileOutputStream("evens.dat");
FileOutputStream OddsOut = new FileOutputStream("odds.dat");
// Create new file output streams and connect to specified files
PrintStream pe = new PrintStream( EvensOut );
PrintStream po = new PrintStream( OddsOut );
//Create print stream and connect to the output stream
/********** I N P U T F I L E **********/
try
//What if there is a problem with file??
{
Scanner sc = new Scanner(new File("numbers.dat"));
//input file is just like keyboard, but come from file
while (sc.hasNextInt())
{
list[i] = sc.nextInt();
i++;
}
}catch(IOException e)
{
out.println("Error in file" + e.toString());
}
/********** O U T P U T F I L E **********/
int howmany = i;
for (i = 0; i < howmany; i++)
if (list[i] % 2 == 0)
pe.println(list[i]);
else po.println(list[i]);
pe.close();
po.close();
out.lprintln("Two files created");
}
}
//Write to evens.dat
//Write to odds.dat
//Close files. This is the point where all data
//is assured to be written to the files.
In this example, the user enters the file name. With this approach, you can run a program one or more times with different
data files.
public class test2
{
public static void main(String[]arg) throws IOException
{
int array[] = new int[1000];
int i = 0, counter = 0;
Scanner sc = new Scanner (System.in);
out.print("Enter the data file name: ");
String fileName = sc.nextLine();
Scanner fileIn = new Scanner(new File (fileName));
for (i = 0; fileIn.hasNextInt(); i++)
array[i] = fileIn.nextInt();
counter = i;
out.println("Data on file");
for (i = 0; i < counter; i++)
out.println(array[i]);
}
}
IOExceptions:
Since there could be problems with file objects, the file object is capable of producing errors beyond our control. For
example, suppose the file doesn’t exist or is corrupted. What if we try to do successive inputs beyond the end of the file?
These would all produce errors (exceptions). This requires the main heading to be:
public static void main(String args[]) throws IOException
IOException needs to be there in case of a file error. For a method that is capable of throwing a checked exception (of
which, IOException is a classic example) you can either handle the error in your code with try, catch, and finally…or you
can defer the response to the error up the calling chain with throws IOException. Incidentally, the IOException class also
requires the importing of the java.io.* package.
One line at a time:
One of the most critical lines above is while (sc.hasNextInt()).The control part of the while-loop, sc.hasNextInt( ), checks
for remaining data in the file. The loop will terminate when all data has been read.
You can check for your output file by simply opening even.dat or odds.dat in JCreator. (Be sure again that you are
referencing “all files” and not just java files.)
Formatting with printf
You can print a number x to the console with the statement System.out.print(x). That command will print x with
the maximum number of non-zero digits for that type. For example,
double x = 1000.0 / 3.0;
System.out.print(x);
prints
333.3333333333333
Notice that the System.out.print command defaults to print 13 decimal places.
Before JDK 5.0, formatting numbers was a bit of a hassle. Fortunately, JDK 5.0 brought back the printf method
in java.util from the C library. For example, the call
System.out.printf(“%8.2f”, x);
prints x with a field width of 8 characters and a precision of 2 characters. That is, the printout contains a leading
space and the seven characters:
_3333.33 (where _ represents a space). If the data is longer than the
specified width, the width is ignored. The printf commands defaults to 6 decimal places.
System.out.printf(“%f”, x); will print 333.333333.
You can supply multiple parameters to printf, for example:
System.out.printf(“Hello, %s. Next year, you’ll be %d”, name, age);
Each of the format specifiers that start with a % character is replaced with the corresponding argument. The
conversion character that ends a format specifier indicates the type of the value to be formatted: f is float, s is
string, and d is integer. In the example above, %s corresponds with the argument name; %d corresponds with
the argument age. The following table shows all conversion characters.
Conversion Character
d
f
s
c
b
n
%
Others:
x
o
e
g
h
t
Type
decimal integer
fixed-point floating point
String
character
boolean
line-separator
the percent symbol
Example
200
16.2
Katy
K
true
hexadecimal integer
octal integer
exponential floating point
general floating point
(shorter of e and f)
hash code
date and time
9f
237
16.23+01
%
42628b2
8/14/2005
In addition, you can specify flags that control the appearance of the formatted output. For example, the comma
flag adds group separators. For example:
System.out.printf(“%,.2f”, 10000.0 / 3.0);
prints 3,333.33
You can use multiple flags. For example, “%,(.2f” may be used to use group separators and enclose negative
numbers in parentheses.
Flags
Flag
Description
'-'
The result will be left-justified.
'#'
The result should use a conversion-dependent alternate form
'+'
The result will always include a sign
' '
The result will include a leading space for positive values
'0'
The result will have leading zeros
','
The result will have group separators
'('
The result will enclose negative numbers in parentheses
#
For (f) floating point, always includes decimal point
For x or o (hex / octal) always include 0x or 0 prefix
^
Convert to uppercase
$
Specifies the index of the argument to be formatted; for example, %1$d %1$x
prints the first argument in the decimal and hexadecimal
**** Argument index values start with 1, not with 0: %1$ formats the first argument, not the second.
The following gives an overview of the syntax:
System.out.printf(…)
1.
2.
3.
4.
5.
%
Argument index (You may use < if it is the same as the preceding argument
flag
width
conversion character OR precision character (for float) followed by conversion character.
PRINTF CLASS WORKSHEET
import java.util.*;
public class printfSample
{
public static void main(String[]arg)
{
int i = 5;
int j = 12;
double d = 12.333946;
double x = 5.27914;
double nodec = 12;
double money = 10000/3.0;
double IOU = -5000;
String str = "Katy High";
//OUTPUTS:
1.
System.out.printf ("\n %d, %x", j, j);
________________________
2.
System.out.printf("\n %.2f %.4f", x, d);
________________________
3. System.out.printf("\n %10.2f, %10.3f",x,d);
________________________
4. System.out.println(money);
________________________
5. System.out.printf("\n %,f", money);
________________________
6. System.out.printf("\n %5.2f", money);
________________________
7. System.out.printf("\n $%5.2f", money);
________________________
8. System.out.printf("\n $%,5.2f", money);
________________________
9. System.out.printf("\nBonus: $%.2f", money);
________________________
10. System.out.printf("\nMy debt: %,(.2f", IOU);
________________________
11. System.out.printf("\nCheck the argument list: %1$10.2f, %2$x, %2$d", d, j);
________________________
12. System.out.printf("\nCheck the argument list: %1$10.2f %2$x %2$d", d, j);
________________________
13. System.out.printf("\n %#f, %#x", nodec, j);
________________________
14. System.out.printf("\n %d %f", x, d);
________________________
System.out.println();
}
}
Arrays: Variance and Standard Deviation
In this program, you will read data from files, practice coding arrays and using the do while loop. You will run
the report for the data file specified by the user.
The data file will contain numbers to be added into your array. You will need to read through the file, count how
many numbers and add to your array. You will not have more than 100 numbers in any one file.
Your program will calculate the average, variance and standard deviation of values stored in an integer array
named inputValues. You will also need two other double arrays, difference and diff_squared, which will be
parallel arrays to inputValues.
inputValues:
Read in from the data file
difference :
This array will hold the differences of the elements in inputValues and the average of all
elements in inputValues.
diff_Squared:
This array will hold the square of each difference in the difference array.
The variance is calculate by
1. Subtracting the average from each value in inputValues and store the result in difference array.
2. Squaring the differences and store the result in diff_squared array.
3. Total the difference squared, divide by the total number of elements and store the result in variance.
The Standard deviation is the square root of the variance.
Use the System.out.printf command so that your output looks like this:
STANDARD DEVIATION AND VARIANCE REPORT
Input Value
15
16
14
29
9
20
Difference
-2.1667
-1.1667
-3.1667
11.8333
-8.1667
2.8333
Total: 103
Average: 17.1667
Variance: 38.4722
Standard deviation: 6.2026
Difference Squared
4.6944
1.3611
10.0278
140.0278
66.6944
8.0278
230.8333
To print in “pretty-column format”:
for (i = 0; i < inputValues.length; i++)
{
out.printf("%-20d", inputValues [i]);
out.printf("%-20.4f", difference[i]);
out.printf("%-20.4f", diff_squared[i]);
out.println();
}
Matrices:
int mat[][] = new int[5][10];
a table of 5 rows and 10 columns
containing 50 zeros
Remember rows then columns – RC Cola!
Using nested loops with matrices:
Process matrices using nested loops:
for (int r = 0; r < 5; r++)
{
for (int c = 0; c < 10; c++)
out.printf("%5d", mat[r][c]);
out.println();
}
Enhanced Loop:
for (int someName[] : mat)
//rows
{
for (int someName2 : someName)
//columns
out.printf("%5d", someName2);
out.println();
}
for (row = 0; row < 5; row++)
for (col = 0; col < 10; col++)
out.printf("%5d" ,mat [row][col]);
//prints the matrix in one long line
for (row = 0; row < 5; row++)
{
for (col = 0; col < 10; col++)
out.printf("%5d" ,mat [row][col]);
out.println();
}
//print the matrix in table-format
Remember the length command? You can use it with matrices too! If you use mat.length, it references the number of
rows. If you use mat[0].length, it references the number of columns in that row. So, you can re-write the previous block of
code as follows:
for (row = 0; row < mat.length; row++)
{
for (col = 0; col < mat [0].length; col++)
out.printf("%5d" ,mat [row][col]);
out.println();
}
//print the matrix in table-format
Matrix Programs
P6.18: Magic Squares
(From Big Java: Late Objects)
An n x n matrix that is filled with the numbers 1,2,3,…,n2 is a magic square if the sum of the elements
in each row, in each column, and in the two diagonals is the same value.
16
5
9
4
3
10
6
15
2
11
7
14
13
8
12
1
The first program will read values from a file, magic1.txt. Your input will first contain n (not
necessarily 4 as in the sample), followed by all the numbers for that matrix. (n x n) You should output
all the numbers and then state whether it is a magic square or not. Your file will contain several
matrices, so you will process until the entire file is read. You should have methods for each of the
following:
checkNumbers
returns true or false
Does each number 1 .. n2 occur in the user input?
equalSums
returns true or false
When the numbers are put into a square, are the sums of the rows,
columns, and diagonals each to each other?
(Pretty-column format – use printf!)
P6.19: Magic Squares 2
(From Big Java: Late Objects)
Implement the following algorithm to construct magic n x n squares; it works only if n is odd.
Set row to n-1. Set column to n / 2;
For k = 1 … n2
Place k at [row][column]
Increment row and column
If the row or column is n, replace it with zero.
If the element at [row][column] has already been filled,
Set row and column to their previous values.
Decrement row.
Here is the 5 x 5 you can get if you follow this method:
11
10
4
23
17
18
12
6
5
24
25
19
13
7
1
2
21
20
14
8
9
3
22
16
15
Write a program whose input is n and whose output is the magic square of order n if n is odd.
Strings
Instantiating String Objects:
 String name = new String(“Bob”);
 String name;
// leave blank to initialize with empty string
 String name = “Bob”;
 String name;
name = “Bob”;
 char data[] = {‘A’, ‘B’, ‘C’};
String str = new String(data);
Comparing Strings:
 Since String objects store addresses, we cannot compare them with ==, < or >.
 Use .equals(String s):
o name1.equals(name2);
o name.equals(“Bob”);
 OR use equalsIgnoreCase(String s)
o name1.equalsIgnoreCase(name2);
o name.equalsIgnoreCase(“BoB”);
 compareTo(String)
OR
compareToIgnoreCase(String)
o returns 0 if strings hold same value
(Example: name = “Bob”; name2 = “Bob”;
int x = name.compareTo(name2);
//returns 0
o negative if calling object is less than argument
(Example: name = “Bob”; name2 = “Dan”;
int x = name.compareTo(name2);
//returns -2 (B is -2 away from D)
o positive if calling object is greater than argument
(Example: name = “Bob”; name2 = “Dan”;
int x = name2.compareTo(name);
//returns 2 (D is 2 away from B)
(Example: name = “Debbie”; name2 = “Dan”;
int x = name.compareTo(name2);
//returns 4 (e is 4 away from a)
Other String Methods:
Given String st = “Katy High School; Katy, TX”
 charAt(int index)
o Example: char ltr = st.charAt(5);
//returns ‘H’
 indexOf(char)
o Example: int pos = st.indexOf(‘S’);
//returns 10
o Example: int pos = st.indexOf(‘x’);
//If not found, -1 is returned
 indexOf(char, int)
o Example: int pos = st.indexOf(‘h’, 10);
//returns 12
 indexOf(String)
o Example: int pos = st.indexOf(“Katy”);
//returns 0
 indexOf(String, int)
o Example: int pos = st.indexOf(“Katy”, 10);
//returns 18
 toUpperCase()
AND
toLowerCase()
o Example: String s2 = "bob";
System.out.print(s2.toUpperCase()); //outputs BOB
o Example: String s2 = “Bob”;
s2 = s2.toLowerCase();
//s2 now contains “bob”
 substring(int from)
o Example: String s = st.substring(10); //s contains “School; Katy, TX”
 substring(int FIRST, int LASTMINUSONE)
o Example: String s = st.substring(10,15);
//s contains “Schoo”
o NOTE: the returned string is from position 10 to 15-1. NOTE THE MINUS ONE!!!
 trim() Returns a string with leading a trailing spaces removed.


length()
Returns the length of a string
int len = st.length();
toCharArray() returns character array
char cArray[] = st.toCharArray();
String Concatenation:
 The ‘+’ and ‘+=” is used for string concatenation.
Example:
String s1 = “Katy”;
String s2 = “Tigers”;
String s3 = s1 + s2;
//s3 contains “KatyTigers”
OR:
String s3 = “”;
s3 += “Katy”;
//s3 contains “Katy”
s3 += “Tigers”;
//s3 contains “KatyTigers”

concat(String) does the same as the ‘+’ sign. It returns the concatenated string.
String s3 = s1.concat(s2);
//s3 contains “KatyTigers”
NEW:
 split(String s)
o Takes regular expression and returns a String array. Trailing empty strings are not included in the
array.
 endsWith(String s)
o Takes a String as argument and returns boolean value of true if the calling object ends with that
argument
o Example System.out.println(name.endsWith(“an”)); //outputs true when name contains “Dan”
 replace(char c1, char c2)
or replace (String s1, String s2)
o takes two parameters – both characters or both Strings
o returns string that replaces all occurrences of first argument with second argument
o Example: String word = “Mississippi”;
o word = word.replace(‘i’,’x’);
//word now contains “Mxssxssxppx”
Character evaluation:
static Character functions
 Character.isLetter(char)
returns true or false.
 Character.isDigit(char)
returns true or false
 Character.isLetterOrDigit(char)
returns true or false
 Character.isLowerCase(char)
returns true or false
 Character.isUpperCase(char)
returns true or false
 Character.isWhitespace(char)
returns true or false for whitespace
 System.out.println(Character.isLetter(name.charAt(j)));
CS2 String Review Worksheet
1. Consider the following program segment.
String s1 = "Computer";
String s2 = "Science";
String s3 = "SCIENCE";
out.println(s1.compareTo(s2));
out.println(s2.compareTo(s1));
out.println(s2.compareTo(s3));
out.println(s1.compareTo(s1));
out.println(s1.equals(s1));
What will be output when the program segment executes?
2. Consider the following program segment.
String s1 = "Computer";
String s2 = "put";
out.println(s1.indexOf(s2));
out.println(s1.indexOf(“z”));
out.println(s1.indexOf(“o”));
What will be output when the program segment executes?
3. Consider the following program segment.
String s1 = "computer";
for (int k = 1; k < s1.length(); k++)
out.println(s1.substring(0,k));
What will be output when the program segment executes?
4. Consider the following method.
public static String quest04 (String s)
// precondition: s does not equal null
{
String t = "";
for (int k = s.length()-1; k >= 0; k--)
t += s.substring(k,k+1);
return t;
}
What string value is returned by the call quest04("computer") ?
5. Consider the following method.
public static String quest05(String s)
// precondition: s does not equal null
{
String t = "";
for (int k = s.length()-1; k >= 0; k--)
t += s.substring(s.length()-1,s.length());
return t;
}
What string value is returned by the call quest05("computer") ?
6. Consider the following method.
public static String quest06(String s)
// precondition: s does not equal null
{
String t = "";
for (int k = 0; k < s.length(); k++)
t += s.charAt(k);
return t;
}
What string value is returned by the call quest06("computer") ?
7. Given the following strings:
String s1 = “computer”;
String s2 = “KHS”;
What is the output of the following code?
out.println(s1 + s2);
out.println(5 + 6 + s1);
out.println(5 * 6 + s1);
out.println(s1 + 5 * 6);
out.println(5 + s1 + 6);
8. Given the following strings:
String s1 = “Katy Tigers are Great!”;
What is the output of the following code?
String s2 = s1.replace(‘a’, ‘*’);
out.println(s2);
9. Given the following strings:
String s1 = “Katy Tigers are Great!”;
What is the output of the following code?
s1.toUpperCase();
out.println(s1);
out.println(s1.toLowerCase());
Answer key for CS2 String Review Worksheet:
1. -16
16
32
0
true
2. 3
-1
1
3. C
co
com
comp
compu
comput
compute
4. retupmoc
5. rrrrrrrr
6. computer
7. computerKHS
11computer
30computer
computer30
5computer6
8. K*ty Tigers *re Gre*t
9. Katy Tigers are Great!
katy tigers are great!
Regular Expressions
from: http://docs.oracle.com/javase/tutorial/essential/regex/intro.html
(more information on site)
Regular expressions are a way to describe a set of strings based on common characteristics shared by each
string in the set. They can be used to search, edit, or manipulate text and data. You must learn a specific syntax
to create regular expressions — one that goes beyond the normal syntax of the Java programming language.
Regular expressions vary in complexity, but once you understand the basics of how they're constructed, you'll
be able to decipher (or create) any regular expression.
\\
backslash character
To use a predefined character, it must be preceded by a \ as follows:
"abc".matches("\\w+");
Predefined character classes
.
\d
\D
\s
Any character (may or may not match the period)
A digit: [0-9]
A non-digit: [^0-9]
A whitespace character: [ \t\n\x0B\f\r]
\S
\w
\W
(tab, new line, vertical tabulation, form feed, carriage
return)
A non-whitespace character: [^\s]
A word character: [a-zA-Z_0-9]
A non-word character: [^\w]
Character Classes
[abc]
[^abc]
[a-zA-Z]
a, b,
or c (simple class)
Any character except a, b, or c (negation)
a through z or A through Z, inclusive (range)
The word "class" in the phrase "character class" does not refer to a .class file. In the context of regular
expressions, a character class is a set of characters enclosed within square brackets. It specifies the characters
that will successfully match a single character from a given input string.
Golden Nugget of Wisdom # 28 from Blue Pelican Java
The split method and regular expressions:
String s = “Weird things”; //Use for examples 1 – 7.
1. String sp[] = s.split(“i”);
//Looks for an exact match on the string
//sp[0] = “We”, sp[1] = “rd th” , sp[2] = “ngs”
2. sp = s.split(“\\s”);
// “\\s” means white space
// sp[0] = “Weird”, sp[1] = “things”
3. sp = s.split(“ei”);
//Looks for an exact match on the string
// sp[0] = “W”, sp[1] = “rd things”
4. sp = s.split(“m”);
//Looks for an exact match on the string
// sp[0] = “Weird things”
5. sp = s.split(“r|h”);
// “r|h” means either ‘r’ or ‘h’
//sp[0] = “Wei”, sp[1] = “d t”, sp[2] = “ings”
6. sp = s.split(“[hi]”);
// “[hi]” means h or i (same as “h|i”)
//The bracket indicated individual characters.
//sp[0] = “We”, sp[1] = “rd t”, sp[2] = “”, sp[3] = “ngs”
//(notice the element of zero length)
String s = “This is a cat. This is a dog.”;
7. “\\.” Escape sequence for a literal period.
sp = s.split("\.");
sp = s.split(“\\.”);
//Syntax error
//This is correct!
sp[0] = This is a cat
sp[1] = This is a dog
8.
Note if there is a match at beginning OR two matches side by side:
String r = "Mississippi";
res1[0] = “Mi”;
String[]res1 = r.split("s");
res1[1] = “”;
res1[2] = “i”;
res1[3] = “”;
res1[4] = “ippi”;
9.
String r = "Mississippi";
String[]res2 = r.split("i");
res2[0] = “M”;
res2[1] = “ss”;
res2[2] = “ss”;
res2[3] = “pp”;
10.
String n = "MMMissMMMippiMMM";
String []res3 = n.split("M");
res3[0] = “”;
res3[1] = “”;
res3[2] = “”;
res3[3] = “iss”;
res3[4] = “”;
res3[5] = “”;
res3[6] = “ippi”;
String s = "WaW7423WV is my password"; //Use for problem 11.
11. String sp[] = s.split("W[1-8]*|[^\\w]");
12.
13.
String s = “How are you?”;
String res[] = s.split("\\w");
for (int i = 0; i < res.length; i++)
{
if (res[i].equals(""))
out.println("EMPTY");
else out.println(res[i]);
}
//The delimiters are a W followed by zero or more digits between 1 and 8
//or
//not a word character.
sp[0] = “”
sp[1] = “a”
sp[2] = “”
sp[3] = “V”
sp[4] = “is”
sp[5] = “my”
sp[6] = “password”
sp[0] =””;
sp[1] = “”;
sp[2] = “”;
sp[3] = “ “;
sp[4] = “”;
sp[5] = “”;
sp[6] = “ “;
sp[7] = “”;
sp[8] = “”;
sp[9] = “?”;
//space
//space
Note if there is a match at beginning OR two matches side by side:
String r = "Mississippi";
res1[0] = “Mi”;
String[]res1 = r.split("s");
res1[1] = “”;
res1[2] = “i”;
res1[3] = “”;
res1[4] = “ippi”;
String r = "Mississippi";
String[]res2 = r.split("i");
res2[0] = “M”;
res2[1] = “ss”;
res2[2] = “ss”;
res2[3] = “pp”;
String n = "MMMissMMMippiMMM";
String []res3 = n.split("M");
res3[0] = “”;
res3[1] = “”;
res3[2] = “”;
res3[3] = “iss”;
res3[4] = “”;
res3[5] = “”;
res3[6] = “ippi”;
Regular expressions can be used with the following String methods:
• String [] split(String regex)
//splits String into elements of a String array around matches to the “regular expression” regex
• String replaceAll(String regex, String replacement)
//replace all matches to the regular expression regex with replacement
• String replaceFirst(String regex, String replacement)
//replace first match to the regular expression regex with replacement
Regex Worksheet
String s = "Welcome to CS2.";
String s2 = "123abc456xyz";
String q1[]= s.split("\\s");
out.println("q1 length: " + q1.length);
for (int i = 0; i < q1.length; i++)
out.println(q1[i]);
q1 length: __________________
output:
String q2[] = s.split("e");
out.println("q2 length: " + q2.length);
for (int i = 0; i < q2.length; i++)
out.println(q2[i]);
q2 length: __________________
output:
String q3[]= s.split("aeiou");
out.println("q3 length: " + q3.length);
for (int i = 0; i < q3.length; i++)
out.println(q3[i]);
q3 length: __________________
output:
String q4[] = s.split("[aeiou]");
out.println("q4 length: " + q4.length);
for (int i = 0; i < q4.length; i++)
out.println(q4[i]);
q4 length: __________________
output:
String q5[] = s.split("e|o");
out.println("q5 length: " + q5.length);
for (int i = 0; i < q5.length; i++)
out.println(q5[i]);
q5 length: __________________
output:
String q6[] = s.split(".");
out.println("q6 length: " + q6.length);
for (int i = 0; i < q6.length; i++)
out.println(q6[i]);
q6 length: __________________
output:
String s = "Welcome to CS2.";
String s2 = "123abc456xyz";
//from previous page
String q7[] = s.split("\\.");
out.println("q7 length: " + q7.length);
for (int i = 0; i < q7.length; i++)
out.println(q7[i]);
q7 length: __________________
output:
String q8[] = s.split("\.");
out.println("q8 length: " + q8.length);
for (int i = 0; i < q8.length; i++)
out.println(q8[i]);
q8 length: __________________
output:
String q9[] = s.split("elc");
out.println("q9 length: " + q9.length);
for (int i = 0; i < q9.length; i++)
out.println(q9[i]);
q9 length: __________________
output:
String q10[] = s.split("[elc]");
out.println("q10 length: " + q10.length);
for (int i = 0; i < q10.length; i++)
out.println(q10[i]);
q10 length: __________________
output:
String q11[] = s.split("[^e]");
out.println("q11 length: " + q11.length);
for (int i = 0; i < q11.length; i++)
out.println(q11[i]);
q11 length: __________________
output:
String q12[] = s2.split("[a-zA-Z]");
out.println("q12 length: " + q12.length);
for (int i = 0; i < q12.length; i++)
out.println(q12[i]);
q12 length: __________________
output:
String s = "Welcome to CS2.";
String s2 = "123abc456xyz";
//from previous page
String q13[] = s2.split("[^a-zA-Z]");
out.println("q13 length: " + q13.length);
for (int i = 0; i < q13.length; i++)
out.println(q13[i]);
q13 length: __________________
output:
String q14[] = s2.split("[0-9]");
out.println("q14 length: " + q14.length);
for (int i = 0; i < q14.length; i++)
out.println(q14[i]);
q14 length: __________________
output:
String q15[] = s2.split("[^0-9]");
out.println("q15 length: " + q15.length);
for (int i = 0; i < q15.length; i++)
out.println(q15[i]);
q15 length: __________________
output:
String q16[] = s.split("[^eo]");
out.println("q16 length: " + q16.length);
for (int i = 0; i < q16.length; i++)
out.println(q16[i]);
q16 length: __________________
output:
CS2 String Review Program: Program:
Censored!
Problem:
Write a program that censors certain words from a line of text. The letters in the censored words are to
be replaced by asterisks (*). The censored word may appear alone or may be contained in a word. If a
censored word is contained in a censored word, the longest word should be removed. If a line contains
more than one censored word, all instances should be removed.
Input:
The first line of the data set is a list of words to censor. Each word is separated by a
single space. On each of the following lines, there is a sentence. Letters may be
uppercase or lowercase.
data file:
pr79
Output:
Output each sentence with the censored words replaced with asterisks.
Assumptions:
Censored words will not be over lapping (i.e. the end of one word is not the beginning of another) even
though a censored word could be entirely contained in a censored word.
Sample Input:
the at rich poor chocolate ice
The richest people in the world are chocolate lovers.
Poor Richard's Almanac is the best choice for getting sage advice.
Rich chocolate and licorice threaten the rich and poor alike.
Sample Output:
*** ****est people in *** world are ********* lovers.
**** ****ard's Almanac is *** best cho*** for getting sage adv***.
**** ********* and licor*** thre**en *** **** and **** alike.
ArrayList Notes
Declaring an ArrayList:
 Generic object declaration
 ArrayList list = new ArrayList();
This list can contain different types of objects in the list. As they are removed, they must be
typecasted from generic Object to the specific type.
 Autoboxing in declaration
 ArrayList <String>list = new ArrayList<String>();
This list will only contain the object type within < >. As elements are removed, they assume
the original type and typecasting is not necessary.
Methods:
 void add(int index, Object obj)
 Inserts obj at index in the list
 ex: fruitList.add(1, “grapes”);
 void add(Object obj)
 Inserts obj at the end of the list
 ex: fruitList.add(“grapes”);
 int size()
 returns the number of elements in the list
 return type int
 Ex:
 System.out.print(“Fruits size: “+ fruitList.size());
 Object get(int index)
 returns the Object at the given index
 ex: String member = (String)fruitList.get(1);
 boolean isEmpty()
 returns true if the list contains no elements and false otherwise.
 int indexOf(Object obj)
 returns the index of the first instance of obj in the list or -1 otherwise.
 Object set(int index, Object obj)
 Replaces the element at the specified position (index) in this list with obj.
 ex: fruitList.set(1, “watermelon”); //replaces the object at position 1 with “watermelon”
 ex: System.out.println(fruitList.set(3,"plums")); //this will print the object that plums
replaced
 Object remove (int index)
 Removes the element at the specified position (index) in this list.
 the Object returned is the element that was removed
 ex: fruitList.remove(1);
 ex: fruitList.add(fruitList.remove(1));
To use ArrayLists you must import the ArrayList library:
import java.util.ArrayList;
Arraylists hold objects, and thus typecasting may be necessary. If you add an int or double, typecasting is
automatic with the most recent jdk (1.5). In other words, an int is added to an ArrayList as Integer. For
earlier versions, you must typecast to add an int as an Integer. When you use the get command, it
returns an Object, thus you need to typecast when it comes off the ArrayList.
String oneFruit = (String) fruitList.get(i);
You can output all elements in the ArrayList by doing the following command:
System.out.println(fruitList); will output:
[apples, grapes, watermelon]
Note that no loop is required.
CS2 ArrayList Review Worksheet
Write the output of each of the following code segments, given the ArrayList declaration:
ArrayList <String> numbers = new ArrayList <String> ();
1. numbers.add("Four");
numbers.add("Seven");
numbers.add("Ten");
numbers.add("Three");
numbers.remove(1);
out.println(numbers);
2. numbers.add("Eleven");
numbers.add("Seven");
numbers.add("Five");
numbers.add("Three");
numbers.set(0, numbers.remove(3));
out.println(numbers);
3. numbers.add("Eleven");
numbers.add("One");
numbers.add("Zero");
numbers.add(“Nine");
numbers.add(numbers.remove(0));
out.println(numbers);
4. numbers.add("Four");
numbers.add("Seven");
numbers.add("Ten");
numbers.add("Three");
for (int k = 0; k < numbers.size(); k++)
out.print(numbers.set(k,"Two") + " ");
5. numbers.add("Four");
numbers.add("Seven");
numbers.add("Ten");
numbers.add("Three");
numbers.remove(1);
numbers.remove(2);
out.println();
for (int k = 0; k < numbers.size(); k++)
out.print(numbers.get(k) + " ");
6. numbers.add("Four");
numbers.add("Seven");
numbers.add("Ten");
numbers.add("Three");
numbers.remove(numbers.size()-1);
numbers.remove(numbers.size()-1);
for (String x: numbers)
out.print(x + “ “);
7. numbers.add("Four");
numbers.add("Seven");
numbers.add("Ten");
numbers.add("Three");
for (int k = 0; k < numbers.size(); k++)
out.print(numbers.set(k,"Two") + " ");
out.println(“\n” + numbers);
8. numbers.add("Four");
numbers.add("Seven");
numbers.add("Ten");
numbers.add("Three");
numbers.add("Twelve");
numbers.add("Two");
for(int i = 0; i < numbers.size(); i++)
numbers.remove(i) ;
out.println(numbers);
9. numbers.add("Four");
numbers.add("Seven");
numbers.add("Ten");
numbers.add("Three");
numbers.add(numbers.remove(1));
out.println(numbers);
10. numbers.add("Four");
numbers.add("Seven");
numbers.add("Ten");
numbers.add("Three");
numbers.add(numbers.set(1,”One”));
out.println(numbers);
11. numbers.add("Four");
numbers.add("Seven");
numbers.add("Ten");
numbers.add("Three");
numbers.add("Twelve");
numbers.add("Two");
for(int i = 0; i < numbers.size(); i++)
numbers.add(numbers.remove(i));
out.println(numbers);
12. numbers.add("Four");
numbers.add("Seven");
numbers.add("Ten");
numbers.add("Three");
numbers.add("Twelve");
numbers.add("Two");
for(int i = 0; i < numbers.size(); i++)
numbers.add(numbers.remove(numbers.size()-1-i));
out.println(numbers);
13. numbers.add("One");
numbers.add("Two");
numbers.add("Three");
numbers.add("Four");
numbers.set(0, numbers.remove(3));
numbers.set(1, numbers.remove(2));
for (String x: numbers)
out.print(x + “ “);
Answer key for CS2 ArrayList Review Worksheet”
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
[Four, Ten, Three]
[Three, Seven, Five]
[One, Zero, Nine, Eleven]
Four Seven Ten Three
Four Ten
Four Seven
Four Seven Ten Three
[Two, Two, Two, Two]
[Seven, Three, Two]
[Four, Ten, Three, Seven]
[Four, One, Ten, Three, Seven]
[Seven, Three, Two, Ten, Four, Twelve]
[Two, Twelve, Three, Ten, Seven, Four]
Four Three
Teacher ArrayList Program
You are given a class called teacher.java that contains last name, first name, subject, and lunch. You are also
given a text file called KHS_teachers.txt and a starter file teacherSort.java. The code to read the data file and load
an ArrayList is done for you. As you work through your code, study the code to read from a file, tokenize the data
and load the ArrayList. Now are you are to finish the code so that it will print based on the menu and user choice.
For cases 1 – 5, you should prompt for the data and then output all corresponding data, without repeating the
match. For example, if I were to print all teachers with a first name of “Mary”, I would only output their last
names, subject and lunch using accessors. If I were printing all teachers I would use the toString method and
print all data for each teacher. Give an appropriate heading before the output.
Example execution:
1. Print teachers by Subject
2. Print teachers by Last Name
3. Print teachers by First Name
4. Print teachers by Lunch
5. Print all teachers
6. quit
Enter choice: 4
Enter lunch: OPEN
Teachers with a(n) OPEN lunch
Kim Doss (Technology)
Lorraine Day (German)
Suzanne Ball (SPED)
Mary Maltz (SPED-Para)
Paula Arnold (SPED)
Sherry Wisniski (SPED)
Deborah Brown (SPED)
Deborah Pipes (SPED)
Caffie Guzman (SPED)
Andrew Robinson (SPED)
Cheryl Schilling (SPED)
1.
2.
3.
4.
5.
6.
Print teachers by Subject
Print teachers by Last Name
Print teachers by First Name
Print teachers by Lunch
Print all teachers
quit
Enter choice: 1
Enter subject: Technology
Technology teachers:
Debbie Gamel B lunch
Art Myrick A lunch
Russell Sadberry C lunch
Norman Wied C lunch
Richard Youngblood A lunch
Kim Doss OPEN lunch
Classes:
A class is a programmer-defined data type that contains data and their associated operations (also called behaviors).
An object is a specific member of a class. Basically, it is the variable of type class.
Three characteristics:
1. An object has behavior as defined by the methods of its class.
2. An object has state. Its instance variables have particular values at any given time.
3. An object has a unique identity (or address). Student object Susan has a unique identify that is different from Student object
Mark.
Instance variables, also called data members, are data within the class.
Method members are behaviors of the object.
Important Vocabulary:
1. Polymorphism: This allows a single accessing feature, such as a method or operator, to have MANY FORMS. (Example: +
is for addition and string concatenation.
2. Encapsulation: The process of placing data and methods inside the same data structure.
3. Inheritance: The process of using features from an established higher class called the base class.
4. Instantiation: The process of creating a new object, or creating an instance of an object
Visibility Modifiers:
private: Usually instance variables are private and cannot be accessed outside their class.
public:
Usually methods are public and can be accessed outside their class.
Default if public – so if you omit the visibility modifier, it is public.
Type of methods:
1. Constructors:
2.
3.
Constructors are used to declare, or initialize an objects.
Constructors always have the same name as the class.
If there are multiple constructors, they are overloaded.
If nothing is in ( ), it is the default constructor.
Constructors are activated with the word new.
If the class has no constructor, Java provides a default constructor.
Mutators: used to change data members within the class
Accessors: used to access, but not change, data members within the class
toString:
1. Because an object is an address, when you output an object, you actually get the address.
2. The toString method is called to output the object’s string representation.
3. You will write a toString function for every class depending on how you want your output to appear.
4. toString is called automatically from print and println.
Aliasing:
Student John = new Student (“John”, 16, 4.1);
//stored at address 0x004ac4
Student Jane = new Student (“Jane”, 15, 2.0);
//stored at address 0x005f96
Jane = John;
Now, Jane contains 0x004ac4, all of John’s information!
Class Sample:
public class rectangle
{
private int length, width;
//Instance Variables
public rectangle()
{
length = 1;
width = 1;
}
//Default Constructor
public rectangle (int l, int w)
{
length = l;
width = w;
}
//Overloaded Constructor
public int getWidth()
{return width;}
//Accessor for width
public int getLength()
{return length; }
//Accessor for length
public void setLength(int l)
{length = l;}
//Mutator for length
public void setWidth(int w)
{width = w;}
//Mutator for width
public int getArea()
{return length * width;}
public int getPerimeter()
{return 2 * length + 2 * width;}
public String toString()
//toString method
{return "\nLength: " + length + "\nWidth: " + width;}
}
equals method:
Signature:
public boolean equals (Object obj)
The equals method is used instead of == since the == operator compares the addresses.
this:
The keyword, this, refers to the current object inside the class. It is the object on the left
side of, or “attached
to”, the dot operator from the calling method.
null reference:
The word null is a reserved word in java. It refers to a zero address, meaning a
constructor has not yet been run for an object. Consider the following:
fraction f;
//Not yet constructed. It contains a zero address (0x00000000)
Since the object is not constructed we cannot use any of the class methods to access data.
f.getNumerator() will result in a null pointer exception.
f = new fraction (4,5);
//Constructs the object after declaration. This works fine.
static:
The keyword static means that the method or variable is associated with the class rather than the object. All
references to the variable or method would be classname.method() or classname.variable. static is commonly
used when for totals, counters or constants.
Passing objects and primitive values:
import static java.lang.System.*;
public class temp
{
public static void main(String[]arg)
{
//Demonstration of parameter changes
parameterTest pt = new parameterTest();
int x = 1;
WHAT y = new WHAT(2);
WHAT z = new WHAT(3);
out.println("Before call to change values: ");
out.println(x + " " + y + z);
public class WHAT
{
//This does not make sense -- no instance variables -- but proves a
point
private int number;
public WHAT()
{
number = 0;
}
public WHAT(int x)
{
number = x;
}
public void setNumber(int x)
{
number = x;
}
public String toString()
{
return number + " ";
}
pt.changeValues(x,y,z);
out.println("After call to change values: ");
out.println(x + " " + y + z);
}
}
}
public class parameterTest
{
public void changeValues(int num1, WHAT num2, WHAT num3)
{
out.println("Inside changeValues: Before change: ");
out.println(num1 +" "+ num2 + num3);
num1=100;
num2.setNumber(200);
num3 = new WHAT(300);
out.println("Inside changeValues: After change: ");
out.println(num1 +" "+ num2 + num3);
}
}
The output for this program is:
Before call to change values:
1 2 3
Inside changeValues: Before change:
1 2 3
Inside changeValues: After change:
100 200 300
After call to change values:
1 200 3
Why is it that only the middle parameter changed?
The first is a simple int. It is passed “by value,” meaning that it copies the number into the receiving variable. Thus in this case, x is
copied into num1. The value x from main was not even accessed in the changeValues method.
The second parameter is passed by reference; it copies the address of y into the receiving variable, num2. Thus, both y and num2
contain the same address. When the value num2 is changed in changeValues, it is the exact same variable as y in main. When num2
changes, y also changes because they are one in the same.
The third parameter is also passed by reference, copying the address of z into the receiving variable num3. However, changeValues
constructs a new value, 300, into a new address. The value 300 is in the new location, not the location that was passed into
changeValues; the value z is left unchanged, since it was in a different memory location.
Class Program
Complex numbers are numbers of the form a + bi where a and b are real and i represent the square root of -1.
Complex number arithmetic is defined by:
plus:
minus:
times:
dividedBy:
(a + bi) + (c + di) = (a + c) + (b + d)i
(a + bi) - (c + di) = (a - c) + (b - d)i
(a + bi) (c + di) = (ac - bd) + (ad + bc)i
(a + bi) / (c + di) = (ac + bd) + (bc - ad)i
c2 + d2
c2 + d2
Write a class that will perform these calculations on two complex numbers. The main is on the T drive. The
main will read numbers from a file and output the result of your calculations. Each method within your class
will receive a complex number as a parameter. Example:
public String minus (complex x)
//parameter is a complex object
{
double s = a - x.getA();
double s2 = b - x.getB();
return "(" + onePlace.format(s) + " + " + onePlace.format(s2) + ")i";
}
Your class will need:
Default constructor:
Overloaded constructor:
Two Accessors:
Two Mutators:
The following methods:
plus
minus
dividedBy
times
toString:
Set both values to 1
Set both values to values passed in as parameters
getA and getB
setA and setB
Outputs as (a + bi)
Sample execution:
Complex numbers:
(4.0 + 3.0i)
Sum:
Difference:
Product:
Quotient:
5.0 + 5.0i
3.0 + 1.0i
-2.0 + 11.0i
2.0 + -1.0i
(1.0 + 2.0i)
Note:
At the beginning of the class, you will find the following command:
private DecimalFormat onePlace = new DecimalFormat("0.0");
This command is used to force one decimal place in the output. See the minus method above and follow the
example in your other methods.
Interfaces Notes:
 A Java interface is a "pure abstract class". This means there is no implementation.
 Interfaces are declared in a way similar to classes but
– consist only of public abstract methods (since public and abstract are default for interfaces you do
not need to write them)
– public final static fields
– This is like a contract between the class and compiler that states “I will declare all methods specified
by the interface.
 A Java class extends exactly one other class, but can implement as many interfaces as desired
 If more than one class implements an interface, its methods are polymorphic.
 To use the interface, the class must specify that it implements the interface declaration.
 The classes that implement the interface must define all methods in the interface.
 An interface is typically used in place of an abstract class when there is no default implementation to inherit
(no instance variables and no default method implementations).
 One of the most common interfaces is: Comparable
public interface Comparable
{
public int compareTo( Object other );
}
 compareTo should return an int <0 if the calling object is less than the parameter, 0 if they are equal, and an
int >0 if the calling object is greater than the parameter
The Comparable Interface:
The Comparable is one of the most common interfaces implemented in our programs. The interface states that
you must have a compareTo method. This method must have the following header:
public int compareTo (Object obj)
The method should return zero if two objects are equal, a negative number if the current object is less than the
object passed in as a parameter (obj) and a positive number if the current object is greater than the object passed
in as a parameter. Consider the following example from main followed by the implementation in fraction class:
if (f1.compareTo(f2) < 0)
out.println(f1 + " is less than " + f2);
else if (f1.compareTo(f2) > 0)
out.println(f1 + " is greater than " + f2);
else out.println(f1 + " is equal to " + f2);
public int compareTo (Object obj)
{
fraction temp = (fraction) obj;
int conum, objnum, comden;
comden = this.denominator * temp.denominator;
conum = this.numerator * temp.denominator;
objnum = temp.numerator * this.denominator;
return conum – objnum;
// *** OR JUST ***
}
Inheritance Notes (IS-A relationship): A grasshopper is a bug.
Extending a class to create a new class:
Using the keyword, extends, inheritance is the process of creating a new class (called the subclass) from an
existing class (called the parent class, superclass, or base class). The new class automatically contains some or
all of the variables and methods in the original class, depending on the visibility modifiers for the methods and
variables. The child class inherits variables and methods that are declared public or protected and does not
inherit those that are declared as private. The programmer can add new variables and methods to the derived
class, or change the inherited ones. Remember that constructors are NOT inherited in a child class, even though
they have public visibility. Since constructors are methods that are used to set up a particular type of object, it
would not make sense for a class horse to have a constructor mammal.
super:
The reserved word, super, can be used to refer to the parent class. Using super, we can use a parent’s members
even if they were not inherited. Super can be used to invoke the parent’s constructor, but remember that a
child’s constructor calls its parent’s constructor automatically! (As soon as the class encounters the word
“extends,” it leaves the current class and goes up one level to the parent. If that class also extends another, it
again immediately leaves to execute the parent’s constructor. Execution then proceeds back down the classes to
create the specific object.) The keyword, super, is used to call a specific constructor, rather than the default
constructor, but can also be used for clarity. This way a parent class always initializes its variables before the
child class constructor begins to execute. JAVA DOES NOT ALLOW FOR MULTIPLE INHERITANCE.
Java does not allow nested supers (ex: super.super.toString() is not allowed)
Details:
Remember, in Java you can implement multiple interfaces, but extend only one class. When a child class defines
a method with the same signature as the parent class, the child’s version overrides the parent’s version in favor
of its own. This is similar to an overloaded function, but since the signatures are the same, there is now no way
to access the parent function from the child. There is no limit to the number of children a class can have or to the
number of levels a class hierarchy can have. ALL classes are created from the Object class. If a class definition
does not use extends to create itself from another class, then that class is automatically created from the Object
class.
class Thing
and
class Thing extends Object are synonymous
Since toString and equals are in the Object class, all classes have access to these functions.
publicprivate -
accessible to all classes (Methods are usually public.)
accessible only within that class, thus hidden from all sub classes.
(Instance variables are usually private.)
protected - accessible by classes within the same package and all descendant classes
protected methods are commonly used to allow descendant classes to modify instance variables in
ways other classes can't
When a method in a class is declared as final, that method may not be overridden thus the behavior is
guaranteed for all decendants.
Composition models the Has-A relationship (or uses a)
A car has an engine
public class car
{
private engine engineType;
…………………
}
Abstract Classes
Notes:
 An abstract class is used to define a class but an object of that type never exists and can never be created or
instantiated.
 A method may be declared abstract in its header, after visibility modifier.
– no body to the method
– all derived classes must eventually implement this method (or they must be abstract as well)
– any class with 1 or more abstract methods must be an abstract class
 If a class inherits from an abstract class that has abstract methods those methods must be defined in the
child or the child must be abstract as well
 An abstract class is like a ghost class.
 It can pass along methods and variables, but it cannot ever be instantiated itself. Thus, we never create an
object of an abstract class.
 It is similar to an interface. Unlike an interface, however, an abstract class CAN contain methods that are
not abstract and it can contain variables other than constants.
 A class is declared as abstract by including the abstract modifier in the class header.
 An abstract class does NOT have to contain abstract methods.
 Abstract classes are like placeholders. It can contain a partial description that is inherited by all of its
descendants in the class hierarchy. Its children, which are more specific, fill in the gaps.
 Example: vehicle can be an abstract class since it is too general for any application. The general ideas that
apply to vehicle can be inherited by its more specific children, car, boat and plane.
 An abstract class can be created at any level, but they are more common higher in hierarchy.
 Typically, a child of an abstract class will have a specific definition for an abstract method inherited from its
parent.
 This is an example of overriding a method, giving a different definition than the one the parent provides.
 An abstract method cannot be made static. Because abstract methods are never implemented, an abstract
static method would make no sense.
Abstract Classes Exercises:
Questions 1-27: Consider the following hierarchy of classes.
Animal
<abstract>
Mammal
Reptile
<abstract>
<abstract>
Dog
Cat
Lizard
Snake
Assume that Animal, Mammal, and Reptile are abstract classes, and that Dog, Cat, Lizard and Snake are nonabstract classes. Assume that all classes have a default constructor.
Label each statement as valid or invalid. If invalid, tell why.
1.
Animal a1 = new Animal();
2.
Animal a2 = new Mammal();
3.
Animal a3 = new Dog();
4.
Animal a5 = new Reptile();
5.
Animal a6 = new Lizard();
6.
Mammal m1 = new Mammal();
7.
Mammal m2 = new Dog();
8.
Reptile r1 = new Snake();
9.
Reptile r2 = new Animal();
10.
Dog d1 = new Dog();
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
Dog d2 = new Mammal();
Cat c3 = new Animal();
Lizard t1 = new Lizard();
Lizard t2 = new Reptile();
Snake s1 = new Snake();
Snake s3 = new Animal();
Snake s4 = new Dog();
Mammal m3 = new Lizard();
Lizard t3 = new Snake();
Reptile r3 = new Mammal();
Assume now that the Mammal class has a method called speak that returns the string “noise” and that the Cat class
overrides that method and it returns the string “meow”. Specify (1) whether or not the declaration is valid or invalid
and if valid, (2) if declaration is valid, is the call to speak valid and (3) if the call to speak if valid, what is the value
returned by the call?
21.
22.
23.
24.
Dog d1 = new Dog();
d1.speak();
Animal a1 = new Cat();
a1.speak();
Mammal m1 = new Cat();
m1.speak();
Cat c1 = new Cat();
c1.speak();
25.
26.
27.
Cat c2 = new Mammal();
c2.speak();
Mammal m2 = new Mammal();
m2.speak();
Mammal m3 = new Dog();
m3.speak();
Abstract Classes Exercises (cont)
Questions 28-31: Consider the following classes.
public class ClassOne
{
public void methodOne()
{ methodTwo();
System.out.print("1");
}
public void methodTwo()
{
System.out.print("2");
}
}
public class ClassTwo extends ClassOne
{
public void methodOne()
{ System.out.print("3");
super.methodOne();
}
public void methodTwo()
{
System.out.print("4");
super.methodTwo();
}
}
Assume the following declarations have been made.
ClassOne c1 = new ClassOne();
ClassOne c2 = new ClassTwo();
28. What is the output of the following statement?
c1.methodOne();
29. What is the output of the following statement?
c1.methodTwo();
30. What is the output of the following statement?
c2.methodOne();
31. What is the output of the following statement?
c2.methodTwo();
Key to Abstract Classes Exercises:
1. I
2. I
3. V
4. I
5. V
6. I
7. V
8. V
9. I
10. V
11. I
12. I
13. V
14. I
15. V
16. I
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
I
I
I
I
V – noise
V – syntax error
V – meow
V - meow
I
I
V – noise
21
2
3421
42
Practice Test: Arrays, Matrices and Strings
1. How do you find the length of an array called employees?
A.
employees.length()
C.
B.
employees.size()
D.
employees.size
employees.length
2. Which of the following is a correct declaration for an array, of type double with fifteen elements?
A.
double array = new double (15);
C.
double array [ ] = new double[15];
B.
double array = new double[15];
D.
double array [ ] = new double(15);
3. Which of the following is a correct declaration for an array, integers, of type int initialized to 1,2,3,4,5?
A.
int integers [5] = {1, 2, 3, 4, 5} ;
C.
int integers [ ] = {1,2,3,4,5};
B.
int integers [5] = 1,2,3,4,5;
D.
int integers [ ] = 1,2,3,4,5;
0
1
4
9
16
25
36
49
64
81
4. Which of the following blocks of code will store the listed values in array number above?
A.
B.
for (j = 0; j < 10; j++)
number[j] = j;
for (j = 0; j < 10; j++)
number[j] = j * j;
C.
for (j = 10; j > 0; j--)
number[j] = j * j;
for (j = 10; j > 0; j--)
{
out.println(“Enter number:”);
number[j] = sc.nextInt();
}
D.
Answer questions 5 - 6 using array num below:
-7
8
-15
0
6
22
1
-3
5. What is the output of the following statement?
for (x = 0; x < 10; x++)
if (num[x] % 2 == 0)
out.print( num[x] + “ “);
A.
B.
8 6 22 4
8 0 6 22 4
C.
D.
-7 -15 6 1 4
-15 6 1 4
C.
D.
-7 0 1 9
0 15 30 45
6. What is the output of the following statement?
for (x = 0; x < 10; x= x + 3)
out.print( (num[x] * 5) + “ “);
A.
B.
-35 0 5 45
-35 0 5
4
9
Use the following array to specify the output for questions 7 – 13.
2
9
7
16
3
12
4
22
33
17
7. for (j = 9; j >=0; j--)
out.print(num[j] + “ “);
A.
2 9 7 16 3 12 4 22 33 17
B.
17 33 22 4 12 3 16 7 9 2
C.
D.
9 8 7 6 5 4 3 2 1 0
Out of range error
8. for (j = 0; j < 10; j++)
if (num[j] % 3 == 0)
out.print(j + “ “);
A.
9 3 12 33
B.
0 3 6 9
C.
D.
1 4 5 8
2 16 4 17
C.
D.
3 16 5 12 7 22 8 33 9 17
No output
10. for (j = 0; j < 10; j++)
if (num[j] % 2 != 0)
out.print(num[j+1] + “ “);
A.
B
C.
D.
7 16 12 17
9 7 3 33 17
9 7 16 12 17
Out of range error.
11. x = 0;
for (j = 0; j < 10; j++)
x += num[j];
out.print(x);
A.
B.
C.
D.
2 9 7 16 3 12 4 22 33 17
2 9 7 16 3 12 4 22 33
125
Out of range error.
12. x = 0;
for (j = 0; j < 10; j++)
if (num[j] %3 == 0)
x++;
out.print(x);
A.
B.
C.
D.
9 3 12 33
57
4
Out of range error.
13. for (j = 9; j >=0; j-=3)
out.print(num[j] + “ “);
A.
B.
C.
D.
2 16 4 17
17 4 16 2
0 3 6 9
9 6 3 0
9. for (j = 0; j < 10; j++)
if (num[j] > 10)
out.println(j + “ “ + num[j]);
A.
16 12 22 33 17
B.
3 16
5 12
7 22
8 33
9 17
14. Which of the following shows the correct way to declare a matrix of integers, called IntMat, with 6 rows and 8
columns?
A.
B.
int intMat = new int[6][8];
int intMat = new int[8][6];
C.
D.
int intMat[][] = new int[6][8];
int intMat[][] = new int[8][6];
15. Given a properly declared matrix called Matrix, what is the output of the following code?
int K = 10;
for (R = 0; R < 3; R++)
{
K--;
Matrix[R][C] = K;
}
A.
for (R = 0; R < 3; R++)
{
for (C = 0; C < 3; C++)
out.print(Matrix[R][C] + " ");
out.println();
}
B.
1 2 3
4 5 6
7 8 9
C.
1 4 7
2 5 8
3 6 9
D.
10 9 8
7 6 5
4 3 2
9 8 7
6 5 4
3 2 1
16. Given a properly declared matrix called Mat, what is the output of the following code?
int K = 0;
for (R = 0; R < Mat.length; R++)
for (C = 0; C < Mat[0].length; C++)
{
K++;
Mat[R][C] = K;
}
for (R = 0; R < Mat.length; R++)
{
for (C = 0; C < Mat[0].length; C++)
out.printf("%-5d", Mat[R][C]);
out.println();
}
A.
C.
1
7
13
19
25
1
6
11
16
21
26
2
8
14
20
26
2
7
12
17
22
27
3
9
15
21
27
3
8
13
18
23
28
4
10
16
22
28
4
9
14
19
24
29
5
11
17
23
29
5
10
15
20
25
30
6
12
18
24
30
B.
D.
1
2
3
4
5
6
7
8
9
10
11
12
Out of range error
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Given the following matrix called Table, answer questions
5
9
8
5
7
9
5
4
7
6
4
3
7
2
3
7
7
5
9
8
17 – 20.
3
3
3
0
2
17. What is the output given the following matrix, and the block of code:
sum = 0;
for (int x = 0; x < Table.length; x++)
sum += Table[x][2];
out.println(sum);
18. Given the following code, what is the output:
for (row = 0; row < 2; row++)
for (col = 0; col < 3; col++)
out.print(Table[row][col] + “ “);
19. for (int r = 0; r < Table.length; r++)
for (int c = 0; c < Table[0].length; c++)
if (r == c)
out.print(Table[r][c] + " ");
20. for (int r = 0; r < Table.length; r++)
for (int c = 0; c < Table[0].length; c++)
if (r + c==Table.length-1)
out.print(Table[r][c] + " ");
Choose the output for questions 21 – 27 given:
String str = “Would you like to learn GUI?”;
21. out.println(str.charAt(4));
a.
space
b.
d
c.
d.
l
y
22. out.println(str.indexOf(‘u’));
a.
3
b.
2
c.
d.
2, 8
-1
23. out.println(str.indexOf(‘u’,5));
a.
2
b.
2, 8
c.
d.
8
-1
24. out.println(str.substring(10,14));
a.
like
b.
[space]like[space]
c.
d.
[space]like
like[space]
25. out.println(str.substring(15));
a.
learn GUI
b.
to learn GUI
c.
d.
to learn GUI?
error message
26. out.println(str.replace('e','E'));
a.
Would you likE to learn GUI?
b.
Would you like to lEarn GUI?
c.
d.
Would you like to learn GUI?
Would you likE to lEarn GUI?
27. String str = “Would you like to learn GUI?”;
String words[] = str.split(“[aeiou ]”;
for (int k = 0; k < str.length; k++)
out.println(str[k]);
//The “_” designates a space in output.
a.
Would
b.
W
you
ld
like
y
to
l
learn
k
GUI?
t
l
rn
GUI?
//includes space after the u
c.
W
ld
y
l
k
t
l
rn
G
?
28. Consider the following program segment.
String s1 = "cat", s2 = “Cat”, s3 = “goat”;
out.println(s3.compareTo(s1));
out.print(s1.compareTo(s2) + " ");
What will be output when the program segment executes?
a.
-4
-32
c.
b.
4
32
d.
4
-4
d.
W
ld
y
l
k
t
l
rn
GUI
-32
32
29. Which of the following statements is true about the String class and the compareTo method?
a.
The String class implements the Comparable interface, which requires compareTo method.
b.
The String class implements the Object interface, which requires compareTo method.
c.
The String class extends the Object class and redefines the compareTo method.
d.
The String class extends the Comparable class and redefines the compareTo method.
30. Which of the following statements is true about the String class and the equals method?
a.
b.
c.
d.
The String class implements the Object interface, which requires the equals method.
The String class implements the Comparable interface, which requires the equals method.
The String class extends the Object class and redefines the equals method.
The String class extends the Comparable class and redefines the equals method.
31. What is the output of this code?
String c = "www.tcea.org";
out.println(c.split("\\.")[1]);
32. What is the output of this code?
a.
b.
c.
www
tcea
org
d.
e.
tc
ww
a.
true
b.
false
String f = "beanandhamgocamping";
out.println(f.matches(".*am.*"));
33. What is the output of the code below?
a.
String a = "[email protected]";
b.
String[] s = a.split("m");
c.
String[] t = a.split("o");
d.
String[] u = a.split("o+");
e.
out.println(s.length + " " + t.length + " " + u.length);
2
4
3
3
3
4
4
3
4
4
3
3
3
3
4
34.
35.
What is the output of this code?
String it = "[to]";
String chunks = "on my way to state";
String[] pieces = chunks.split(it);
for( int i = 0; i < pieces.length; i++)
{
if (pieces[i].equals(""))
out.println(i + ": empty");
else out.println(i + ": " + pieces[i]);
}
a. 0: empty
1: n my way
2: empty
3: s
4: a
5: e
b. 0: n my way
1: s
2: a
3: e
c. 0: n my way
1: empty
2: s
3: a
4: e
d. 0: empty
1: n my way
2: emtpy
3: empty
4: s
5: a
6: 3
What is the output of this code?
a.
String s = "UIL SCHOLARSHIPS";
String t[] = s.split("[AIO]");
out.print(s.matches(".*I.*L.+"));
out.print(" " + t.length);
out.println(" " + t[3]);
b.
c.
d.
e.
true 5 L
false 5 RSH
true 5 RSH
false 4 L
true 4 L
FREE RESPONSE
Given arrays nums1 and nums2 of the same length, for every element in nums1, consider the corresponding element in
nums2 (at the same index). Return the count of the number of times that the two elements are the equal.
countSame({1, 2, 3}, {1, 2, 10})
countSame ({1, 7, 2, 3}, {1, 4, 2, 3})
countSame ({1, 2, 3, 15, 28}, {2, 3, 4, 5, 9})
public static int countSame (int nums1[], int num2[])
{
}
→2
→3
→0
Given a matrix called nums, output the smallest and largest values as well as their locations. If
there are duplicates, you may simply output the location of any one of the values.
public void range (int nums[][])
{
}
Given a string called s, return true if the string is a palindrome and false otherwise.
public boolean isPalindrome (String s)
{
}
Arrays, Matrices and Strings Answer Key
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
D
C
C
B
B
A
B
C
B
D
C
C
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
B
C
D
C
19
5 9 4 9 5 3
5 5 7 9 2
3 7 7 7 7
B
B
C
A
countSame:
int count = 0;
for (int i = 0; i < nums1.length; i++)
if (nums1[i] == num2[i])
count++;
return count;
range:
int small = nums[0][0], big = nums[0][0], sr = 0, sc=0, br = 0, bc=0;
for (int r = 0; r < nums.length; r++)
for (int c = 0; c < nums[0].length; c++)
{
if (nums[r][c] > big)
{
big = nums[r][c];
br = r;
bc = c;
}
if (nums[r][c] < small)
{
small = nums[r][c];
sr = r;
sc = c;
}
}
out.println(“The largest number is “ + big + “ at nums[“ + br + “][“ + bc + “]”);
out.println(“The smallest number is “ + small + “ at nums[“ + sr + “][“ + sc + “]”);
isPalindrome:
for (int f = 0, b = s.length()-1; f < b; f++, b--)
if (s.charAt(f) != s.charAt(b))
return false;
return true;
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
C
D
B
B
A
C
B
A
D
A
C