• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/127

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

127 Cards in this Set

  • Front
  • Back

Selection sort

Algorithm that finds the smallest Item and put it into location 0, then finds the next smallest and places it into the 1 index. and so forth

Inner Class

a class that is declared within another class


Every Java object has a pseudo-instance variable called ______ which is a refrence back to that same object

.this


______ implicitly converts back and forth between primitive types and there _______ classes.

Autoboxing, Wrapper classes

If JButton is clicked a ___________ is generated which then passed to a ____________ is linked to the JButton

Action Event and Action Listener

Name the layout managers in Java

Flow Layout, GridLayout, BorderLayout, GridbagLayout

Shallow Copy

if a copy constuctor for a class makes a bitwise copy of all of the instance variables it is making a Shallow copy


Binary Sort and its Function

the amount of guesses it will take to find the value (Worst Case Scenario) is : logBase2(N) (Log N)


where N is the number of Items.


for this code to work the Array must be sorted in from Least to Great or Vice Verse.


The Code find the middle and compares that value. so if it is greater it will never search less.

We can arrange graphical components differently in different parts of our JFrame by putting them into ____ objects, since each ________ has its own Layout Manager

JPanel, JPanel

T/F


The binary The binary search
algorithm requires the array being searched to be sorted.

TRUE

row major order

The first index gives us a "row", which is an array of items

data abstraction

We don’t need to know the internal data representation
We don’t need to know the method implementation


how the ArrayList is implemented

Data is maintained in two parts:
an array to actually store the information
an int to keep track of the number of elements being stored


Most of our operations are concerned with the logical size of the array

Number of actual elements being stored

The physical size of the array is

abstracted out of our view

The physical size of the array is abstracted out of our view meaning......

This changes as necessary but we never need to know what it actually is in order to use the ArrayList
Remember previous discussion on resizing

A is sorted in ascending order if

A[i] < A[j] for all i < j

A is sorted in descending order if

A[i] > A[j] for all i < j

Some algorithms are better than others
The most useful measure of “better” here

is how long it takes to run
The better algorithms run a lot more quickly than the poorer algorithms

SelectionSort

SelectionSort is very intuitive:
Find the smallest item and swap it into index 0
Find the next smallest item and swap it into index 1
Find the next smallest item and swap it into index 2…
Find the next smallest item and swap it into index N-2

InsertionSort

unlike the other sorts, passes through the array only once. The insertion sort is commonly compared to organizing a handful of playing cards. You pick up the random cards one at a time. As you pick up each card, you insert it into its correct position in your hand of organized cards.

Sequential Search

Start at the beginning of the array and check each item in sequence until the end of the array is reached or the item is found

One stops the loop with failure (get to end)
The other stops the loop with success
If the data is unsorted, we cant do any better


linear run-time

time proportional to N, the number of items in the array

Idea of Binary Search:

Searching for a given key, K
Guess middle item, A[mid] in array
If A[mid] == K, we found it and are done
If A[mid] < K then K must be on right side of the array. If A[mid] > K then K must be on left side of the array. Either way, we eliminate ~1/2 of the remaining items with one guess


associated with the class itself rather than individual objects.Can be accessed through the class using ClassName.variableName or through the objects using variableName from within an object objectName.variableName from outside an object. access from class or frm outsde of object,data must be public.


Static Variables

When should I use a variable and when should I use a method?

Variables should be used to store the basic properties of an object
Can be changed through mutators but should not become "obsolete."Methods should be used to calculate / determine values using variables. We don't want to waste time calculating something that is set. However, if a value may change over time, it should be calc'ed

Copying objects

In Java there are two primary ways of doing this:
Using a “copy constructor” for the class


Using the “clone” method for a class

copy constructor

This method takes an argument of the same class type and makes a copy of the object
Ex: String newString = new String(oldString);

“clone” method

This allows an object to “make a copy of itself.”


defer it to CS 0445

Assign each instance variable in the old object to the corresponding instance variable in the new object
If the instance variables are themselves references to objects, those objects will be shared
See ex12b.java and Scores.java

Shallow Copy

Copy primitive types normally
For reference types, do not assign the reference; rather “follow the reference” and copy that object as well
Note that this process could proceed through many levels
See ex12b.java and Scores.java

Deep Copy


Often in instance methods you are accessing both instance variables and method variables
If a method variable has the same name as an instance variable, updates will change the method variable, NOT the instance variable.


It allows disambiguation between instance variables and method variables

The this. reference

When a reference to an object is reassigned, the original object can no longer be accessed through that reference
If there is no other reference to that object, then it cannot be accessed, period
In this case the object has become ...

Garbage Collection

Graphical output and use of a mouse and other graphical components for input

Graphical interfaces

The AWT

(Abstract Windowing Toolkit)


first versions of Java
Created components such as Frame, Panel, Button, TextField, Label
AWT varied on different windowing systems
AWT Java program looks different when run on MS Windows machines, MACs and Sun
because the differ underlying windowing systm

more consistent in its look and feel across all platforms.


It also adds some extra features that did not exist in the AWT
components are similar to AWT in name, but with a “J” in front
Ex: JFrame, JPanel, JButton, JTextField, JLabel

Swing

Set of graphics and media packages that enables developers to design, create, test, debug and deploy rich client applications that operate consistently across diverse platforms

JavaFX

objects that will be the windows in graphical applications
We can draw/paint graphics within them

JFrames

bjects that will be the windows in graphical applications within the context of another program (i.e. a Web browser)

JApplets

simple components to show formatted text on the display
We can set the font type, size and color
We can set and change the text itself as desired throughout program execution

JLabels

simple components that can also show text on the display in addition
they also respond to clicks of the mouse

JButtons

If a user clicks the mouse within a JButton, an _______ object is generated in response
This object is passed automatically to an________
object

ActionEvent, ActionListener

The ActionListener must be registered to _______ to the JButton

listen

ActionListener is actually an

interface with the single method actionPerformed().


Any class that implements actionPerformed() can be an ActionListener


like ControlListener you used in Assig4


causing the actionPerformed method within the ActionListener to execute

It is the actionPerformed method that is doing the actual response to the button click
This idea is called

event-driven programming



Programmer writes code to respond to the various events that may occur

The basic idea for the different types of events...

Triggered object generates an event object
Event object is passed to event listener object
Method in the event listener executes to handle the event
It is important that event handlers are linked to the appropriate event generators
Otherwise event will still be generated but will not be responded to

If we want to have multiple components, we need to determine how to lay them out
To do this we use a_______


These determine how components appear in a window and how much space is allocated for them.

layout manager

Places components as we read a book – left to right top to bottom

FlowLayout

Places components in an equally sized 2-dimensional rectangular grid

GridLayout

This is a component in which the user can enter text

JTextField

Have most of the functionality of JFrames, except without the title/menu bar
Can store other components and lay them out using a layout manager

JPanels

subdivides our window into 5 areas
NORTH, SOUTH, EAST, WEST, CENTER
We can put a component in each area or just some of them
If the component is a JPanel, we can then put our other components within that

BorderLayout

How to terminate a graphical program?

set an option in the JFrame
theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



or create a JButton that uses the System.exit(0); method call

What if we want it to also store and manipulate our own data in the JPanel?

We need to extend it using inheritance

When we extend a class in Java, the new class has ...

all of the functionality of the original, plus any new functionality that we give it via additional instance variables and methods
So, we can do this:
class MyPanel extends JPanel
We can then put whatever we’d like into our new class.We can add new instance variables, methods or both

(T/F) ActionListener is a class

false. ActionListener is an interface

A _____ is a named set of methods.

Java interface

(T/F) A Java interface is a named set of methods
headers and method bodies.

False, A Java interface is a named set of methods
However, no method bodies are given – just the headers

In Java interface: Static constants (are allowed/not allowed),


instance variables (are allowed/not allowed), static methods (are allowed/not allowed).

Static constants are ALLOWED


Instance variables are NOT Allowed
Static methods are NOT Allowed

(T/F) Any Java class (no matter what its inheritance) can implement an interface by implementing the methods defined in it.

True. Essentially an interface is stating an ABILITY of the class

(T/F) A given class can implement any number of interfaces

True

Note that in the________we must declare that the interfaces are implemented

Class header

can be used to reference any object that implements that interface

interface variable

(T/F) a single class may implement many interfaces, if it is being
accessed through an interface variable, the methods in the other interfaces are
also available.

False! if accessed through an interface variable, the methods in the other interfaces are
NOT available. The interface masks the object such that only the interface methods are visible / callable. If other methods are attempted to be accessed, a compilation error will result.


But only the interface methods are accessible through the interface reference

Even though a single class may implement many interfaces, if it is being accessed through an interface variable, the methods in the other interfaces are not available. Describe the example used in class. Booable();

Laughable L1, L2, L3;
L1 = new Comedian();
L2 = new SitCom(); // implements Laughable
L3 = new Clown(); // implements Laughable
L1.laugh(); L2.laugh(); L3.laugh();
L1.boo(); // illegal evn thoComedian has boo()
((Booable)L1).boo(); // this is ok since we cast


________ are classes that ______ objects around primitive values, thus making them compatible with other Java classes.

Wrappers, "Wrap"

Java primitive types are NOT classes, and thus cannot be used in this way.
If I make an array of Object or any other class, primitive types cannot be stored in it. How do we work around this problem?


by using Wrapper Classes

a static method that enables us to


convert from a String into an int.

Integer.parseInt()

a static method that tests if a letter is a character or not.

Character.isLetter()

(T/F) Arithmetic operations are defined for wrapper classes.

FALSE! Arithmetic operations are NOT defined for wrapper classes. We need to get the underlying primitive.


k = i + j;


k = new Integer(i.intValue() + j.intValue());


In words: Get the primitive value of each Integer object, add them, then create a new Integer object with the result

This does the conversion back and forth automatically.

Autoboxing

(T/F) autoboxing Saves the programmer some keystrokes and improves efficiency.

FALSE! Saves the programmer some keystrokes
However, the work STILL IS DONE, so from an efficiency point of view we are not saving
Should not use unless absolutely needed

One ability of the wrapper classes is....

static methods to parse strings into the correct primitive values


Integer.parseInt(), Double.parseDouble(), Boolean.parseBoolean()


These enable us to read data in as Strings, then convert to the appropriate primitive type afterward

The Character wrapper class provides many useful methods:

Case conversion, checking for letters, checking for digits.


Can be useful when we are parsing text files ourselves.

The String class has some very useful methods:

ex:


split()


See ex18.java

Sometimes we want to build a new class that is largely like one we already have
Much of the functionality we need is already there, but some things need to be added or changed. We can achieve this by...

using inheritance! wahhhhh !



Attributes of a base class, or superclass are passed on to a subclass

the “is a” idea

A subclass object “is a” superclass object.


Note that “is a” is a one way operation

“Is a” is a ____ way relationship.

“Is a” is a one way relationship.

Inheritance in Java is implemented by ______a class

Inheritance in Java is implemented by extending a class.


We saw this already in Counters2.java, where our new class extended JPanel


The protected declaration is...

...between public and private.


Protected data and methods are directly accessible in the base class and in any subclasses (and in the current package).


However, they are NOT directly accessible anywhere else

In Java, class _______is the base class to all other classes.

In Java, class Object is the base class to all other classes

The tree of classes that extend from Object and all of its subclasses is called...

...the class hierarchy

All classes eventually lead back up to....

All classes eventually lead back up to Object

class hierarchy enables...

enables consistent access of objects of different classes, as we shall see shortly

it allows us to mix methods and objects of different types in a consistent way.

polymorphism

method overloading is also called...

ad hoc polymorphism

ad hoc polymorphism is also called ...

method overloading

ad hoc polymorphism, or method overloading

In this case different methods within the same class or in a common hierarchy share the same name, but have different method signatures (name + parameters)


public static float max(float a, float b)
public static float max(float a, float b, float c)
public static int max(int a, int b)

When a method is called, the call signature is matched to the correct method version. When is this done?

This is done during program COMPILATION

ad hoc polymorph, or method overloading, If an exact signature match is not possible, it will select the next closest via ...

via “widening” of the values is used

when values of “smaller” types are cast into values of “larger” types, this is called...



hint: polymorph concept

Widening.


Fewer widenings provides a "closer" match

If two or more versions of the method are possible with the same amount of “widening”, the call is _________, and a ______ error will result.

If two or more versions of the method are possible with the same amount of “widening”, the call is ambiguous, and a compilation error will result

Subclassing Polymorphism
Sometimes called...

“true polymorphism”

Subclassing Polymorphism


Consists basically of two ideas:

Method overriding
Dynamic (or late) binding

Method overriding

A method defined in a superclass is redefined in a subclass with an identical method signature
Since the signatures are identical, rather than overloading the method, it is instead overriding the method
For subclass objects, the definition in the subclass replaces the version in the superclass

Dynamic (or late) binding

The code executed for a method call is associated with the call during run-time
The actual method executed is determined by the type of the object, not the type of the reference


Polymorphism example: the Animals


Animal [] A = new Animal[3];
A[0] = new Bird();
A[1] = new Person();
A[2] = new Fish();
for (int i = 0; i < A.length; i++)
A[i].move();


When mixing objects of difference classes, some access rules are important to know: what are they?

Superclass references can always be used to access subclass objects, but NOT vice versa.
Given a reference R of class C, only methods and instance variables that are defined (initially) in class C or ABOVE in the class hierarchy can be accessed through R
They still exist if defined in a subclass, but they are not accessible through R


(T/F) Superclass references can always be used to access subclass objects, and vice versa

FALSE!


Superclass references can always be used to access subclass objects, but NOT vice versa!

Animal A = new Bird();
Bird B = new Animal();



which is ok

Animal A = new Bird(); // this is ok
Bird B = new Animal(); // this is an ERROR

Suppose class Fish contains a new instance variable waterType and a new method getWaterType()
Fish F = new Fish();
Animal A = new Fish();
System.out.println(F.getWaterType()); ok?
System.out.println(A.getWaterType()); ok?

System.out.println(F.getWaterType()); // ok
System.out.println(A.getWaterType()); // NO!


The reason is that the method is not visible from the reference’s point of view (A is an Animal reference so it can only “see” the data and methods defined in class Animal)
System.out.println(((Fish) A).getWaterType());
^ ok, sinc we have now cast the ref to the Fish type, wich CAN acc methd


If unsure, test using__________before casting.

If unsure, test using instanceof operator before casting

Object, Method and Instance Variable Access

Superclass references CAN BE used to ref subclass objects
Subclass references CANNOT BE used to ref superclass objects
The type of the ref deter what data and methods are ACCESSIBLE
The type of the object determines what data and methods EXIST
Methods and data initially defined within a subclass CANNOT BE accessed via a superclass reference
The type of the object also determines which VERSION of an overridden method is called

Superclass references (CAN BE / CANT BE) used to ref subclass objects

Superclass references CAN BE used to ref subclass objects

Subclass references (CAN / CANNOT)used to ref superclass objects

Subclass references CANNOT BE used to ref superclass objects

The _____ determines what data and methods are ______.

The type of the reference determines what data and methods are ACCESSIBLE

The __________ determines what data and methods _______.

The type of the object determines what data and methods EXIST

Methods and data initially defined within a subclass (CAN/ CANNOT BE) accessed via a superclass reference

Methods and data initially defined within a subclass CANNOT BE accessed via a superclass reference

The type of the object also determines which __________of an overridden method is called


The type of the object also determines which VERSION of an overridden method is called


Sometimes in a class hierarchy, a class may be defined simply to give cohesion to its subclasses
No objects of that class will ever be defined
But instance data and methods will still be inherited by all subclasses, this is called...

Abstract classes

(T/F) Abstract classes objects may be instantiated

FALSE


No objects may be instantiated

Java allows only_______ inheritance

Java allows only single inheritance

We may want to identify an object in multiple ways:
One based on its inherent nature (i.e. its inheritance chain). Make an example

Ex: A Person
Others based on what it is capable of doing
Ex: An athlete
Ex: a pilot

(T/F) An interface variable can be used to reference any object that implements that interface

True However, only the interface methods are accessible through the interface reference

An occurrence of an erroneous, unusual or unexpected event in a program execution

Exception:

Exceptions are objects that are ...


Exceptions are objects that are thrown …
and catched


Java exception handling.


Exceptions are handled using

Exceptions are handled using try-catch blocks

If all goes well (no exceptions occur) what block of code is executed?

Code in try block is executed, followed by code in (optional) finally block.


If an exception occurs anywhere in the try block
Execution immediately jumps out of the try block.

If the exception is not handled in a catch block, the (optional) finally block is executed and then the exception is...

propagated

Is The Finally block is optional?

YES

If an exception is handled
Execution resumes immediately AFTER

try/catch block in which it was handled, and does NOT return to throw point

termination model of exception handling

As opposed to a resumption model, where execution resumes from where the exception occurred

If an exception is propagated
A handler is searched for by... AKA...

backing up through the call chain on the run-time stack. dynamic exception propagation

If no exception handler is ever found


Console applications...


GUI applications...

Console applications crash and report exception
GUI applications will continue to execute, but may be in an inconsistent state – more soon

Checked exceptions

If a method does NOT handle these, the method MUST state that it throws them
Done in a throws clause in the method header


These include IOException, and InterruptedException (and their subclasses)
That is why various handouts throughout the term have had some exception handling – it was required

Unchecked exceptions

Method not required to explicitly "throw" these
These include RunTimeException and Error

a method should be able to call itself – we call this a...

RECURSIVE CALL