Primitive data types - you use these data types to create variables which are storage locations in the computer's memory - they have no other built in capability other than storing a value.
byte short int long char float double boolean
postfix mode - number++;
prefix mode - ++number;
increment operator - increase value by one number++;
number++; == number = number + 1;
decrement - decrease value by one
number--; == number = number - 1;
Conditional Loop - executes as long as a particular condition exists
Count-Controlled Loop - a loop that repeats a specific number of times
- must initialize a control variable to a starting value
- must test a control variable by comparing it to a maximum value. When the control variable reaches its maximum value, the loop terminates
- it must update the control variable during each iteration. This is usually done by incrementing the variable.
iteration - each repetition of a loop
loop control variable - controls the number of time that the loop iterates
infinite loop - if a loop does not have a way of stopping it continues to repeat until the program is interrupted
user controlled loop - allows the user to decide the number of iterations
pretest loop - tests the Boolean expression before an iteration
2 parts
-
Header: BooleanExpression is any valid Boolean expression
-
Body: Any valid Java statement. A statement or block of statements that repeats as long as the expression is true.
-
it will never iterate if the Boolean expression is false input validation - a while loop can be used to create input routines that repeat until acceptable data is entered
=====
while (BooleanExpression)
Statement;
=====
int number = 1;
while (number <= 5)
System.out.println("Hello")
number++;
=====
p.194 A posttest loop - its Boolean expression is tested after each iteration
do
{
Statement;
Statement;
}
while (BooleanExpression);
Ideal in situations
loop header
for (count = 1; count <= 5; count++)
initialization; expression test expression; update expression
counter variable - keeps count of the number of iterations
multiple initialization & update expressions
p. 203
int x, y;
for (x =1, y =1; x <= 5; x++)
{
System.out.println(x + " plus " +
" equals " + (x+y));
}
multiple Boolean expressions
use the && or || operators
input validation - a while loop can be used to create input routines that repeat until acceptable data is entered
priming read - the read operation that takes place just before the loop is called. it tests the loop to see if the input value is good.
accumulator - a variable used to keep the running total. it is initialized with a starting value which is usually zero
running total - a sum of numbers that accumulates with each iteration of a loop it accumulates the total as it reads each number in the series
sentinel value - a value that signals when the end of a list of values has been reached- cannot be mistaken as a member of the list - signal that there are no more values to be entered
They are necessary when a task performs a repetitive operation and that task itself must be repeated. p.211 (example: a clock)
- an inner loop goes through all of its iterations for each iteration of an outer loop
- inner loops complete their iterations before outer loops do
- to get the total number of iterations of a nested loop, multiply the number of iterations of all the loops
p.212
break statement - causes a loop to terminate early
- use in switch statement (chapter 3) but not in a loop (It makes the code difficult to understand and debug.)
continue statement - cause a loop to stop its current iteration and begin the next one.
When continue is encountered all the statements in the body of the loop that appear after it are are ignored and the loop prepares for the next iteration
In a While Loop
- the program jumps to the Boolean expression at the top of the loop, if the expression is true the next iteration begins
In a DO-While Loop
- the program jumps to the Boolean expression at the bottom of the loop which determines whether the next iteration will begin
In a For Loop
- continue cause the update expression to be executed and then the test is evaluated
- Ideal where you do not want the loop to iterate if the condition is false from the beginning
- Ideal if you want to use a sentinel value
- Ideal when you want the loop to iterate at least once
- Ideal in situations where the exact number of iterations is known
- the file must be opened
- data is then written to the file or read from the file
- the file must be closed
input file - file the program read data from
output file - file the program writes data to
text file - contains data that has been encoded as text
binary file - contains data that has not been converted to text you caanot view the contents with a text editor
p.215 buffer - a small holding section of memory
print or println method writes a line of data to a file
PrintWriter outputFile = new PrintWriter("StudentData.txt");
p.
To get input from a user:
Scanner keyboard = new Scanner(System.in);
To read input from a file:
File myFile = new File("StudentData.txt");
Scanner inputFile = new Scanner(myFile);
methods - can be used to break a complex program into small manageable pieces
void method - executes a group of statements ant then terminates
value returning method - performs a task and returns a value to the statement that called it
examples: Integer.parseInt
int number;
String str = "700";
number = Integer.parseInt(str);
=====
p.272 The name of this method is sum. The return statement is return result. *Expression is the value to be returned. The sum method returns the value in the result variable.
public static int sum(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}
predefined methods - methods in the Java API such as System.out.println, Integer.parseInt, Math.pow
divide and conquer - a large problem is divided into several smaller and smaller pieces
functional decomposition - the process of breaking down a problem into smaller pieces
code reuse - the benefit of using methods - a method can be written once and be executed as many times as needed - small methods
definition: header and a body
method header - lists several important things about the method including the method name - method modifier, return type, method name, parenthesis
method header - return type - method name - parenthesis
public static - void - displayMessage ()
method modifier - the key words public and static are modifiers public - the method is publicly available outside the class static - the method belongs to the class not the specific object
return type - a void method does not return a value, value returning methods list a data type here
method name - a descriptive name
parenthesis - where the argument would go
method body - a collection of statements that are performed when the method is executed - these are enclosed inside a set of curly braces
call a method - a method executes when it is called
Hierarchical Method Call or layered - method A calls method B calls method C When C finishes the JVM returns to method B, when B finishes the JVM returns to method A
arguments (actual/formal arguments) - values that are sent into a method, when passing an argument to a method be sure that the argument's data type is compatible with the parameter's data type.
System.out.println("Hello");
widening conversion - p.260 if the argument's data type is ranked lower than the parameter variable's data type Java will automatically convert it
passed by value - p.262 arguments of the primitive data types are passed by value, only a copy of an argument's value is passed into a parameter variable. If a parameter variable is changed inside a method, it has no effect on the original argumet
parameter variable (actual/formal parameters) - a variable that holds a value being passed into a method
passing a variable as an argument:
wrong: displayValue(int x);
right: displayValue(x);
passing object references to a method - p.263 This method accepts a String object as its argument and displays a message showing the number of characters in the object.
public static void showLength(String str)
{
System.out.println(str + " is " + str.length() +
" characters long.");
}
immutable - p.264 -266 String objects are immutable - they cannot be changed. Any time you use the = operator to assign a string literal to a String reference variable, a new String object is created in memory.
@param tag documentation - p.267 the description of each parameter variable
@return documentation - p.274 description of the method's return value
parameter list - two parameter variables declared in the method header
Julie
parameter scope - part of the program where the variable may be accessed by it's name. A parameter's scope is the method in which it appears.
local variable - declared inside a method. it is NOT accessible to statements outside the method. Different methods can have local variables with the same names because the methods cannot see each other's local variables
local variable lifetime - p.270 a method's local variable exists only while the method is executing.
initializing local variables with parameter values -
public static void showSum(double num1, double num2)
{
double sum = num1 + num2;
System.out.println("The sum is " + sum);
}
calling a value returning method - p.273 when you call one you usually want to do something meaningful with the value it returns p 274
returning a Boolean value - p.278
public static boolean isValid(int number)
{
if (number >= 1 && number <= 100)
status = true;
else
status = false;
return status;
}
returning a reference to an object - p. 279 a value returning method can also return a reference to a non-primitive type like a String object - here the fullName method returns a String object containing "John Martin"
public class ReturnString
{
public static void main(String[] args)
{
String customerName;
customerName = fullName("John", "Martin");
}
public static String fullName(String first, String last)
{
String name;
name = first + " " + last;
return name;
}
}
calling a method that throws exceptions - p. 284 if a method call another method that has a throws clause in its header, then the calling method should have the same throws clause
Putting a semicolon at the end of a method header - Method headers are never terminated with a semicolon
Writing modifiers or return types in a method call statement - Method modifiers and return types are written in the method headers but never in the method calls.
Forgetting to write the empty parenthesis in a call to a method that accepts no arguments
Forgetting to pass arguments to methods that require them.
Passing an argument of a datatype that cannot be automatically converted to the data type of the parameter variable. -
Attempting to access a parameter variable with code outside the method where the variable is declared -
Not writing the data type of each parameter variable in a method header -
Changing the contents of a method's parameter variable and expecting the argument that was passed into the parameter to change as well. -
Using a variable to receive a method's return value when the variable's data type is incompatible with the data type of the return value. -
Not writing a return statement in a value returning method -
Not writing a required throws clause in a methods that calls another method. -
-
A void method does not return a value.
-
A header appears at the beginning of a method definition.
-
The body of the method is enclosed in curly braces.
-
A method header can contain the method name, method modifier, method return type, method name, parenthesis, a list of parameter declarations.
-
A value passed into a method when it is called is a parameter.
-
A variable that receives a value that is passed into a method is an argument.
-
An @param tag is a javadoc tag used to document a parameter variable.
-
A return statement causes a method to end and sends a value back to the statement that called the method.
-
An @return tag is a javadoc tag used to document a method's return value.
-
You NEVER terminate a method header with a semi-colon.
-
& 12. When passing an argument to a method, Java will automatically convert the argument's data type if it is ranked lower than the parameter variable's data. This is called widening conversion.
-
A paramter variable's scope is only in the method in which the parameter is declared.
-
When code in a method changes the value of a parameter, it also changes the value of the argument that was passed into the parameter.
-
When an object, such as a String, is passed as an argument, it is actually a reference to the object that is passed.
-
The contents of a String object cannot be changed.
-
When passing multiple arguments to a method, the order in whichthe arguments are passed are not important.
-
No two methods in thesame program can have a local variable with the same name.
-
It is possible for one method to access a local variable that is declared in another method.
-
You must have a return statement in a value-returning method.
A class is a blueprint for an object. It specifies the fields and methods a particular type of object has. From the class one or more objects may be created
class - a blueprint that objects may be created from or cookie cutter
procedural programming - p.297 program made of one or more procedures, set of statements that perform a specific task
objected oriented programming - programming centered on creating objects
object - a software entity - a self-contained unit consisting of data (fields) and procedures (methods) - house or cookie
objects fields - the data contained in an object
methods = procedures an object performs
OOP - Object Oriented Programming - addresses the problem of code/data separation through encapsulation and data hiding.
encapsulation - refers to the combining of data and code into a single object
data hiding - refers to an object's ability to hide its data from code that is outside the object. Only the objects methods may then directly access and make changes to the object's data. This protects it from accidental corruption.
object re-usability - p.299 also helps with code/data separation
state - the data that is stored in the object's field at any given moment
access specifier - where the class may be accessed from ie: public private protected
private method - methods only available inside the class - access specifier p.305
public method - methods that can be accessed outside the object
instance method / class methods - p.306 public void setLength(double len) do not write the word static in the header - stores a value
instance of a class - each object that is created from a class
class objects - normally have methods that perform useful operations on their data
primitive variable - only sore data and have no methods any operations performed on a primitive variable must be written in code that is external to the variable
UML diagram - Unified Modeling Language p.304 a set of standard diagrams for graphically depicting object oriented systems illustrates a class,its fields, its methods in that order.
It is common practice to make all of a class's field private and to provide public methods for accessing and changing those fields. p.317
UML Diagram of the Rectangle Class p.318
Rectangle class |
----------|-----------------
fields |
length |
width |
methods |
setLength | stores a value in length field
setWidth | stores a value in width field
getLength | returns the value from length field
getWidth | returns the value from width field
getArea | returns the area, length * width
String object - for each string literal that appears in a program a String object is created in memory to hold it.
Class Objects normally have methods that perform useful operations on their data
Primitive variable only store data and have no methods. any operations performed on a primitive variable must be written in code that is external to the variable
members - p.305 fields and methods that belong to a class
accessor method / getter - a method that gets a value from a classes field but does not change it
mutator method / setter - a method that stores a value in a field or changes the value of a field in some other way
stale data - when the value of an item is dependent on other data and that item is not updated when the other data is changed the item has become stale p. 318 do not store calculated data in a field instead write a method that returns the result of the calculation
Access Specification in UML Diagram - p.318 - means private method | + means public method
Rectangle class |
----------|-----------------
fields |
-length :double |
width :double |
methods |
- setLength(len :double) :void | stores a value in length field
- setWidth(w :double) :void | stores a value in width field
- getLength() :double | returns the value from length field
- getWidth() :double | returns the value from width field
- getArea() :double | returns the area, length * width
When a variable is said to reference an object is stores the memory address of the object in the variable. p.308 bottom of page
instance fields / instance variables - you can create several instances of a class and store different values in each instance's fields - every instance of a class has its own set of instance fields and can store its own values in those fields
instance methods - the methods that perform operations on a specific instance of a class - instance methods do not have the key word static in their headers
constructor method - a method that is automatically called when an object / class is created - they normally perform initialization or setup operations such as storing initial values in instance fields. They help construct an object. Has the same name as the class p.325 constructor are not executed by explicit method calls and cannot return a value
public Rectangle(double len, double w)
method header for a constructor:
AccessSpecifier ClassName(Parameters...)
UML diagram showing a class's constructor p.327
Rectangle class |
----------|-----------------
fields |
-length :double |
width :double |
methods |
Rectangle(len :double, w :double) |
- setLength(len :double) :void | stores a value in length field
- setWidth(w :double) :void | stores a value in width field
- getLength() :double | returns the value from length field
- getWidth() :double | returns the value from width field
- getArea() :double | returns the area, length * width
uninitialized reference variable - Rectangle box; this variable is declared but the variable does not yet hold the object's address p.327
When an object is created, its constructor is ALWAYS called.
If you do not write one Java automatically provides one when the class is compiled.
default constructor - the constructor that Java provides if you don't write one. (it is a no-arg constructor)
Rectangle r = new Rectangle();
- It does not accept arguments.
- It sets all of the objects numeric fields to 0
- It sets all Booleans to false
- If the object has any fields that reference variables they are set to null.
no-arg constructor - a constructor that does not accept arguments p.328
public Rectangle()
{
length = 2.0;
width = 1.0;
}
Rectangle r = new Rectangle();
String class constructor - accepts a string literal as its argument which is used to initialize the String object
String name = new String("Joe Mahoney");
or for short
String name = "Joe Mahoney";
**** -
Two or more methods in a class may have the same name as long as their parameter lists are different.
Two or more constructors in a class may have the same name as long as their parameter lists are different.
Two methods have the same signature if they have the same name and argument types.
overloaded method - multiple methods in the same class have the same name but use different types of parameters - make classes more useful p.334
binding - the process of matching a method call with the correct method - used when an overloaded method is called - Java uses a methods signature to distinguish it from other methods of the same name
method's signature - the methods name and the data types of the method's parameters in the order that they appear. The method's return type is NOT part of the signature. p.334
Overloading Constructors - a class can have more than one constructor
- each version of the constructor must have a different parameter list
- as long as each constructor has a unique signature, the compiler can tell them apart
p.335
Any time you write a constructor for a class that accepts arguments
you should also write a no-arg constructor
if you want to be able to create instances of the class
without passing arguments to the constructor.
UML diagram with overloaded constructors p.336
BankAccount | class |
---|---|
fields | |
-balance :double | |
methods |
- BankAccount() | overloaded constructor
- BankAccount(startBalance :double) | overloaded constructor
- BankAccount(str :String) | overloaded constructor
- deposit(amount :double) :void | overloaded deposit method
- deposit(str :String) :void | overloaded deposit method
- withdraw(amount :double) :void | overloaded withdraw method
- withdraw(str :String) :void | overloaded withdraw method
- setBalance(b :double) :void | overloaded setBalance method
- setBalance(str :String) :void | overloaded setBalance method
- getBalance() :double |
p.342 Instance fields are visible to all of the class's instance methods.
An instance field can be accessed by any instance method in the same class as the field.
If an instance field is declared with the public access specifier, it can also be accessed by the code outside the class.
shadows - p.342 you cannot have 2 local variables or 2 parameters with the same name in the same scope but you can have a local variable or parameter value with the same name as a field BUT when you do this the local variable or parameter shadows or hides the name of the field. This can cause elusive bugs. IT IS BEST TO AVOID THIS even though it is acceptable.
p.344 The classes in the Java API are organized into packages. An import statement tells the compiler which package a class is located in.
- String class
- Scanner class
- JOptionPane class
- DecimalFormat class
- Random class
explicit import statement - identifies the package location of a single class import java.util.Scanner;
wildcard import statement -imports all the classes in a package import java.util.*;
The java.lang package is automatically imported into every Java program.
- java.applet - applet classes
- java.awt - window toolkit
- java.io - input / output
- java.lang - general classes for the Java language - automatically imported
- java.net - network communications
- java.security - security features
- java.sql - accessing databases using structured query language
- java.text - classes for formatting text
- java.util - utility classes
- javax.swing - classes for gui
-
written description of the problem
-
identify all the nouns, pronouns and noun phrases - each is a potential class
-
refine the list to include only the classes that are relevant to the problem
-
physical object
-
roles played by a person
-
result of an event
-
record keeping
-
the things a class is responsible for knowing
-
the actions a class is responsible for doing
problem domain - set of real world objects, parties, and major events related to the problem
- A class is a collection of programming statements that specify the fields and methods that a particular type of object may have.
- A class is analogous to a cookie cutter.
- An object is an instance.
- A field is a member of a class that holds data.
- New is a keyword that causes an object to be created in memory.
- An accessor method gets a value from a class's field but does not change it.
- A mutator method stores a value in a field or in some other way changes the value of a field.
- When the value of an item is dependent on other data, and that item is not updated when other data is changed, the value has become stale.
- A constructor method is automatically called when an instance of a class is created.
- When a local variable has the same name as the field, the local variable's name shadows the field's name.
- A default constructor is automatically provided for a class if you do not write one yourself.
- Two or more methods on a class may have the same name, as long as their parameter list is different.
- Binding is the process of matching a method call with the correct method.
- A class's responsibilities are the things the class knows(fields) and the actions the class performs (methods.)
- True. The occurrence of a string literal in a Java program causes a String object to be created in memory, initialized with the string literal.
- True. Each instance of a class has it's own instance fields.
- True. When you write a constructor class you are overwriting the default constructor.
- True. A class can have many constructors.
- True. To find the classes needed for an object-oriented application you identify all of the nouns in a description of the problem domain.
An array can hold multiple values of the same data type simultaneously. p.452
int[] numbers; This statement declares numbers in an array reference variable. Declaring an array reference DOES NOT create an array.
p.459 int[] days = {31, 28, 31, 30, 31, 30}; The values are stored in the array elements in the order they appear in the list.
p.460
Declares a reference variable
int[] numbers;
or int numbers[];
with multiple variables:
int[] numbers, codes, scores;
or
int numbers[], codes[], scores[];
this does not work because only numbers is a reference to an int array
int numbers[], codes, scores;
or
=====
Sooooo..
This declares a reference variable
int[] numbers;
or int numbers[];
Then creates an instance of an array:
numbers = new int[6];
=====
Declares a reference variable AND creates an instance of an array:
int[] numbers = new int[6];
=====
Declares a reference variable AND creates an instance of an array AND stores initial values in the array:
int[] numbers = {1,2,3,4,5}
=====
size declarator - the number inside the brackets - it indicates the number of elements or values the array can hold
-
must be a non-negative integer expression - it is common to use a final variable as a size declarator
float[] temp = new float[100];
char[] letters = new char[41];
long[] units = new long[50];
double[] sizes = new double[12];
final int NUMBERS = 6; int[] numbies = new int[NUMBERS];
subscript - the number assigned to each element of an array
Java initializes array elements with 0 by default.
The loop's control variable, index, is used as a subscript. p.457
hours[index] = keyboard.nextInt();
bounds checking - it does not allow a statement to use a subscript that is outside the range of valid subscipts for an array. Bounds checking occurs at run time.
off by one error - because the subscripts start counting at 0 and not one for 1-100 you would use 0-99
initialization list - the series of values inside the braces - the Java compiler determines the size of the array by the number of items in the list You DO NOT need to use the keyword new p.459
int[] numbers = {1,2,3,4,5}
Individual array elements are processed like any other type of variable
p.461
grossPay = hours[3] * payRate;
int[] score = {7,8,9,10,11};
++score[2]; // Pre-increment operation
score[4]++; // Post-increment operation
=====
When using increment and decrements operators, be careful not to use the operator on the subscript when you intend to use it on the array element.
The following statement decrements the variable count, but does NOTHING to the value stores in the array element amount[count]:
`amount[count--];
=====
p.463
**Array elements may also be used in relational expressions. For example, the following if statement determines whether cost
grossPay - hours[index] * payRate;
if (cost[20] < cost[0])
while (value[count] != 0)
{
Statements
}
Each array in Java has a public field named LENGTH. This field contains the number of elements in the array.
double[] temperatures = new double[25];
size = temperatures.length;
for (int i = o; < temperatures.length; i++)
System.out.println(temperatures[i]);
p.464 The enhanced for loop iterates once for every element of the array. Each time it iterates, it copies an array element to a variable.
for (dataType elementVariable : array)
statement;
-with the enhanced for loop you do not need to be concerned about the size of the array
- you don not need to create an "index" variable to hold subscripts
=====
you cannot use enhanced for loops if you need to
- change the contents of an array element
- work through the array elements in reverse order
- access some of the array elements but not all of them
- simultaneously work with two or more arrays within the loop
- refer to the subscript number of a particular element
=====
p.466&467
User Specify Array size
tests = new int[numTests];
for (int index = 0; index < tests.length; index++)
p.467
int[] numbers = new int[10];
numbers = new int[5];
You cannot copy an array by assigning one array reference variable to another
The code below looks like it is copying the array but it is just makes a copy of the address that is stores in array1 and stores it in array2. This is a reference copy.
int[] array1 = {2,4,6,8,20}
int[] array2 = array1;
To actually copy an array you need to copy the individual elements of one array to another. This is best done with a loop
int[] firstArray = {2,4,6,8,20}
int[] secondArray = new int[5];
for (int index = 0; index < firstArray.length; index++)
secondArray[index] = firstArray[index];
An array can be passed as an argument to a method. To pass an array, you pass the value that references the array.
When an entire array is passed into a method, it is passed just as an object is passed: the actual array itself is not passed, but ** a reference to the array** is passed into the parameter.
This means that the method has direct access to the original array. p.472
Methods can be written to:
- store values in an array
- display an arrays contents
- total all of an arrays elements
- calculate their average
p.470
public static void showArray(int[] array)
{
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
}
p.475/6
int[] firstArray = {2,4,6,8,20};
int[] secondArray = {2,4,6,8,20};
if(firstArray == secondArray)
System.out.println("The arrays are the same.");
else
System.out.println("The arrays are NOT the same.");
p.476
int[] units = new int[25];
int total = 0;
for (int index = 0; index < units.length; index++)
total += units[index];
p.476
double[] scores = new double[10];
double total = 0;
double average;
for (int index = 0; index < scores.length; index ++)
total += scores[index];
average = total / scores.length;
Notice that the last statement i not inside the loop. This statement should only execute once, after the loop has finished its iterations.
p.476/7
int[] numbers = new int[50];
int highest = numbers[0];
for (int index = 1; index > numbers.length; index++)
{
if (numbers[index] > highest)
highest = numbers[index];
}
int[] numbers = new int[50];
int lowest = numbers[0];
for (int index = 1; index < numbers.length; index++)
{
if (numbers[index] > lowest)
lowest = numbers[index];
}
p.485/7
p.487 In addition to accepting arrays as arguments, methods may also return arrays.
p. 489
An array of String objects may be created, but if the array is uninitialized, each String in the array must be creaed individually.
String[] names = {"Jen", "Lars', "Friendly", "Pikku"};
An array of String objects is really an array of references to String objects.
p.491
System.out.println(names[0].toUpperCase());
p.492
You may create arrays of objects that are instances of classes that you have written.
final int NUM_ACCOUNTS = 5;
BankAccount[] accounts = new BankAccount[NUM_ACCOUNTS];
for (int index = 0; index < accounts.length; index++)
accounts[index] = new BankAccount();
p.495
A search algorithm is a method of locating a specific item in a larger collection of data.
It is a simple technique for searching the contents of an array.
The sequential search algorithm uses a loop to sequentially step through an array starting with the first element.
It compares each element with the value being searched for and stops when the value is found OR the end of the array is encountered.
public class SearchArray
{
public static void main(String[] args)
{
int[] tests = {2,4,6,8,10};
int results;
results = sequentialSearch(test, 100);
if (results == -1)
{
System.out.println("Boo, you did not find the number you were looking for.");
}
else
{
System.out.println("Hooray, you found the number you were looking for.");
}
public static int sequentialSearch)int[] array, int value)
{
int index;
int element;
boolean found;
index = 0;
element = -1;
found = false;
while (!found && index < array.length)
{
if (array[index] == value)
{
found = true;
element = index;
}
index++;
}
return element;
}
}
Program Output: You earned 100 on test 4.
A two dimensional array is an array of arrays. It can be thought of as having rows and columns.
p.498
double[][] scores = new double[3][4];
The first size declarator specifies the number of rows and the second size declarator specifies the number of columns.
Each element in a two dimensional has two subscripts.
Programs that process 2-D array do so with nested loop. p. 500
When initializing a two dimensional array, you enclose each row's initialization list in its own set of braces.
int[][] numbers = { {1,2,3,4}, {2,4,6,8},{3,6,9,12} };
Length field for row and a length field for column.
A two dimensional array has multiple length fields.
public class Lengths
{
public static void main(String[] args)
{
int[][] numbers = { {1,2,3,4},
{2,4,6,8},
{3,6,9,12} };
System.out.println("The number of rows is " + numbers.length);
for (int index = 0; index < numbers.length; index++)
{
System.out.println("The number of columns in row " + index + " is " + numbers[index].length);
}
}
}
p.510
Java does not limit the number of dimensions that an array may have. It is possible to create arrays with multiple dimensions, to model data that occurs in multiple sets.
double[][][] seats = new double[3][5][8];
This array is three sets of five rows with each row containing eight elements.
A sorting algorithm is used to arrange data in to some order. A search algorithm is a method of locating a specific item in a larger collection of data. The selection sort and binary search are popular sorting algorithms.
A sorting algorithm is a technique for scanning through an array and rearranging its content in some specific order.
- The smallest value in the array is located and moved to element 0.
- The next smallest value is located and moved to element 1
- This process continue until all of the elements have been placed in their proper order.
The advantages of the sequential search array.
- simplicity
- easy to understand and implement
- doesn't require the data in the array to be stored in any particular order
Disadvantages.
-
it is inefficient
-
for an array of N items the sequential search will locate an item in N/2 attempts for (for 100 items it would take 50 attempts)
-
as the number of failed search attempts increases so does the average number of comparisons p.513
public static void selectionSort(int[] array) { int startScan, index, minIndex, minValue;
for (startScan = 0; startScan < array.length-1); startScan++) { minIndex = startScan; minValue = array[startScan]; for(index = startScan + 1; index < array.length; index++) { if (array[index] < minValue) { minValue = array[index]; minIndex = index; } } array[minIndex] = array[startScan]; array[startScan] = minValue; }
}
-
much more efficient than the sequential search algorithm
-
the values in the array must be sorted in ascending order
-
it searches from the middle
-
the value in the middle is either greater or less than the value being searched for
-
it cuts the array in half each time
-
it uses three variables to mark positions withing the array first, last and middle
public static int binarySearch(int[] array, int value) { int first; int last; int middle; boolean found;
first = 0; last = array.length - 1; position = -1; found = false; while (!found && first <= last) { middle = (first + last) / 2; if (array[middle] == value) { found = true; position = middle; } else if (array[middle] > value) last = middle - 1; else first = middle + 1; } return position;
}
p.516
public class CommandLine
{
public static void main(String[] args)
{
for (int index = 0; index < args.length; index++)
System.out.println(args[index]);
}
}
p. 518
**Variable length argument lists make it possible to write a method that takes a variable number of arguments.
varg parameter - the ellipsis that follows the data type int means that the parameter can take a variable number of arguments - varag parameters are arrays p. 518
public static int sum(int... numbers) { int total = 0; for (int val : numbers) total += val; return total; }
ArrayList is a class in the Java API that is similar to an array and allows you to store objects.
- Unlike an array, an ArrayList object's size is automatically adjusted to accomodate the number of items being stored in it.
- The last item stored in an ArrayList will have an index that is 1 less than the size of the ArrayList
- If you pass a value larger than than there are stored in the array to the get method an error will occur.
- Looping by the size method in the for loop prevents a bound checking error from occuring
Advantages over other arrays
-
An ArrayList object automatically expands as items are added to it
-
In addition to adding items to an ArrayList, you can remove items as well
-
An ArrayList object automatically shrinks as items are removed from it
import java.util.ArrayList;
ArrayList<String> nameList = new ArrayList<String>();
size method - the ArrayList's size method show the size of the ArrayList
use it to control the number of times a loop iterates
import java.util.ArrayList;
public class ArrayListDemo
{
public staic void main(String[] args)
{
ArrayList<String> nameList = new ArrayList<String>();
nameList.add("James");
nameList.add("James");
nameList.add("James");
System.out.println("The ArrayList has " + **nameList.size**() +
" object stored in it.");
for (int index = 0; index < **nameList.size**(); index++)
System.out.println(nameList.get(index));
}
}
=====
You can also use the enhanced for loop p.523
for (String name : nameList)
System.out.println(name);
=====
Both return:
The ArrayList has 3 objects stored in it.
James
Catherine
Bill
The ArrayList class has a toSring method that returns a string representing all of the items stored in an ArrayList object. p.524
System.out.println(nameList);
returns: [James, Catherine, Bill]
The ArrayList class has a remove method that removes an item at a specific index. You pass the index as an argument to the method. p.524
In the code below, nameList.remove(1); when the item at index 1 was removed, the item that was previously stored at index 2 was shifted in position to index 1.
When an item is removed from an ArrayList, the items that come after it are shifted downward in position to fill the empty space.
An error will occur if you call the remove method with an invalid index.
=====
import java.util.ArrayList;
public class ArrayListDemoRemoveItem
{
public staic void main(String[] args)
{
ArrayList<String> nameList = new ArrayList<String>();
nameList.add("James");
nameList.add("James");
nameList.add("James");
for (int index = 0; index < nameList.size(); index++)
{
System.out.println("Index: " + index + " Name: " +
nameList.get(index));
}
**nameList.remove(1);**
System.out.println("The item at index 1 is removed. " +
"Here are the items now.");
for (int index = 0; index < nameList.size(); index++)
{
System.out.println("Index: " + index + " Name: " +
nameList.get(index));
}
}
}
=====
p.526
**nameList.add(1, Mary);**
p.527 An ArrayLists size is the number of items stored in the in the ArrayList object.
An ArrayLists capacity is the number of items it can store without having to increase its size.
When an an ArrayList object is first created, using the no-arg constructor, it has an initial capacity of 10 items. When the eleventh item is added, the ArrayList object must increase its size. To avoid this you can specify a starting capacity by apssing an int argument to the ArrayList constructor.
ArrayList<String> list = new ArrayList<String>(100);
an ArrayList can hold any type of object
import java.util.ArrayList;
public class ArrayListCapacity
{
public static void main(String[] args)
{
ArrayList<BankAccount> accountlist = new ArrayList<BankAccount>();
list.add(new BankAccount(100.0));
list.add(new BankAccount(500.0));
list.add(new BankAccount(1500.0));
for (int index = 0; index < list.size(); index++)
{
BankAccount account = list.get(index);
System.out.println("Account at index " + index +
"\nBalance: " + account.getBalance());
}
}
}
Errors to Avoid p.528
- Using an invalid subscript.
- Confusing the contents of an integer array element with the element's subscript.
- Causing an off-by-one error.
- Using the = operator to copy an array.
- Using the == operator to compare two arrays.
- Reversing the row and column subscripts when processinga two-dimensional array.
**** -
**** -
**** -
- In an array declaration the size declarator indicates the number of elements that the array will have.
- Each element of an array is accessed by a number known as a subscript.
- The first subscript in an array is always 0.
- The last subscript in an array is always one less than the number of elements.
- Array bounds checking happens at run time.
- The array field length holds the number of elements that the array has.
- The sequential search algorithm steps through an array, comparing each item with the search value.
- The binary search algorithm repeatedly divides the portion of an array being searched in half.
- N/2 is the typical number of comparisons performed by the sequential search on an array of N elements (assuming the search values are consistently found).
- When initializing a two-dimensional array, you enclose each row's initialization list in braces. p. 502
- To insert an item at a specific location in an ArrayList object, you use the add method.
- To delete an item from an ArrayList object, you use the remove method.
- To determine the number of items stored in an ArrayList object, you use the size method.
- Java does not allow a statement to use a subscript that is outside the range of valid subscripts for an array.
- An array's size declarator CANNOT be a negative integer expression.
- Both of the following declarations are legal and equivalent:
int[] numbers;
int numbers[];
p.460 - The subscript of the last element in a single-dimensional array is one less than the total number of elements in the array.
- The values in an initialization list are stored in the array in the order that they appear in the list.
- The Java compiler does not display an error message when it processes a statement that uses an invalid subscript. It throws an exception and terminates. Exception - InvalidSubscript p.457
- When an array is passed to a method, the method has access to the original array.
- The first size declarator on the declaration of a two dimensional array represents the number of rows. The second size declarator represents the number of columns.
- A two dimensional array has multiple length fields.
- ArrayList automatically expands in size to accommodate the items stored in it.
https://quizlet.com/31200207/bcis-3630-exam-2-flash-cards/
p.593
Java API Documentation Java API Common packages, classes, and interfaces
UML static or structural view: Class Diagram
p.540 A static class member belongs to the class, not objects instantiated from the class.
Q. Difference between an instance field and a static field: p.545
A. p.540
instance field and instance classes are associated with specific instances of a class and cannot be used until and instance of the class is created.
Static field or methods It is possible to create a field or method that does not belong to any instance of a class.
Q. What action is possible with a static method that isn't possible with an instance method? A. they can be called directly from the class as needed without creating a new instance of the class
Q. Describe the limitations of static methods A. - limitations - they CANNOT refer to non-static members of the class.
- Any method called from a static method must also be static
- if the method uses any of the class's fields they must be static as well
When a field is declared with the keyword static, there will be only one copy of the field in memory, regardless of the number of instances of the class that might exist. The single copy is shared by all instances of the class. Static fields and methods do not belong to any instance of a class.
Java automatically stores 0 in all uninitialized static member variable.
public class Countable { private static in instanceCount = 0; public Countable() { instanceCount++; } public int getInstanceCount() { return instanceCount; } }
Static methods - p.543 When a class contains a static method it isn't necessary for an instance of the class to be created in order to execute the method.
-
they can be called directly from the class as needed
-
they are most often used to create utility classes that perform operations on data but have no need to collect and store data.
-
limitations - they CANNOT refer to non-static members of the class.
-
Any method called from a static method must also be static
-
if the method uses any of the class's fields they must be static as well
public class metric { public static double milesToKilometers(double m) { return m * 1.609; }
public static double kilometerrsToMiles(double k) { return k / 1.609; }
}
kilometers = Metric.milesToKilometers(10.0);
p.549
Passed by value - when a varaible is passed as an argument to a method.
When the method changes the contents of the parameter variable it does not affect the contents of the original variable that was passed as an argument.
When a reference variable is passed as an argument to a method, the method has access to the object that the variable references.
When writing a method that receives the value of a reference variable as an argument you must take care not to accidentally modify the contents of the object that is referenceing the variable.
p.549
A method can return a reference to an object.
account = getAccount();
return new BankAccount(balance);
the toString method returns a string that represents the state of an object. Most classes can benefit from having a method named toString, which is implicitly called under certain circumstances.
Used to display an object's state which is the data that is stored in the object's fields at any given moment. p.551
Every class automatically has a toString method that returns a string containing the object's class name followed by the @ symbol, followed by an integer that is usually based on the object's memory address.
p.556
You cannot determine whether two objects contain the same data by comparing them with the == operator. Instead, the class must have a method such as equals for comparing the contents of the objects.
- A static method cannot access any non-static member variables in its own class.
- When an object is passed as an argument to a method, an reference to the object is actually passed.
- If you write this method for a class, Java will automatically call it any time you concatenate an object of the class with a string.
- Making an instance of one class a field in another class is called aggregation.
- b This This is the name of a reference variable that is always available to an instance method and refers to the object that is calling the method. b
- The ordinal, enum method returns the position of an enum constant in the declaration.
- d. ssuming the following declaration exists: enum Seasons { SPRING<WINTER, SUMMER, FALL } What is the fully qualified name of the FALL constant?
- You cannot use the fully qualified name of an enum constant for this.
- The Java Virtual Machine periodically performs this process, which automatically removes unreferenced objects from memory.
- If a class has this method, it is called automatically just before an instance of the class is destroyed by the Java Virtual Machine.
- CRC stands for
- TorF A static member method may refer to non-static member variables of the same class, but only after an instance of the class has been defined.
- TorF All static member variables are initialized to -1 by default.
- True When an object is passed as an argument to a method, the method can access the argument.
- TorF A method cannot return a reference to an object.
- TorF You can declare an enumerated data types inside a method.
- TorF Enumerated data types are actually special types of classes
- TorF enum constants have a toString method.
- In an inheritance relationship, this is the general class.
- In an inheritance relationship, this is the specialized class.
- This key word indicates that a class inherits from another class.
- A subclass does not have access to these superclass members.
- This key word refers to an object's superclass.
- In a subclass constructors, a call to the superclass constructor mst
- The following is an explicit call to the superclass's default constructor.
- A method in a subclass that has the same signature as a methodin the superclass is an example of
- A method in a subclass having the same name as a method in the superclass but a different signature is an example of
- These superclass members are accessible to subclasses and classes in the same package.
- All classes direwctly or indirectly inherit from this c;ass
- With this type of binding the Java Virtual Machine determines at runtime which method to call, depending on the type of the object that a variable references.
- This operator can be used to determine whether a reference variable references an object of a particular class
- When a class implements an inference, it must
- Fields inan intereface are
- Abstract methods must be
- Abstract classes cannot
- TorF Constructors are not inherited.
- TorF In a subclass, a call to the superclass constructor can only be written in the subclass constructor.
- TorF If a subclass constructor does not explicity call a superclass constructor, JAva will not call any of the superclass's constructors.
- TorF An object of a superclass can access members declared in a subclass.
- TorF The superclass constructor always executes before the subclass constructor.
- TorF When a method is declared with the final modifier, it must be over-ridden in a subclass.
- TorF A superclass has a member with package access. A class that is outside the superclass's package but inherits from the superclass can access the member.
- TorF A superclass reference variable can reference an object of subclass that extends the superclass
- TorF A subclass reference variable can reference an object of the superclass
- TorF When a class contains an abstact method, the class cannot be instantiated
- TorF A class may only implement one interface
- TorF By default all members of an interface are public