Programming Fundamentals Unit 4

Ace your homework & exams now with Quizwiz!

Java automatically creates the array and fills its elements with the initialization values

-row 0 {1, 2, 3} -row 1 {4, 5, 6} -row 2{7, 8, 9}

More than two dimension

Java does not limit the number of dimensions that array may be. More than three dimensions is hard to visualize but can be useful in some programming problems.

Array indexes always start

at zero and continue to (array length -1)

Superclass

general class also called base classes

An array is a

list of data elements

A class becomes abstract when you place the abstract keyword in the class definition

public abstract class ClassName

diamond operator

you are no longer required to write the data type in the part of the statement that calls the ArrayList constructor. Instead, you can simply write a set of empty angled brackets ArrayList<String> list = new ArrayList<>();

Members of the superclass that are marked public:

-are inherited by the subclass, and may be directly accessed from the subclass

Returning an Array Reference

A method can return a reference to an array. The return type of the method must be declared as an array of the right type public static double[] getArray() { double[] array = { 1.2, 2.3, 4.5, 6.7, 8.9 }; return array; } The getArray method is a public static method that returns an array of doubles.

equals method

Determines whether two different String objects contain the same string with the used of ==

Arrays are objects and provide a public field named length that is constant and can be tested.

Double[] temperatures = new double [25]The length of this array is 25

Selection Sort

A sort algorithm that repeatedly scans for the smallest item in the list and swaps it with the element at the current index. The index is then incremented, and the process repeats until the last two elements are sorted.

array initialization list

A technique for creating an array and assigning it some initial values. When relatively few items need to be initialized, an initialization list can be used to initialize the array int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};The numbers in the list are stored in the array in order:-days[0] is assigned 31, -days[1] is assigned 28, -days[2] is assigned 31, -days[3] is assigned 30, -etc.

The length field in a two-dimensional array

A two-dimensional array, however, has multiple length fields. It has a length field that holds the number of rows, and then each row has a length field that holds the number of columns Each row has a length constant tells how many columns is in that row Each row can have a different number of columns

You cannot copy an array by merely assigning one reference variable to another. You need to copy the individual elements of one array to another.

Ex: int[] firstArray = {5, 10, 15, 20, 25 }; int[] secondArray = new int[5]; for (int i = 0; i < firstArray.length; i++) secondArray[i] = firstArray[i]; This code copious each element of fristArray to the corresponding element of secondArray

A class can be derived from only one superclass but

Java allows a class to implement multiple interfaces.

Polymorphism with Interfaces

Java allows you to create reference variables of an interface type. An interface reference variable can reference any object that implements that interface, regardless of its class type. This is another example of polymorphism. You cannot create an instance of an interface

Returning objects from methods

Methods are not limited to returning the primitive data types. Methods can return references to objects as well. Just as with passing arguments, a copy of the object is not returned, only its address. See example: ReturnObject.java Method return type: public static BankAccount getAccount() { ... return new BankAccount(balance); }

Abstract Methods

Methods that have only a method header and will be written in another file. It is a method that appears in a supercalss but expects to be overridden in a subclass. If a subclass fails to override an abstract method, a compiler error will result.

The ArrayList Class

Similar to an array, an ArrayList allows object storage Unlike an array, an Arraylist object it Automatically expands when a new item is added and Automatically shrinks when items are removed Requires: import java.util.ArrayList You can store any type of object in an ArrayList

enhanced for loop

Simplified array processing (read only), it always goes through all elements General format: for(datatype elementVariable : array) Statement;

Copy constructors

Special constructor used when a newly created object is initialized to the data of another object of same class

The ArrayList class's toString method returns a string representing all items in the ArrayList:

System.out.println(nameList); This statement yields: [ James, Catherine]

string Array: Instantiation

If an initialization list is not provided, the new keyword must be used to create the array: String[] myArr = new String[numberOfItems]; String[] myArr = {"a","b","c"};

garbage collection

automatic reclamation of memory occupied by objects that are no longer referenced. Java handles all the memory operations for you, simply set the reference to null and Java will reclaim the memory.

Preventing a method from being overridden

The final modifier will prevent the overriding of a superclass method in a subclass. If a subclass attempts to override a final method, the compiler generates an error. This ensures that a particular superclass method is used by subclasses rather than a modified version of it. (public final void message () )

lambda expression

can be used to create an object that implements interface and overrides its abstract method.

A search algorithm is a

method of locating specific item in a large collection of data

'Is a' relationship

The relationship between a superclass and an inherited class

interface inheritance

The relationship between the class and the interface.

Superclass's Constructor

The super keyword refers to an object's superclass. The superclass constructor can be explicitly called from the subclass by using the super keyword

Passing and Returning Two-Dimensional Array References

There is no difference between passing a single or two-dimensional array as an argument to a method. The method must accept a two-dimensional array as a parameter

protected members

These members may be directly accessed by methods of the same class or methods of the subclass or same package. Not quite private because the members can be accessed outside the package but not quite public because access is restricted to methods in the same package, subclass, classes etc.

Array elements can be treated as any other variable

They are simply accessed by the same name and a subscript

The ArrayList's class add method with one argument adds new items to the end of ArrayList.

To insert items at a location of choice used the add method with two arguments: nameList.add(1, "Mary");

When a class contains a static method, it is not necessary to create

n instance of the class in order to use the method

To access items in an ArrayList, use the get method:

nameList.get(1); In this statement 1 is the index of the item to get

The ArrayList class's remove method removes designated item from the ArrayList:

nameList.remove(1);

To replace an existing item, use the set method in a arraylist:

nameList.set(1, Becky");

To get the current size call the size method of a array list

nameList.size();

String objects have several methods including

oUpperCase compareTo Equals charAt

dynamic binding

or late binding it is performed when a variable contains a polymorphic reference. The JVM determines at runtime which method to call, depending on the type of object that the variable references.It is the object's type rather than the reference type that determines which method is called.

Both overloading and overriding can take place in an inheritance relationship but

overriding can only take place in an inheritance relationship.

In Java 8, Functional interface and lambda Expressions work together to simplify code,

particularly in situations where you might use anonymous inner classes.

More often you will want to write methods to process array data by

passing the entire array not just one element at a time

An array is accessed by:

the reference name a subscript that identifies which element in the array to access.

All objects have a toString method that returns the class name and a hash of the memory address of the object

We can override the default method with our own to print out more useful information.

Interfaces

similar to an abstract class that has all abstract methods but it cannot be instantiated and all of the methods listed in an interface must be written elsewhere. The purpose of this is to specify the behavior for other classes. It is often said that it is like a 'contract' and when a class implements it the class must adhere to the contract.

this reference

simply a name that an object can use to refer to itself. It can be used to overcome shadowing and allow parameters to have the same name as an instance field and can be used to call a constructor from another constructor. Elaborate constructor chaining can be created using this technique. If this is used in a constructor it must be the first statement in the constructor

Polymorphism

the ability to take many forms, in Java, a reference variable is this because it can reference objects of types different from its own as long as those types are subclasses of its type. A reference variable can reference objects of classes that are derived from the variable's class, but you cannot assign a superclass object to a subclass reference variable

To invoke a static method or use a static field

the class name, rather than the instance name is used.

To display the length of each string held in a String array:

for (int i = 0; i < names.length; i++) System.out.println(names[i].length());

toString method

formats a number stored in a numeric variable and then returns the result as a string. Does not have to be called explicitly but is called implicitly

Abstract methods are used to ensure

hat a subclass implements the method

If the object of the subclass had overridden a method in the superclass:

if the variable makes a call to that method the subclass's version of the method will be run

References can be tested to see if they point to null prior to being used:

if(name != null) { System.out.println("Name is: " + name.toUpperCase()); }

You can let the user specify the size of an array

int numTests; int[] tests; Scanner keyboard = new Scanner(System.in); System.out.print("How many tests do you have? "); numTests = keyboard.nextInt(); tests = new int[numTests];

two-dimensional array

is an array of arrays, it can be thought of as having rows and columns.

Anonymous Inner classes:

is an inner class that has no name, it must implement an interface or extend another class. It is useful when you need a class that is simple and to be instantiated only once in your code.

Default methods

is an interface method that has a body. You can add new methods to an existing interface without causing errors in the classes that already implement the interface.

Java keyword extends

is used on the class header to define the subclass.

When a single element of an array is passed to a method

it is handled like any other variable.

When a class implements multiple interfaces,

it must provide the methods specified by all of them. To specify multiple interfaces in a class definition, simply list the names of the interfaces, separated by commas and after the implement key word. public class MyClass implements Interface1, Interface2, Interface3

Avoid returning references to private data elements

it will allow any object that receives the reference to modify the variable

If a parameterized constructor is denied in the superclass:

the superclass must provide a no-arg constructor, or subclasses must provide a constructor, and subclasses must call a superclass constructor.

Ragged Arrays

When the rows of a two-dimensional array are of different lengths, - You create a ragged array by first creating a two-dimensional array with a specific number of rows, but no columns.

Creating Arrays

When you declare an array in Java the array variable does not allocate any space in memory for the array. It only creates a storage location for the reference to the array. If a variable does not contain a reference to the array the variable is null. You can not assign elements to an array unless it has already been declared. data_type var_name[size]; ex. int A[4]

null reference

a reference that does not refer to any object. If it is null then no operations will be perform

Binary Search

a search algorithm that starts at the middle of a sorted set of numbers and removes half of the data; this process repeats until the desired value is found or all elements have been eliminated.

An interface can contain field declarations

all fields in an interface are treated as final and static. Because they automatically become final, you must provide an initialization value.

Off-by-one errors in loops are ____ errors.

logic It is very easy to be off-by-one when accessing arrays. It would throw an ArrayIndecOutOfBoundsException

Protected:

an access specification that causes the member;s accesses to be somewhere between private and public.

Once created, an array size is

an array size if fixed and cannot be changed

Using protected instead of private makes some tasks easier, however

any class that is derived from the class or is in the same package has unrestricted access to the protected member. So it is always better to make all fields private and then provide public methods for accessing those fields.

If no access specifier for a class member is provided the class member is given package access by default with

any method in the same package that may access the member.

Members of the superclass are marked private:

are not inherited by the subclass, exist in memory when the object of the subclass is created may only be accessed from the subclass by public methods of the superclass

class collaboration

two classes that interact with each other If an object is collaborating with another object it must know something about the second object's methods and how to call them.

Variable-length argument lists

variable-length argument lists, which makes it possible to write a method that takes a variable number of arguments. it use the paramter varag... Vararg parameters are actually arrays

Overriding Superclass Methods

write method with the same name in the class need to use an accessor method because variable is private. Since, you don't have knowledge of the instance name used this.getFullName(); The keyboard this always refers to the current instance of an object

Comparing Arrays

- To compare the contents of two arrays, you must compare the elements of the two arrays. // First determine whether the arrays are the same size. if (firstArray.length != secondArray.length) arraysEqual = false; // Next determine whether the elements contain the same data. while (arraysEqual && index < firstArray.length) { if (firstArray[index] != secondArray[index]) arraysEqual = false; index++; } if (arraysEqual) System.out.println("The arrays are equal."); else System.out.println("The arrays are not equal.");

Abstract Classes

A class that cannot be instantiated (can't use new on it). It can only be extended and is used to define base classes. It represents the generic or abstract form of all classes that are derived from it.

Specialized objects have:

All of the characteristics of the general object, plus additional characteristics that make it special

Reassigning Array References

An array reference can be assigned to another array of the same type.

The length Field & The length Method(2)

An array's length is a field. You do not write a set of parentheses after its name A String's length is a method. You do write the parentheses after the name of the String class's length method

Arrays of Objects

Because Strings are objects, we know that arrays can contain objects. But each element needs to be initialized

To designate a different capacity for a ArrayList use a parameterized constructor:

ArrayList<String> list = new ArrayList<String>(100);

Creating an ArrayList

ArrayList<String> nameList = new ArrayList<String>();

Passing Arrays as Arguments

Arrays are objects. Their references can be passed to methods like any other object reference variable

The length Field & The length Method

Arrays have a final field named length String objects have a method name length

CRC cards

Class, responsibility, collaboration cards. A design tool for classes that lists a class's name, its responsibilities and the classes with which it collaborates on an index card.

object aggregation

Creating an instance of one class as a reference in another class is called __________; creates a "has a" relationship between objects

Calling String Methods on Array Elements

Each element of a String array is a String object Methods can be used by using the array name and index before System.out.println(names[0].toUpperCase()); char letter = names[3].charAt(0);

a chain of inheritance

If ClassC is derived from ClassB which is derived from ClassA, this would be an example of ________. A superclass can also be derived from another class. Classes often are depicted graphically in class hierarchy which shows the inheritance relationships between classes

Inheritance

In object-oriented programming it is used to create an 'is a' relationship among classes

The length of an array can be obtained via its length constant

Int size = temperatures.length;The variable size will content 25

It is possible to declare an array reference and create it in the same statement

Int[] numbers = new int[6];

Multiple arrays can be declared on the same line

Int[] numbers, codes, scores With the alternate notation each variable must have bracketsInt numbers[], codes[], scores; The scores variable in this instance is simply an int variable

finalize method

It is a method that is called by the garbage collector before deletion/destroying the object which is eligible for garbage collection, so it can perform clean-up activities. This means closing the resources associated with that object like Database Connection, Network Connection or we can say resource de-allocation. It will run just prior to the garbage collector reclaiming its memory.

The length field of the array gives ___

Number of rows in the array

Passing Objects as Arguments

Objects can be passed to methods as arguments. Java passes all arguments by value. When an object is passed as an argument, the value of the reference variable is passed. The value of the reference variable is an address or reference to the object in memory. A copy of the object is not passed, just a pointer to the object. When a method receives a reference variable as an argument, it is possible for the method to modify the contents of the object referenced by the variable.

There is a distinction between overloading a method and overriding a method

Overloading is when a method has the same name as one or more other methods, but with a different signature. When a method overrides another method, however, they both have the same signature.

Polymorphism and Dynamic Binding

Polymorphism: the same message can have different meanings Dynamic binding: type of object is not determined until run-time Contrast with static binding

Processing data in an array is the same as any other variable

Pre and post increment works the same Array elements can be used in relational operations Arrays can be used as loop conditions

Class fields are declared using the static keyword between the access specifier and the field type

Private static int instancecount = 0; The field is initialized to 0 only once, regardless of the number of times the class is instantiated

There are two ways to copy an object (You cannot use the assignment operator to copy reference types)

Reference only copy: This is simply copying the address of an object into another reference variable Deep copy (correct) : this involves creating a new instance of the class and copying the values from one object into the new object.

The sequential search algorithm uses a loop to

Sequentially step through an array Compare each element with the search value and stop when the value is found or the end of the array is encountered

Typically, if the amount of data that an array must hold is unknow

Size the array to the largest expectation number of elements or Use a counting variable to keep track of how many valid data is in the array

Object class

The name of the Java class that is the "mother" of all objects. All other Java class automatically inherit the Object class as the top-level parent class in the hierarchy. This class provides basic methods such as the toString, hashCode, and equals methods.

Array size Loops

The length constant can be used in loop to provide automatic bounding

Any class that does not specify the extended keyword is automatically derived form the Object class.

Ultimately, every class is derived from the Object class.

Initializing a two-dimensional array

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, 5, 6}, {7, 8, 9} };

Accessing Two dimensional Array Elements

When processing the data in a two-dimensional array, each element has two subcripts One for its row another for its column Programs that process two-dimensional arrays can do so with nested loops to fill the scored array

Garbage collector

a Java component that reclaims de-referenced handles.

Inner class:

a class that defined inside another class

Arrays allow us to create

a collection of like values that are indexed because primitive variables are designed to hold only one value at a time. can store any type of data but only one type of data at a time

Static methods are convenient

because they may be called at the class level. They are typically used to create utility classes, such as Math class in the Java Standard Library

The subclass inherits fields and methods from the superclass without any of them

being rewritten with new fields and methods may be added to the subclass.

Static fields and static methods do not

belong to a single instance of a class

Reading the contents of a file into an array

final int SIZE = 5; // Assuming we know the size. int[] numbers = new int[SIZE]; int i = 0; File file = new File ("Values.txt"); Scanner inputFile = new Scanner(file); while (inputFile.hasNext() && i < numbers.length) { numbers[i] = inputFile.nextInt(); i++; } inputFile.close();

Arrays may be of any type

float[] temperatures = new float[100]; char[] letters = new char[41]; long[] units = new long[50]; double[] sizes = new double[1200];

Methods can also be declared static by placing the static keyword between

he access modifier and the return type of the method. P ublic static double milesToKilometers (double miles) (...)

An ArrayList has capacity which is the number of items it can hold without

increasing it size with the default capacity of an ArrayList is 10 items

@Override annotation

indicates that a method should override a superclass method with the same signature if it does not a compilation error occurs

Instance methods typically interact with

instance fields or calculate values based on those fields

This is not the way to copy an array:

int[] array1 = { 2, 4, 6, 8, 10 }; int[] array2 = array1; // This does not copy array1.

Saving the contents of an array to a file

int[] numbers = {10, 20, 30, 40, 50}; PrintWriter outputFile = new PrintWriter ("Values.txt"); for (int i = 0; i < numbers.length; i++) outputFile.println(numbers[i]); outputFile.close();

Functional interface:

is a interface that has one abstract method

Primitive static fields are initialized to 0 if

no initialization is performed

The array size must be a

non-negative number and it may be a literal value, constant, or variable.

Static methods may not communicate with instance fields

only static fields.

When an interface variable references an object

only the methods declared in the interface are available and explicit type casting is required to access the other methods of an object referenced by an interface reference.

If a class implements an interface it used the implements keyword in the class header:

public class FinalExam3 extends GradedActivity implements Relatable

Declaring a two dimensional array

requires two sets of brackets and two size declarations First one is for the number of rows Second is for the number of columns The two sets of brackets in the data type indicate that the scores variable will reference a two-dimensional array Notice that each size declarator is enclosed in its own set of brackets

Subclass:

specialized class also called derived classes is base on or extended from the superclass

Instance methods require

that an instance of a class be created in order to be used

An interface looks similar to a class except...

the keyword interface is used instead of the keyword class and the methods that are specified in an interface have no bodies only headers that are terminated by semicolons.

When an instance of the subclass is created

the non-private methods of the superclass are available through the subclass object

to populate the ArrayList,

use the add method nameList.add("James"); nameList.add("Catherine");

calling a superclass constructor

use the super keyword in the first statement of the subclass constructor super(initialBalance)

Enumerated types

used to define variables that can only assign certain discrete integer values Know as an enum it requires declaration and definition like a class. It is a specialized class Syntax: enum typeName { one or more enum constants }

Array subscripts can be accessed

using variables (such as for loop counters)

command line arguments

values entered by a user when running a program from a command line The main method has a header that look like this: public static void main(String[] args) The main method receives a string array as a parameter. The array that is passed into the argos parameter comes from the operating system command-line It is not required that the name of main's parameter array be argos

Constructors are not inherited.

when a subclass is instantiated the superclass default constructor is executed first


Related study sets

BA 396 - Foundations of Marketing Research

View Set

1/15 completed Exam: Therapist Development Center

View Set

Unit 1 Vocabulary (IM 6th Grade)

View Set

Prelab 3: The Upper Appendicular Skeleton and Associated Muscles

View Set

HIT 205 - International Classification of Diseases Diagnosis Coding II With Lab

View Set