JAVA FINAL 5

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Variable

A memory location with a name and a type that stores a value. These items are "uninitialized" until they have been given a value.

--

Decrement by one

Empty String

A special string literal, denoted by "".

Constructor?

A special type of method that is called when an object is created to initialize variables.

Assignment Statement

A statement assigning a value to a variable.

while

(i != TotalNum) { } // code in here

Cast

(typeName) expression

Literals

Have a fixed value, as opposed to a variable. Each primitive type has an associated set of literal values and a literal value can be assigned to a primitive variable of the same type.

What must variable names have/not have?

Have: Starts with a lower case letter. Not Have: after initial letter cannot have a symbol other than the underscore (no spaces).

What is an abstract data type?

I a specification of the type's operations: what an instance of that type can do.

Bit

I binary digit, either 0 or 1

-Cannot put a decimal into an integer -Integers cannot hold decimal values EX: int = double <---WRONG EX: double = int <--- CORRECT

Mixing Data Types Rules

A no-argument constructor has....

No parameters.

*** If a variable is used as an argument...

ONLY the value of the the argument is plugged into the parameter, NOT the variable itself

Emergency exit

Sytem.exit(value);

JRE

An environment used to run Java Applications. Contains basic client and server JVM, core classes and supporting files.

bug

An error in the code

What is the difference between Assignment and Initialization?

Assignment can be done as many times as desired whereas initialization can be done only once.

String

Can use +, ., and +=

Conversion

Changing one type of primitive data to another.

low-end servers

Desktop computer without a screen or keyboard usually accessed via a networ

!

The ___ operator, called the "inversion" operator, returns the opposite value of the boolean value it precedes.

java.io.*;

To utilize data streams.

System.out.println("ab\"\\c"); prints out

ab"\c

LinkedList

Makes it easy to create structures like stacks or queues.

Public int

Makes it possible to modify the variable from another program that is using the object.

How can you specify a string to make a assert statement more meaningful

assert price > 0 : "Price less than 0.";

b

b

Local variables don't get ...

default values, so they must be initialized before use.

class definition

describes what attributes its objects will have and what those objects will be able to do

What should methods do?

determine how the class will define its behaviors solve a problem

void

indicates that the main() value doesn't return any value when it's called.

Pi

Math.PI

π

Math.PI;

absolute value of x - y

Math.abs(x - y);

random number between 0 and n

Math.random() * (n + 1);

random number between 0 and 1

Math.random();

square root of a

Math.sqrt (a);

radians to degrees

Math.toDegrees();

Source

Information in it's original form.

What is the scope of a variable?

It defines where the variable can be used in a program.

Overloading Polymorphism : ad-hoc

It means integer addition when used in form 22 + 33; it means floating point addition when used in the form 2.2 + 3.3; and it means string concatenation when used in the form + ", esq."

Math.sqrt(x)

square root of x

polymorphism

Method overloading is an example of polymorphism. polymorphism can be defined as "one interface with multiple behaviors." Another form of polymorphism is method overriding, which is an example of dynamic binding. Method overriding is discussed later in this topic.

Program

- Sequence of instructions for the computer

()

used to surround perimeters

What will automatically happen if you add elements at any index in the ArrayList object?

"It will automatically move the other elements" [Orginal below] An ArrayList object can have elements added at any index in the array and will automatically move the other elements.

remainder

%

System.out.Printf("%3d", i*j)

% /number of spaces taken up/ Integer, variable

and

&&

Logical Operators

&& ||

Integer value: 97

'a'

An 'abstract' class can have both ...

'abstract' and non-abstract methods.

A class cannot be both ...

'final' and 'abstract'.

Classes can also be modified with ...

'final', 'abstract' and 'strictfp'.

grouping operator

( ), highest precedence

Actual parameter

(i.e. Argument) • the variables or data to substitute formal parameters when invoking a method

Formal parameter

(i.e. Parameter) • variables defined in method signature

What is an iterator? Where have we used them before?

Within the loop, obtain each element by calling next( ). We've used these with scanner and random

short hand a = a * n

a *= n;

short hand a = a + n;

a += n;

addition operator

+, fifth highest precedence, left to right association

play 2001.mid

StdAudio.play("2001.mid");

Encapsulation

When each object protects its own information.

method selector operator

., second highest precedence, left to right association

Anatomy of a Java Statement

...

Defining Parameters

...

UML Notation

...

This method is present in all exceptions, and it displays a detailed error message describing what happened.

.getMessage() method

What operator divides two numbers?

/

How do you make a comment?

//Comment /*Multi-Line Comment*/ /**JavaDoc Comment *Describes Program or *Method **/

short

16 bit integer

Conditional operator

condition?truepath:falsepath; (hours<12 ? "AM" : "PM";)

Math.cos(x)

cosine of x

Loop count to 10

for(count = 0; count<11: count++);

debugging

freeing the program of all errors

An 'abstract' class cannot be ...

instantiated.

Declare and define integer a from double, b.

int a = (int) b;

Switch Example 2

int i=2; switch (option) { case 1: Statement; case 2: Statement; case 3: Statement; }

Name the 6 numeric data types

int, double, short, long, byte, and float

What could a object be compared to for similarity?

like base blocks that are interchangeable in how they can be used in other programs.

statements

lines of code in java

API documentation

lists the classes and methods of the Java library

Block statement

{ statement; statement; }

Use a division assignment operator to make c=4 when c=8

c/=2

embedded computers

A computer used to running one predetermined application or collection of software

Named constant:

A memory location whose content is not allowed to change during program execution.

Abstract Method

A method that does not have an implementation (no body of code defined)

The RGB values of Color.RED

255, 0, 0

In Java, every program statement ends with what?

; (a semicolon)

/

Division

Linear/Sequencial Search

Elements are searched one at a time in the order which they are numbered.

Expression

A simple value or a set of operations that produces a value.

char

A single character

Iteration

A single trip through a loop.

Variable Declarations

A statement that typically specifies two things about a variable: The variable's name and the variable's data type. Must be done before it can be used in a program.

Pseudocode

A stylized half-English, half-code language written in English but suggestion Java code

Control structure

A syntatic structure that controls other statements. Ex. A for loop.

Machine Language

A system of instructions & data executed directly by a computer's CPU.

Statement

A unit of executable code, terminated by a semi-colon.

field

A variable that belongs to the entire class (not just a method).

What is an abstract class?

Abstract classes, unlike interfaces, are classes. There are more expensive to use because there is a lookup to do when you inherit from them. Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for them.

name [row] [col]

Access an element

Mixed expression:

An expression that has operands of different data types.

&&

And

Work with Java Arrays

Chapter 6 Objective 1

Chapter 12: The ______ is the strategy for the view.

Controller

Able to be modified by the class, package, subclass, and world.

Define the keyword "public"

Method that returns.

Define the keyword "return"

class

Defines the characteristics and actions of an object. Models things from the problem domain.

Code Block

Delimited by curly-brackets, enables a set of statements to be treated as a single statement.

Inclusion Polymorphism

It refers to the ability an object to invoke a method that it inherits; public class TestRatio{} Ratio x = new Ration(); x.hashCode(); <--- inheritated

What does JVM stand for?

Java Virtual Machine

TreeSet

Keeps the elements sorted and prevents duplicates.

What are the three ways to return control to the statement that calls a method?

Let the second bracket of the called method return control use return; to return control use return (expression); to return a variable as well as control

HashMap

Lets you store and access elements as name/value pairs.

void

Means that the method does something but does not return any value at the end

Methods

Part of an Object's behavior.

Methods with parameters

Methods that you can pass one or more values in to.

Are primitive data types considered objects in Java?

No, primitive types are the only elements of the Java language that are not modeled as objects.

type

Specifies what kind of thing a variable or a parameter is. Example: int, char, boolean...

-Must end with a ; (semicolon)

Statements

Expressions

Statements that involve a mathematical equation and produce a result.

draw circle at (x, y) radius = r

StdDraw.circle(x, y, r);

what is the code to display the current time?

System.currentTimeMillis()

Print format statement to get 3.14 of pi

System.out.printf("%.2f", pi);

concatenate and output

System.out.println("this with "+ thisEnter);

What System.out method moves the cursor to the next line?

System.out.println()

print (return)

System.out.println();

not equal

!=

What are 6 assignment operators?

= += -= *= /= %= ----------------- v20

What is the assignment statement

= its the equal sign

assignment operator

=, lowest precedence, right to left association

Assembly Language

A programming language that uses letters and numbers to represent machine language instructions

.java

All Java file names have to have this extension.

application software

Software/programs developed by the users

What are standard Java arrays and when must they be initialized?

Standard Java arrays are objects and must be initialized after they are declared.

....

Standard Java arrays can be declared with square brackets after the type or variable name. Example: int[] myArray or int my Array[]

Reasons to use "int"

Numbers -2 billion to, 2 billion

double

Used to declare and initialize a fraction interager. Ex: double canVolume = 0.335;

==

Used to equal a value

New tab character

\t

Math.toDegrees(x)

convert x radians to degrees (ie, returns x*180/p)

Variable declaration statement

declares the identifier and data type for a variable

What are static methods?

don't need to instantiate an object of the class to invoke the method.

What is the this reference?

it is used to refer to the currently executing object (static)

literals

items in programs whose values do not change; restricted to the primitive data types and strings

Where should the default statement be placed within a switch statement?

last

Identifiers may contain ...

letters, digits and the underscore character

static

means the method is accessible and useable even though no methods of the class exist

import java.util.Scanner

imports Scanner library

/n

newline; advances the curson to the next line for subsequent printing

Method call

object.methodName(parameters);

Wildcard import

imports all the classes in a package. EX: • import javax.swing.* imports all classes from package javax.swing. import javax.swing.*;

If a superclass member is public, the subclass ...

inherits it - regardless of package.

A for loop is functionally equivalent to the following while loop structure:

initialization; while ( condition ) { statement; increment; }

System.out.println

prints statement and creates new line

Chapter 1: Good OO designs are

reusable, extensible and maintainable

What must every method and class have an open and closed of?

{ } (braces, or curly brackets)

commands

program statements

both

The & and | operators always evaluate ____ operands.

Static variables are not tied to ...

any particular instance of a class.

Value: true/false

boolean

Instantiation

Creating an object.

Representing a character using a binary code.

Encoding

;

End of a statement

Pseudocode

English-like descriptions of algorithms.

What are the two subclasses of the throwable class?

Error & Exception

prompt

Asks the user a question

=

Assignment Operator

!=

Boolean not equal to

Reasons to use "float"

127 digits after the decimal point

short

2 bytes, stores integer values

2000

20 + '0' + 0=

Computer Simulations

attempt to mimic real-world activities so that their process can be improved or so that users can better understand how the real-world process operates

\\

backslash; causes a backslash to be printed

-8 bits Range: -128 to 127 No rules

byte

A loop can also be used for input validation, making a program more robust

The number of games won must be greater than or equal to zero and less than or equal to the total number of games played

Use an Addition assignment operator to make c=5 when c=2

c += 3

Make c not equal to b

c!=b

If a class cannot be accessed, its members ...

cannot be accessed.

I can have many arguments.

method

How should we create methods?

method decomposition parameters

Evaluation

The process of obtaining the value of an expression.

public static void main(String [ ] args)

method header;

The 'synchronized' modifier applies only to ...

methods and code blocks.

Boolean Literal

The words true and false.

true

The || and | operators return ____ if either or both operands are true.

A parameter is a local variable initialized to....

the value of the corresponding argument. (Known as Call-by-value)

Values passed in and out of methods

They can be implicitly promoted to a larger type or explicitly cast to a smaller type

What is the definition of the Java class Library A.K.A Java A.P.I(Java Application Programming Interface)?

This is the list of preprocessed classes, packages, and methods that you may use at your disposal such as the Math....() methods.

Blueprint

This is what it is liken to when a class describes how to make an object of that class type.

Create a math program that generates to random numbers to be added together .

This shows how the use of boolean or true/false is used in the answer

datacenters

Thousands of processors forming a large cluster

parts of a program set up to run on their own while the rest of the program does something else.

Threads

java.awt.*;

To paint basic graphics and images.

contains the class of exception to be caught and a variable name.

catch clause

Methods that use instance variables

causes objects of the same type to behave differently

/b

causes the cursor to back up, or move left, one position

java.lang.*;

To utilize the core java classes and interfaces.

ArrayList: add "hi"

myArr.add("hi");

ArrayList: add "hi" to ArrayList at index i

myArr.add(i,"hi");

ArrayList: check if list contains item

myArr.contains(item);

else

Used in conjunction with if. Checks if the condition is false

Ternary Operator

Used to assign a value or display a value based on a condition.

Integer.ParseInt()

Used to get a value of a String, usually with a digit.

Length method

name.length()

Prints to the current line(single function)

print

Prints x on the same line

print(x)

System.out.print

prints statement

I shouldn't be used with instance variables

public

How to define a class?

public class "class name" (no extension)

main loop

public static void main (String[] args)

" "

quotation marks; encloses a string of characters, such as a message that is to be printed on the screen

Scanner in = new Scanner(new File("input.txt");

reads input from a file (also declared in same line)

java SentinelDemo < numbers.txt

redirects input

==,!=,>,<,>=,<=

relational operators; equal, not equal, greater than, less than, greater than/equal to, less than/equal to

/r

return; causes the cursor to go to the beginning of the current line, not the next line

int

Variable type with 32 bits and a range of [-2147483648 to 2147483647] = 4 bytes of storage

objects

second category of Java variables such as scanners and strings

A class with public access can be ...

seen by all classes from all packages.

Objects

sent messages

.

separates package names / adds folders

What is the method signature of public void setDate(int month, int day);?

setDate(int, int);

Naming standard for mutator method?

setXYZ();

By definition, I take one argument.

setter

char newChar = (char)(mychr + x)

shift character by x numbers (use ASCII table values)

programming vs natural languages

size, rigidity, literalness

aggregation

special form of association representing ownership of a relationship bw obj's

Sentinel value

special input value signifying → end of input

String: remove whitespace

str.trim();

What is the class before the keyword, extends called? the one after?

subclass Superclass

A 'final' class cannot be ...

subclassed.

-=

subtract and assign operator

primitive

data such as numbers and characters, NOT objects

Scanner in = new Scanner(System.in);

declares Scanner "in"

-64 bits Range: -big to big

double

//

double slash; marks the beginning of a comment (a statement ignored by the computer)

declare and initialize primitive variables

double thisIsDouble; int thisEnter; thisIsADouble=0.0; thisEnter=0;

declare and initial double array, points, with length N

double[] points = new double [N];

passing arguments

the act of sending an argument to a method

Your classes should generally have both an _______ method and a _____ method.

equals && toString

Method returning true if this string is = to string 2

equals(s1)

\\

escape character for backslash

What is a conditional expression ?

evaluates a condition based on an expression

The for Statement

for (initialization; condition; update) statement;

What is the syntax of a decision control flow example?

if (x == y) { ... } else { ... } switch (index) { case 0: {...} case 1: {...} default: {...} }

if (condition) { statements1 } else { statements2 }

if statement (else not required in all cases)

The 'transient' modifier applies only to ...

instance variables.

The 'volatile' modifier applies only to ...

instance variables.

What is the code to generate a random number between 0-9?

int math=(int)(Math.random() *10); System.out.print(math)

true

What will print (or ERROR)?

a high-level design (Sierra 109)

What you should start with a Java Program

Arrays as Parameters

When an array is passed as a parameter, it is actually passing an object reference.

identifier

a name

Virus

a program that can enter a computer and perhaps destroy information

architecturally neutral

a program that can run on any operating system ex. Java

null Reference

a reference that does not refer to any object

Arithmetic expressions

a sequence of operands and operators that computes a value

jGRASP

a source code editor

/* */

long comments

instance

an object of a class.

What is an object

an Object is an instance of a class (created by instantiating a class with a new keyword and a constructor invocation) for ex. Point p = new Point(1.0, 2.0);

Assignment operator

an operator (=) that changes the value of the variable to the left of the operator

public

an access specifier

compile-time error

an error in which the compiler detects a violation of language syntax rues and is unable to translate the source code to the machine

Helper methods should be

marked as private

public static void boxString(String contents)

void methods return no value, but can produce output

What is the ASCII value of 'a'?

97

Make g conditional upon some statement

?:g

Java Virtual Machine (JVM)

A platform-targeted runtime environment that knows how to execute Java bytecode.

Input Assertion

A precondition for a loop ex: int d; int j = 10; do{ d++ while }(int j<=20);

subtraction operator

-, fifth highest precedence, left to right association

Runnable vs Thread

-Extend Thread...-Implement Runnable. Implementing Runnable allows you to extend another thread

Life Cycle - Blocked

-The thread is waiting for some resource...-Common reasons for blocking: waiting for input over a network or from a file, or waiting for the user

What are single array variables capable of doing?

They can reference a large collection of data

Superclass

This is where a class can inherit instance variables and methods from.

Comparing Object References

To see if two object references are the same (which means they refer to the same object on the heap), use the equality operator (==)

How do you declare a CONSTANT in Java?

Using the keyword "final": final float pi = 3.14159f;

blank.

Value

Post Condition?

What will be true after a method is called

ERROR

What will print (or ERROR)?

The animal is a elephant

What will print (or ERROR)?

What is control statement stacking?

When a number of control statements are placed one after another in a sequence within a program.

Implicit type coercion:

When a value of one data type is automatically changed to another data type.

What is the purpose of this algorithm? for (int i = 0; i < data.size(); i++) { data.set(i, i ); } A) Filling in initial values for an array. B) Counting matches in an array. C) Filling in initial values for an array list. D) Counting matches in an array list.

Ans: C Section Ref: Section 7.6 Common Array Algorithms

Which of the following statements about an inner class is true? A) An inner class may not be declared within a method of the enclosing scope. B) An inner class may only be declared within a method of the enclosing scope. C) An inner class can access variables from the enclosing scope only if they are passed as constructor or method parameters. D) The methods of an inner class can access variables declared in the enclosing scope.

Ans: D Section Ref: 9.8

Object

An instance of a class.

Consider the following code snippet: public interface Sizable { int LARGE_CHANGE = 100; int SMALL_CHANGE = 20; void changeSize(); } Which of the following statements is true? A) LARGE_CHANGE and SMALL_CHANGE are automatically public static final. B) LARGE_CHANGE and SMALL_CHANGE are instance variables C) LARGE_CHANGE and SMALL_CHANGE must be defined with the keywords private static final. D) LARGE_CHANGE and SMALL_CHANGE must be defined with the keywords public static final.

Ans: A Section Ref: Special Topic 9.1

A class that represents the most general entity in an inheritance hierarchy is called a/an ____. A) Default class. B) Superclass. C) Subclass. D) Inheritance class.

Ans: B Section Ref: 10.1

To override a superclass method in a subclass, the subclass method ____. A) Must use a different method name. B) Must use the same method name and the same parameter types. C) Must use a different method name and the same parameter types. D) Must use a different method name and different parameter types.

Ans: B Section Ref: 10.3

Which of the following is a good indicator that a class is overreaching and trying to accomplish too much? A) The class has more constants than methods B) The public interface refers to multiple concepts C) The public interface exposes private features D) The class is both cohesive and dependent.

Ans: B Section Ref: 8.2

Which code fragment constructs an arrray list named players that is initialized to contain the strings "Player 1" and "Player 2"? A) ArrayList<String> players = new ArrayList<String>(); players.set(0, "Player 1"); players.set(1, "Player 2"); B) ArrayList<String> players = new ArrayList<String>(); players.set(1, "Player 1"); players.set(2, "Player 2"); C) ArrayList<String> players = { "Player 1", "Player 2" }; D) ArrayList<String> players = new ArrayList<String>(); players.add("Player 1"); players.add("Player 2");

Ans: D Section Ref: Section 7.2 Array Lists

char

Any character. Surrounded by single quotation marks.

API

Application Program Interface (API) • Set of classes & interfaces that can be used to develop Java programs.

Methods?

Are always public. They return data. Methods are made so that you can call on them so that you can use its functionality.

exception that is thrown when your not properly checking to make sure that your code always stays within the bounds of an array

ArrayIndexOutofBounds

Autoboxing

Autoboxing is the automatic conversion of a primitive value to a corresponding wrapper object: Integer obj; int num = 42; obj = num; The assignment creates the appropriate Integer object The reverse conversion (called unboxing) also occurs automatically as needed Integer obj = new Integer(45); int num; num = obj; The assignment extracts the int value from obj

!

Boolean not

&&

Boolean operator meaning both sides have to be true. A Short circuiting logical operator.

What are the different layout managers? What would you use them for?

Border -NESW Box - organizes in single row or column Card - organizes so that only one is visible at a time Flow - Left to Right Grid - Grid of rows and columns GridBag - Grid of cells

Reference Variables

Can't store data values, but *refer to objects* that do.

Case SenSitive

Capital letters must be capitalized to reference a variable correctly

-put data type you want in parenthesis before data you want to convert EX: int x = (int) 12.3; //cast double value of 12.3 as int, now has a value of 12

Casting Rules

Autoboxing

Casts a simple variable value to the corresponding class.

Unboxing

Casts an object to the corresponding simple value.

switch break

Causes the switch to terminate by transferring control to the end of the statement. Note that it can be used in a similar way in any statement.

Create a new instance of circle

Circle c = new Circle(); ( this is a member of a class that has the same name as the class and has a body)

give an example of a constructor

Circle() (( this is a member of a class that has the same name as the class and has a body))

Selection Statements

Flow control structures that allow us to select which segments of code are executed depending on conditions. Includes 'if...else' and 'switch...case'.

RuntimeException

Class is the superclass of those exceptions that can be thrown during normal runtime of the Java virtual machine.

// marks the single line ? /* block ? */

Comments

supercomputers

Computer used to run large problems and usually accessed via a network

Extreme Condition

Data at the limits of validity ex: When a data type is (almost) overwhelmed by the data value; an int hold (almost) or trying to hold past its 32 bit limit which it will succeed.

type[] [] name

Declare a 2D array

[]

Declares arrays

Localizing variables

Declaring variables in the innermost scope possible.

Null means nothing. It's a place holder.

Define "Null"

Exception that occurs when you're reading from a file and the file ends before you expected it to end.

EOFException

-Begins with a \ -Always comes in pairs

Escape sequences

What are the four basic development activities? How do they interact with one another? Which one is the most important?

Establishing the requirements -Software requirements specify what a program must accomplish. Creating a design -A software design indicates how a program will accomplish its requirements. Implementing the design -Implementation is the process of writing the source code that will solve the problem. Testing -Testing is the act of ensuring that a program will solve the intended problem given all of the constraints under which it must perform.

Use the dot operator (.)

How do you access a method or instance variable?

curly brackets and ;

In general, Java doesn't require code blocks delimited by '{..}' to be followed by a ';' as would normally be the case for a statement.

For Loop

Repeats a section of a program a fixed amount of times.

Modulus

Represented by the character %, gives the remainder of a division between integral or fractional numbers (note that the result can also be fractional).

Index Operator

Represented by two bracket symbols ([]) and has the highest precedence of all Java operators. Used to indicate the index of an array.

Java1

Result? "Java" + 1

Iteration

Returning an object that can be used to cycle through all of the elements in a list

Why is there a semicolon (;) at the end of each statement?

So Java knows that it is the end of a statement.

system software

Software layer between the application software and the hardware that includes the operating system and the compilers

Graphical User Interface

Software that lets the user interact with a program or operating system through images and point-and-click mechanisms such as buttons and text fields

Insertion Sort

Sorts a list of values by repeatedly inserting a particular value into a subset of the list that has already been sorted.

VHDL

Special language used to describe hardware components. VHSIC Hardware Description Language

What are the local variables/parameters of a method stack known as?

Stack frames/activation records

println

Starts a new line after displaying the text.

draw filled circle at (x, y) radius = r

StdDraw.filledCircle(x, y, r);

draw line from (x, y) to (q, s)

StdDraw.line(x, y, q, s);

JSE JEE JME Java Card

Java Standard Edition - Contains the core functionality of the Java language; used to develop desktop applications. Java Enterprise Edition - Provides additional functionality required of enterprise applications, including web applications. Java Micro Edition - A scaled-down version used for mobile phones and other handheld devices. Java Card - The smallest Java footprint used for integrated circuits (e.g., memory and microprocessor cards).

What does empty Parenthesis at the end of a method declaration mean?

That the data for the method will be put in later.

true

The && and & operators return true only if both operands are _____.

Assignment operator:

The = (the equals sign). Assigns a value to an identifier.

What is the ArrayList class a representation of?

The ArrayList class is an object-orientated representation of a standard Java array.

What's the equivalent of a dictionary in Java? Please create an example.

Map - Look in module about collections.

Round to smallest integer not less than number input(round number up)?

Math.ceil(#) Ex: ceil(9.2)=10

How do you put e to a power? Ex: e^x

Math.exp(x)

Natural logarithm of a number?

Math.log()

Ways to handle an exception

Not handle it at all - program will crash and and produce a message describing the exception

exceptions happen when you try to use a variable that doesn't refer to an object yet.

NullPointerException

Chapter 1: defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

OO Patterns: Strategy

Define the Java related "object" and what is it interchangeable with?

Object and class define state (data_ and behavior (operations). Classes define an object's behavior.

Class

Where all Java code is defined.

Operator Overloading

Where the user can define the behaviour of an operator depending on the *types of its operands*. This isn't possible in Java, although the '+' operator is overloaded by the system to concatenate String objects.

Can standard Java arrays be multi-dimensional?

Yes, standard Java arrays can be multi-dimensional; each set of square brackets represents a dimension.

Can you have an inner class inside a method and what variables can you access?

Yes, we can have an inner class inside a method and final variables can be accessed.

A local variable disappears when...

a method invocation ends.

println

a method that prints characters to the screen and moves to the next line

print

a method that prints characters to the screen and remains on the same line

Method

a sequence of instructions that accesses the data of an object

program statements

a series of sentences that tell a program what to do

out

an object that provides a way to send output to the screen

numeric data types

another name for primitive data types; most commonly int and double

'synchronized' methods can have ...

any access control and can also be marked 'final'.

arithmetic expression

consists of operands and operators combined in a manner familiar from algebra

A variable declared "Final"

constant

String concatenation

append a string or value to another string

expressions that represent a condition that a programmer believes to be true at a specific place in a program.

assertions

What is the syntax of a sequence control flow example?

base = rate * hours; taxes = base * taxRate; net = base - taxes; count++; count--;

{ double volume = sideLength * sideLength * sideLength; return volume; }

body of method

A thread can be created in two ways:

by subclassing the Thread class or implementing the Runnable interface in another class.

Chapter 1: Most patterns and principles address issues of

change in software

-16 bits unsigned Range: 0 to 65535 -Holds one letter -Value enclosed in ' ' -Outputs letter unless addition is in parenthesis

char

Java interpreter

checks the bytecode and communicates with the operating system, executing bytecode instructions line by line within the JVM

Insert a comment? On multiple lines?

double slash ex. //commented slash asterisk ex. /* one line two lines */ (its the back slash for both)

Math.exp(x)

e^x

Arrays.toString(values) = [4,7,9...]

elements separated by commas with brackets

for (typeName variable: array/collection) { sum = sum + variable; }

enhanced for loop for arrays; adds each element of array to sum (declared before loop)

Importing a Class from a Package

import packageName.ClassName;

adding a throws clause to your method definition simply means that the method _______ throw an exception if something goes wrong,

might

syntax error

misuse of the language

Identifier

name of a variable, method or class

Integer.parseInt or Double.parseDouble

obtains the integer value of a string containing the digits

How does the substring() method of the String class work ?

the first argument specifies the index of the first character to include, the second argument indicates the index of the last character plus 1. A call to substring(2, 5) for a string would return the characters from index position 2 to index position 4.

An object reference marked 'final' does not mean ...

the object itself immutable.

Method call/actual and formal for method name; Return value, no parameters

variableName = methodName(); public static int methodName():

Constants

variables whose values cannot change

>=

Relational operator: greater than or equal to

<

Relational operator: less than

<=

Relational operator: less than or equal to

Primitive and Reference

Variables come in two flavors.

Bit

A binary digit 0 & 1. • binary numbers = #'s consists of 0's & 1's.

Where must all import declarations appear?

Before the first class declaration

String Literal

Anything within double quotation marks.

Single '

Quotation type used for character values.

==

Relational operator: equals

-

Subtraction

A class implementing an interface can itself be ...

abstract.

multiplication operator

*, fourth highest precedence, left to right association

Life Cycle - Runnable

- A pool of potentially runnable threads...-Not actively running...-Scheduler will select a thread from this group...-The only state a thread can go to from Runnable is the Active State

;

- Ends a statement - Acts like a period

Source Code

- Instructions for a program Ex: public class HelloWorld{ public static void main(String [] args){ System.out.println("Hello World");} }

Byte Code

- Java compiles code into ____ first - Unique to Java

.Java

- Java file created by user

Thread

- Process that can run at the same time with another process

Applet

- Small Java programs already translated into byte code Ex: animations on a webpage

.Java~

- This file cannot be used for anything

What is the Iterator interface?

- defined as part of java standard class library - hasNext(), returns a boolean result and - next() returns object

byte

1 byte, stores an integer

There are three access modifiers:

1) 'public' 2) 'protected' 3) 'private'

int

32 bit integer

Method

A group of Attributes and Behaviors.

String

A sequence of characters

Parameters are filled in with _________________ when invoking a method.

Arguments

machine language

Binary language that the processor can understand

&

Bitwise And operator

new type [nRows] [nCols]

Create a 2D array

Cable modem = as fast as?

DSL

Numbers with radix 16

Hexadecimal

Objects have both _______ and _______.

Instance Variables && Methods

What is method overloading and method overriding?

Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.

Mutator

Method that alters the attributes of an object.

!=

Not equal to

Private variable declaration?

Only applies to that class. ex. private String first;

||

Or

Use of the word "this"

Refers to the object itself

%=

Take remainder and assign operator

instanceof

The ____________ operator is for reference variables only and checks whether the object is of a particular type.

Source code:

The combination of the import statements and the program statements

string1.compareTo (string2) < 0

The compareTo method compares strings in lexicographic order.

b

bb

how do you define a constant?

final double NUMBER1=4.5; or final double PI=3.14;

Naming standard for accessor method?

getABC();

Numeric Data Sub-Types

int, long, float, double

declare and initial int array, number, with length N

int[] number = new int [N];

______\n______ is the escape sequence for

new line

short type

represents an integer in the range from -215 (-32768) to 215-1 (32767) • Primitive

The return Statement

return expression;

in.useDelimiter("[^A-Za-z]+");

restricts input to only letters, removes punctuation and numbers

console.nextDouble():

retrieves that floating-point number, if the value of this expression is that floating-point number.

I always fly solo.

return

No classes instances are needed in order to ...

use 'static' members of the class.

JFrame

used to show a frame(window)

variable declaration statement

when a program declares the type of a variable

syntax errors

when a syntax rule is violated

Uses a phone line & can transfer data in a speed 20 x faster vs. regular modem.

• DSL (digital subscriber line)

Hardware

The Physical pieces of a computer system

Swapping

Three assignment statements that change elements to a different index using a temporary place holder.

An object

What is an Array always is?

The number and type of values

What must match the order and type of the parameters declared by the method?

it should describe what to do

What should prep code should do?

literal values or values of declared type.

What type of values you can pass as an argument to a method?

A void return type does not return anything

What void return type mean?

27

What will print (or ERROR)?

Void

When a method does not return a value.

'public' members can be accessed by ...

all other classes, even in other packages.

What is the format for a, while, statement?

initialization; while (loopContinuationCondition) { Statement increment; } ex: pg 91

A class can extend only ...

one class (no multiple inheritance), but it can implement many interfaces.

Interfaces can extend ...

one or more other interfaces.

Prints a formatted string

printf

Prints to a new line and flushes the buffer.

println

Prints x on the same line, then moves the cursor to the next line

println(x)

What does c++ do? and what is it called? and c--?

prints result then adds 1. Postfix increment prints result then subtracts 1. Postfix decrement

set input variables

thisEnter = myScanner.next.Int();

If some code in your method's body might throw an exception, add the ______ keyword after the closing parenthesis of the method followed by the name or names of the exception

thows

J2ME

Acronym for Java 2 Platform, Micro Edition.

Predecrement

--x "Decrement, then give me x"

How to use sub-string function?

...

Java Environment

...

Java reserved keywords

...

Method call/actual and formal for method name; Return value, no parameters

...

The Parts of a typical class

...

Work with ArrayList Objects and Their Methods

...

terabyte

10^12 or 2^40 bytes

Programming:

A process of planning and creating a program.

Browser

A program that allows the user to find and view pages on the world wide web.

true or false

A boolean value can be ____ __ _____

Interface

A collection of constants and abstract methods

int

A data type that represents whole numbers.

What's a method?

A mini-program that is referred to by the program and others.

Equivalence Class

All the sets of test data that exercise a program in the same manner ex: all data types listed.

Argument Storage

An Array.

array

An object that is a simple but powerful way to group and organize data.

instance

An object.

What is the difference between constructor and method?

Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.

Does not change. Cannot make an instance of.

Define the keyword "static"

Method that does not return.

Define the keyword "void"

Argument

Extra information sent to a program.

Accessor

Extracts information from an object without changing it. Usually prefixed with 'get'.

;

Like a period in English. Marks the end of a statement or command

Bounds Checking

Makes sure that the index is within the range of the array being referenced. If the index is not valid, an ArrayIndexOutOfBoundsException is thrown. Automatically performed by the index operator.

cos x

Math.cos(x);

Methods

Name for functions that are defined in a class..

\n

New line

4 Java Data Types?

Numeric, String, Character, Boolean.

static

One copy and everyone can see it

assembly language

Symbolic representation of machine instructions

How about turning a primitive number into a String?

Use string concatenation double d = 30.24; String dString = "" + d; Use toString method in the Double class double d = 30.24; String dString = Double.toString(d); Check Java API for more such methods

Cast operator:

Used for explicit type conversion

What escape sequence makes the newline character?

\n

Constructor Definition

accessSpecifier ClassName(parameterType paramterName, ...) { constuctor body }

Write an expression that returns the position of the 1st occurrence of the String "Avenue" in address (a String).

address.indexOf("Avenue")

//

comment

An example of a for loop:

for (int count=1; count <= 5; count++) System.out.println (count); The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times

What is the syntax of a looping control flow example?

for (int i=1; i<10; i++) { ... } while (x < y) { ... } do { ... } while (x<y)

The 'native' modifier applies only to ...

methods.

All instances shares ...

only one copy of a 'static' variable/class.

Default and 'protected' members differ only when ...

subclasses are involved.

Pascal Casing or upper camel casing

the style that joints words in which each begins with an uppercase letter

When are the &, |, and ^ operators also bitwise operators?

when they're applied to integral operands

The while Statement

while (condition) statement;

while

while (true) { }

keywords

words in java that cannot be used as user-defined symbols

Hacking

-Act of exhibiting rare problem-solving abilities - Today: term is negative and describes a thief stealing information via internet

Life Cycle - Active

-The state of the thread that has control of the CPU...-Only time a thread can progress...-Can go to any of the following states from here: dead, blocked, suspended, sleeping, wait, runnable

random number between 1 and n

1 + Math.random() * n;

Compiler

A highly specialized piece of software that takes a programming language understandable by humans and converts it into a language that computers can understand.

High-level language

A programming language whose concepts and structures are convenient for human reasoning. Such languages are independent of the structures of computers and operating systems.

Attribute

A value an object stores internally.

=

Assignment

Naming Methods?

Begins with public then is whatever data is going to be returned. ex. public String displayname()

main()

Block statement statement in which all of the program's work gets done.

||

Boolean operator meaning only one side has to be true. A Short circuiting logical operator.

Abstract is assigned when you want to prevent an instance of a class from being created.

Define the keyword "abstract"

Used to catch exceptions and tell the application to do something else.

Define the keyword "catch"

used to implement an interface.

Define the keyword "implements"

Only able to be modified inside the class.

Define the keyword "private"

Able to be modified by the class, package, and subclass. But not the world.

Define the keyword "protected"

Surround all String text with?

Double Quotes

How is the filename of a public class formatted?

Filename.java

Difference bw floating type vs. double type

Float → 6-7 sig. digits of accuracy Double → 14-15

reference variables

Four types of things can be tested with the equality operators: numbers, characters, booleans, and _________ __________

HashMap<String, String>: Instantiation

HashMap<String, String> myMap = new HashMap<String,String>();

<

Less than

Create a generic method as in v59 and use bounded types (v60)

TODO

Enclosing Classes

The class that the nested class is nested in

True

True or False? For interfaces, an object passes the instanceof test if any of its superclasses implement the interface on the right side of the instanceof operator.

Parallel Arrays

Two arrays with corresponding elements.

How did we read in files? What is required?

We used a scanner, while loop, and iterator

Behavior

What an object does.

What escape sequence makes one backslash character in a print or println statement?

\\

Package

a group of related classes in a named directory

if (string1.equals(string2))...

compares equality of 2 strings

if / else

if (true) { } else { }

'final' reference variables must be ...

initialized before the constructor completes.

static method

method invoked WITHOUT creating an instance of the class → use "STATIC" in method declaration

Method call/actual and formal for method name; No return value, no parameters

methodName(); public static void methodName():

The two main kinds of methods:

methods that return a value / void methods

instance field

public double r; ( any field declared without the static modifier is an instance field)

Syntax to define a method (behavior (function in C++))

returntype methodName(optional_list_of_arguments) { ...} Names of properties (variables) and methods should start with a lower case letter, using camelCase if multiple words.

If a class implements the Runnable interface, what methods must the class contain?

run()

This method is the engine of a threaded class.

run()

/** Computes the volume of a cube. @param sideLength the side length of the cube @return the volume */

structure for commenting before methods (javadoc)

'private' members are not visible to ...

subclasses, so private members cannot be inherited.

long type

• represents an INTEGER ranging from -263 to 263-1 • Primitive variable vs. integer - ranges → -231 (-2147483648) to 231-1 (2147483647).

What package is the ArrayList part of?

" java.util package " The ArrayList class is part of the java.util package.

What must every line of code not followed by curly braces end in?

";"

How do you assign data to a variable?

"=". ex. int number = 100

If the ArrayList object capacity is exceeded what will it automatically do?

"It will automaticallly resize" An ArrayList object will automatically resize if its capacity is exceeded.

||

"Or" operator

Methods and instance (non-local) variables are known as ...

"members".

Method Selector

(.) - Selects the method

Assignment Operator

(=) - Assigns right side to left side Ex: celsius = (fahrenheit + 32)

How do you create variables?

(A kind of variable) (name of the variable) = (value of variable); For example, String var = "Hello, World";

{ }

(Curly braces). Marks the beginning and end of a unit, including a class or method description.

Unary operators

+ and - Take a single operand; not binary. Added to the list of precedence: 1) Unary 2) Multiplicative 3) Additive

Preincrement

++x "Increment, then give me x"

.Class

- Byte code form of the program that can be sent to other computer with Java

Println

- Name of the message will be printed out and the cursor will be placed at the beginning of the next line

Interpreter

- Program behaving like a computer Ex: JVM

Import Statement

- Program reads keyboard input using a scanner object Ex: import java.util.Scanner;

Life Cycle - Dead

-Thread execution is complete...-Cannot restart this thread...-There is a stop() method that can be used to kill a thread, but it is depreciated

Member access comes in two forms:

1) Code in one class can access a member of another class. 2) A subclass can inherit a member of its superclass.

Instance variables can ...

1) have any access control 2) be marked 'final' or 'transient'

Three ways to spot a non-abstract method:

1) the method is not marked abstract. 2) the method has curly braces. 3) the method has code between the curly braces.

Length

A constant in all Java arrays that keeps an array at its declared size.

driver program

A driver program is often used to test your own written class The DogTestDrive class contains a main method that drives the use of the Dog class, exercising its services

What is a 'set' in Java?

A grouping like a LIST but all the items are unique. There are no duplicates.

What's a list in Java?

A grouping that is ordered, sequential & can have duplicates.

abstract data type vs abstract class

A java abstract class is a class with at least one abstract method and no body. An abstract data type is a specification of a type's operations that could be implemented in any object oriented programming.

String

A line of text that can include letters, numbers, punctuation, and other characters.

The bits representing the value

A primitive variable value contains what?

Error

A problem that usually cannot be fixed

Class

A template in accordance to which objects are created. Includes a data specification and functions operating on these data and possibly on the data belonging to other class instances.

.....How would a three dimensional array be declared as? (How would it look like?)

A three dimensional array would be declared as int[ ][ ][ ] threeDArray.

Boundary Condition

A value at which two equivalence classes meet. ex: (exsampleClassA >= 0 || > exsampleClassB)

Array Element

A value stored in an array.

Local variable

A variable declared inside a method that is accessible only in that method.

J2SE

Acronym for Java 2 Platform, Standard Edition.

+

Addition

Scanner input = new Scanner(System.in);

Adds scanner to program

Statement

An instruction you give a computer.

Quick Check: Data Conversion

An int type can not store a float value Can fix it with casting to perform the narrowing conversion: int i = (int) 10.0/5 Output: 2

Mutator methods exhibit which of the following types of side effect? A) Modification of the implicit parameter. B) Modification of an explicit parameter. C) Production of printed output. D) Acceptance of text input.

Ans: A Section Ref: 8.4

When designing a hierarchy of classes, features and behaviors that are common to all classes are placed in ____. A) every class in the hierarchy B) the superclass C) a single subclass D) all subclasses

Ans: B Section Ref: 10.1

In Java, every class declared without an extends clause automatically extends which class? A) this B) Object C) super D) root

Ans: B Section Ref: 10.7

The wrapper class for the primitive type double is ____________________. A) There is no wrapper class. B) Double C) doubleObject D) Doub

Ans: B Section Ref: Section 7.3 Wrappers and Auto-boxing

Which class manages a sequence of objects whose size can change? A) Array B) Object C) Sequence D) ArrayList

Ans: D Section Ref: Section 7.2 Array Lists

Arithmetic Operators

Can be applied to integral or floating point types, includes multiplication(*), division(/), remainder(%), addition(+), subtraction(-).

What is the difference between design state and the implementation stage in the development of software?

Design Stage : identifies the components(classes) to be used and the relationships among them. Implementation Stage: is where the computer program code is actually written.

confirm

Displays a message and returns true if OK was clicked and false for cancel

alert

Displays a message with an ok button

do{ code here } while ( argument here);

Do loop

matrix[3] [2] = 8; pixels[r] [c] = aPixel;

Example of setting the value of elements

Demarcation and indentation

Good programming style in Java includes clearly showing the body of an if statement by creating a boundary around it with '{..}' curly-brackets. Segments of code can also all start with tabbed whitespace to highlight the structure of a program.

Lexicographic Ordering

If all characters are in the same case (upper or lower), the lexicographic ordering is the same as alphabetic ordering, therefore "book" comes before "bookcase" Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode Also, short strings come before longer strings with the same prefix (lexicographically)

Instance Variables are

Lifetime: instance variables exist as long as the object exists Scope: instance variables can be referenced by all methods in that class

Local Variables

Lifetime: when the method finishes, all local variables are destroyed (including the parameters of the method) Scope: local variables can only be used in that method

Exception that occurs when a URL isn't in the right format (perhaps a user typed it incorrectly)

MalformedURLException

absolute value?

Math.abs(#)

Smaller value of x and y?

Math.min(x,y)

*

Multiplication operator

Chapter 1: Patterns show you how to build systems with good

OO design qualities

During runtime, value assigned that exceeds positive bounds of a variable

Overflow error

System.out.print(" ");

Prints a string of text

compiler

Program that translates statements in high level language to assembly language

return function?

Returns and expression. ex. return first + " " + middle + " " + last;

Instance variables

Set to 0 a = 0; b = 0; c = 0;

What word is always capitalized in java syntax?

String

Create an example of Polymorphism that reflect v51

TODO

Arrays.copyOf(values, n)

The call Arrays.copyOf(values, n) allocates an array of length n, copies the frst n elements of values (or the entire values array if n > values.length) into it, and returns the new array.

What does it mean in an && operator statement to have a dependent condition?

The dependent condition is the one that gets tested first and must come after the && operator

2.3.1 a. add f, f, g add f, f, h add f, f, i add f, f, j addi f, f, 2 b. addi f, f, 5 sub f, g, f 2.3.2 a. 5 b. 2 2.3.3 a. 17 b. -4

The following problems explore translating from C to MIPS. Assume that the variables f and g are given and could be considered 32-bit integers as declared in a C program. a. f = -g - f; b. f = g + (-f - 5); 2.3.1 [5] <2.2> For the C statements above, what is the corresponding MIPS assembly code? Use a minimal number of MIPS assembly instructions. 2.3.2 [5] <2.2> For the C statements above, how many MIPS assembly instructions are needed to perform the C statement? 2.3.3 [5] <2.2> If the variables f, g, h, i, and j have values 1, 2, 3, 4, and 5, respectively, what is the end value of f?

What are variables?

Things that store information.

False

True or False? If the left-operand is false, the && will go ahead and evaluate the right operand.

byte

Used to define a primitive variable as an integer with 1 byte of storage. Also a corresponding wrapper class.

break

Used to leave a loop early

Semicolon

Used to separate sections.

Comma

Used to separate things within a section.

final

Variables marked ______ cannot be incremented or decremented.

%

What arithmetic operator returns the remainder of a division?

design test code

What do you use prep code for?

Null

What does a reference variable have for its value when it is not referencing any object?

What is the difference between an argument and a parameter?

While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

Backspace

\b

What escape sequence makes the backspace character?

\b

New line

\n

New line character

\n

Tab

\t

Object reference

a value that denotes the location of the object in memory

What is the sentinel value?

a value to be typed in to stop a loop

How do you test a diagram as to whether it is structured?

apply the rules backwards to reduce it to the simplest activity diagram.

double[] values = new double[10]; double[] moreValues = {32, 54, 67.5};

array declaration and initialization

Example using conditional operator

boolean someCondition = true; result = someCondition ? value1 : value2;

What is a local variable?

can be used only in the method that declares it from point of declaration to end of method

\

char that comes after is exempted from compiler (ie printing "")

in.hasNextDouble()

checks for numerical input; false if the next input is not a floating-point number

How do you start a program?

class (name of program) { //Your program goes here!! }

null reference example

class NameIsEx { String name; void printName( ) { System.out.println (name.length ( ) ); } }

Syntax rules:

determine the validity of instructions in a programming language.

logic

determines the exact order of instructions needed to produce the desired results

do { i++; //more code }while (i<max)

do/while loop

For numeric data types what declaration will always be used?

double

double b = a / b, but a is an int. Cast int to double

double b = (double) a / b;

What is the format for a, for, statement?

for (initialization;loopContinuationCondition;increment) statement (Initialization=declared variable and value) (loopContinuationCondition=i<5) (Statement=(println)

for loop (use i and N)

for (int i = 0; i < N; i++) { }

The first concrete class to extend an 'abstract' class must ...

implement all of its 'abstract' methods.

An 'abstract' implementing class does not have to ...

implement the interface methods (but the first concrete subclass must).

'abstract' methods must be ...

implemented by a subclass, so they must be inheritable.

Interfaces can be ...

implemented by any class, from any inheritance tree.

What are all of the methods for Scanner objects to read in input from a user.?

input.nextLine();

-32 bits Range: -2,147,483,648 to 2,147,483,647 No rules

int

declare and define command line integer argument, a

int a = Integer.parseInt (args[0]);

HashMap: see if map contains a key

myMap.contains("key");

HashMap: get value string from key string

myMap.get("key");

HashMap: insert a key string and a value string

myMap.put("key","value");

HashMap: get a Collection of the values

myMap.values();

Initialize a variable

n = 5;

final int VOLUME = 8

names constant integer

Device connecting a computer to a local area network (LAN).

network interface card (NIC) • LAN is commonly used in business, universities, & gov't organizations. A typical type of NIC, called 10BaseT, can transfer data at 10 Mbps.

String input

next() nextLine()

Members can use all four access levels:

public, protected, default, private.

A class with default access can be ...

seen only by classes within the same package.

-16 bits Range: -32,768 to 32,767 No rules

short

Origin

the point (0,0) in a coordinate system

vocabulary

the set of all of the words and symbols in a given language

Java Virtual Machine (JVM)

the software that Java runs on allowing to to be architecturally neutral

A single 'abstract' method in class means ...

the whole class must be abstract.

Local Variables

variables declared within a method or, more accurately, within a code block. These variables can only be used within the code block scope. They aren't initialised by default, so should be initialised by hand !.

PrintWriter out = new PrintWriter("output.txt");

writes output to a file "output.txt"

import x.y.z

x - overall name of package, y - name of package subsection, z - name of particular class in subsection

Postincrement

x++ "Give me x, then increment"

An increment operator

x+++

Class constant

A named value that cannot be changed. A class constant can be accessed anywhere in the class. (It's scope is the entire class).

Nested classes/inner classes

A nested class is a class that is a member of another class. Example: class EnclosingClass{NestedClass}}

What must come after a declared class?

A pair of brackets that contain the method(s) between them

What do you attach to a method if it requires more information?

A parameter that represents additional information: Method: public static double _maximum_(Parameters(double x, double y, double z))

Relative Path

A path that is not anchored to the root of a drive. Its resolution depends upon the current path. Example ../usr/bin.

null

A value of no value

Literal

A value represented as an integer, floating point, or character value that can be stored in a variable.

A class that cannot be instantiated is called a/an ____. A) Abstract class. B) Anonymous class. C) Concrete class. D) Non-inheritable.

Ans: A Section Ref: Special Topic 10.1

What is the difference between composition vs aggregation.

Composition, is when a type is composed of another type, the complete existence of that component type's objects is controlled by the composing type's object; The components are uniquely bound to it and cannot be changed by any outside object. Aggregation, the component elements exists outside the collection, can be changed by other classes, and may even be components of other aggregates.

String concatenation

Combining several strings into a single string, or combining a string with other data into a new, longer string. Done by System.out.println("Words" + variable + "more words");

Java is Pass-by-value (cont)

Compatible type: you can pass an argument of smaller data type to a parameter of larger data type. So, you can pass a byte where an int is expected.

A software program that translates source code (e.g., Java source code) into a machine language program.

Compiler

Chapter 12: The view uses the ____________ to implement the user interface, which usually consists of nested components like panels, frames and buttons.

Composite Pattern

{}

Defines a block of code

In particular, exceptions of either the ______or ____________ class or any of their subclasses do not have to be listed in your throws clause.

Error & RuntimeExceptions

What is a main method for?

For letting your program run.

cobol

High level language for business data processing

fortran

High level language for scientific computation

C

High level language used to write application and system software

Java Program

Is a sequence of statements(smallest executable unit) that have to be formed in accordance with a predefined syntax.

syntax

Language rules that govern how words can be combined to form meaningful phrases and sentences

*=

Multiply and assign operator

Chapter 12: The model (MVC) makes use of the _______ so that it can keep observers updated yet stay decoupled from them.

Observer Pattern

What is assumed to be true when a method is called

Precondition

Stores a specific type of value

Primitive data types

Objects

Programs that you create. These can be thought of as physical items that exist in the real world.

What is the result of the conditional expression above?

Result is the conditional expression is EXPRESSION1 if BOOLEAN-EXPRESSION is true; otherwise the result is EXPRESSION2

3

Result? 2 + 1

String method length()

Returns the number of characters in a string, counting from 1. E.g. "12345".length() would return 5. An empty String has length 0.

draw an image, starfield.jpg at (0, 0)

StdDraw.picture(0, 0, "starfield.jpg");

read double

StdIn.readDouble();

read an integer

StdIn.readInt();

std print

StdOut.println();

Define an array

Stores a fixed-size sequential collection of elements of the same type .

Value: group of characters -Capitalize the S, enclose value in " "

String

What non-numeric data type can have class operations preformed to it?

String

0 or more characters surrounded by double quotes?

String (always capital "S")

Example of variable declaration and explanation.

String firstName; Start with data type then variable name. Must end with the ";".

nextLine()

String of words

%

Take remainder operator

Hash Code

Tells where in the array the data item should be stored.

Do While Loop

Tests the condition at the end of each repetition of a section of a program.

When defining a method, the _____ parameter is a name used for the calling object.

"this."

division operator

/, fourth highest precedence, left to right association

What symbols are used to make comments in Java? (Both single and block comments)

// and /* */

long

4 bytes, stores long integer values

What is the end of file indicator for windows? and for UNIX/Linux/Mac OS X?

<Ctrl> z <Ctrl> d

OOP Program

A group of objects that work together to get something done.

Maps

supports the ability to add and retrieve items from a collection using a key value pair. The key (K) is the lookup identifier and the value (V) is the item being looked up. The methods for inserting/retrieving items in/out of the Map are put(...) and get(...). General accounts - For general public use. Business accounts - For commercial organizations. Nonprofit accounts - For nonprofit organizations. The above account types can be abstracted as a Java enum (enumerator): enum AccountType {general, business, nonprofit}; Each user is allowed to have one account of each type. Accounts for a given user could be contained in a Map data structure where the key for each account is one of the above enum values (general, business, or nonprofit) as shown below: Account generalAccount = new Account(); Account businessAccount = new Account(); Account nonprofitAccount = new Account(); //... Map<AccountType, Account> accountsMap = new HashMap<AccountType, Account>(); accountMap.put(AccountType.general, generalAccount); accountMap.put(AccountType.business , businessAccount); accountMap.put(AccountType.nonprofit , nonprofitAccount); Retrieval of the accounts from the map is then achieved with the key: Account generalAccount = accountMap.get(AccountType.general); Account businessAccount = accountMap.get(AccountType.business); Account nonprofitAccount = accountMap.get(AccountType.nonprofit); In summary, the key is used to place values in the map and also to retrieve values from the same map. advantage, code readily accommodates additional account types. simply add to the enum type: enum AccountType {general, business, nonprofit, government, education};

How do you make a Switch statement?

switch (var) { case 1://if var = 1 //What happens break; case 2 ://if var = 2 //What happens break; default://Otherwise //What happens break; }

throws FileNotFoundException

terminates main if FileNotFoundException occurs

inheritance

the ability to create classes that share the same attributes and methods of existing classes but with more specific features

Escape character (\)

used in codes to represent characters that cannot be directly typed into a program

Data encapsulation

The separation of the representation of data from the applications that use the data at a logical level; a programming language feature that forces information hiding.

Token:

The smallest individual unit of a program written in any programming language.

Methods

Things an object does are and represents the behavior of an object.

Instance Variables

Things an object knows about itself and represent the state of an object.

Error

This Class indicates issues that an application should not try to catch. Subclass of the class Throwable.

Why is the method "main" Declared static?

This allows the JVM to invoke "main" without creating an object of the class

prepcode, test code and real (Java) code)

Three things to write when designing a new class

String comparing a to b

a.compareTo("b");

Abstract Classes & Interfaces

abstract class - class that is never intended to be instantiated as an object. Its purpose is to serve as a base class that provides a set of methods that together form an API. classes that inherit the abstract class can override its base behavior as necessary. Because the derived classes can be instantiated, they are referred to as concrete classes. This combination of an abstract base class and one or more concrete derived classes is widely used in industry and is known as the "Template" design pattern. class is identified as being abstract by pre-pending the keyword "abstract" to the class definition. package domain; public abstract class LibraryItem { } abstract keyword prohibits a LibraryItem from being instantiated with the "new" keyword. When a class is denoted as abstract, it typically means that one or more of its methods are also abstract, which implies they have no implementation. method is declared to be abstract by using the "abstract" keyword: public abstract boolean validate(); there's no {...} following the signature; rather, a semicolon is present. method must not have an implementation following its signature, the enclosing class must be declared to be abstract. implementation of validate() in one of the concrete derived classes: Book. package domain; public class Book extends LibrarayItem { public boolean validate() { if (id <= 0) return false; if (title == null || title.equals("")) return false; if (author == null || author.equals("")) return false; if (pages <= 0) return false; return true; } } another technique for declaring "abstract" interfaces by way of the "interface" keyword: package domain; public interface IValidator { public boolean validate(); } interface construct is used to capture zero or more method signatures without specifying their implementation details. methods enclosed within an interface definition must be "abstract" in the sense that they must not provide an implementation (i.e., {...}), but the abstract keyword is not necessary. interfaces are implemented in classes with the "implements" keyword. User and Login are not defined as abstract since implementations are provided for the validate() method. package domain; public abstract class LibraryItem implements IValidator { public abstract boolean validate(); } uniform interface for validating objects. package domain; public class User implements IValidator { public boolean validate() { } } package domain; public class Login implements IValidator { public boolean validate() { } } while Java does not support multiple class inheritance , it does support the implementation of multiple interfaces in a single class. To serialize Login objects across a secure network Login class needs to implement the Serializable interface. package domain; public class Login implements IValidator, Serializable {...} Serializable does not contain any methods, known as a Marker Interface. Marker interfaces, used to "mark" classes (and hence their objects) as "one of those," but without any additional methods. In summary, interface constructs are used to separate interface abstractions from implementation details.

Objects...

are instances (instantiations) of classes, as objects are created, the properties that are defined in the class template are copied to each object instance and assigned values. Thus, each object has its own copy of the class properties

When you know how many times you want to repeat a loop

When do you choose for loops over while loops?

When can you not use a (while) statement instead of a (for) statement? How does it differ?

When the (while) statement has an increment after a continue statement, it is different than a (for) statement. they differ in execution.

Mixing types

When you use multiple data types, Java will convert the simpler forms to the more complex ones. Example: 2 * 3.6 will be evaluated as 2.0 * 3.6, where both objects are doubles.

double d = in.nextDouble();

declares and inputs a real value (floating point #)

Chapter 12: These patterns work together to ______ the three players in the MVC model, which keeps designs clear and flexible.

decouple

access specifier

defines the circumstances under which a class can be accessed and the other classes that have the right to use a class

Are there standard Java arrays built into the Java language?

Yeah, hell Yeah lol there standard Java arrays are built into the Java language.

What are some examples of these class relationships?

dependency - concat method of the string class - str3 = str1.concat(str2); Aggregation - A car is an aggregation of objects (wheels, engine, etc)

semantic error

a logical error, for example if you use the correct word in the wrong location

short hand a = a + 1;

a++;

Constant definition

final typeName variableName = expression;

What is the goal of testing?

find errors, fix them, improve quality to discover problems assess quality of the evolving system

-32 bits Range: -big to big -Must put an f at the end of the value EX: 98.6f; <--- f won't print

float

For loop structure

for ( <initialization>; <continuation test>; <update>) { <statement>; ... <statement>; }

The "for each" loop

for (Type variable: collection) statement;

System.out.println("fun\tny"); prints out

fun ny

System.out.println("funny"); prints out

funny

array.length

gives the length of the array (no parentheses!)

public static double cubeVolume (double sideLength)

header for method

Only setters should update these.

instance variables

declare a as an int

int a;

Declare & Initialize a variable

int n = 5;

Declare a variable

int n;

How could you define an integer named num and initialize it to 394?

int num = 394;

1. Define a variable that = to ten. 2. Create a while loop that prints you name tens time.

int ten = 10; while(copies > ten) { System.out.println("Reynald"); copies --; }

1. Create an Array called 'number' w/ 3 slots 2. Write out the 2nd number

int[] numbers = new int[3];

Literals

items whose values do not change, like the number 5.0 or the string "Java"

Keyboard integer input

keyboard.nextInt();

LinkedList: peek methods

list.peek(); //peeks head list.peekLast(); // peeks last element

&&

logical AND operator returns true if both its operands are true. E.g. 'boolean isCup = hasHandle && holdsTea;'. Otherwise returns false.

||

logical OR operator returns if any of its its operands are true (including both). E.g. 'boolean isCool = hasCar || hasBand'.

^

logical XOR, effectively returns true if both its operands are different (ie. a mix of true and false) but returns false if they are the same. E.g. 'boolean isHetero = likesWomen ^ likesMen;'.

Chapter 1: Patterns are proven

objectoriented experience

Method overloading

occurs when a class contains more than one method with the same name. Within a class, methods can have the same name if there's difference: The number of parameters. And/or the type parameters. And/or order of parameters. The determination of which overloaded method to invoke is a compile-time decision; hence, it is sometimes referred to as static binding. Library library = new Library(); Book book = new Book(); library.add(book); User user = new User(); library.add(user); Notice that the statement library.add (book) is clearly targeting the add (Book) method because of the parameter data type, Book. Similarly, the statement library.add(user) is clearly targeting the add(User) method because of the parameter data type, User. Since these decisions can be determined at compile time, the binding is said to be static.

{ }

opening/closing braces; encloses a group of statements, such as the contents of a class or a method

( )

opening/closing parentheses; used in a method header

*

operator for multiplication

ad hoc polymorphism

overloading and coercion are two special kinds of ad-hoc polymorphism

to swap values of integers you need a...

place holder

&&

"And" operator

Integer value: 48

'0'

'abstract' methods cannot be ...

'private' or 'final'.

Interface methods are by default ...

'public' and 'abstract' - explicit declaration of these modifiers is optional.

Mutator method

(Setter) - changes the value of a private field of an obj.

LAN

(adj.) drooping; without energy, sluggish

Syntax Error

- Compile error - Mistake detected by the compiler - Generally a type - ^ will indicate where the mistake is (always go up)

Double

- Name for a floating-point integer (decimals) Ex: 10.1, 9.0

What is the Comparable interface?

- defined in java.lang package - contains only one method, compare to -takes an object as a parameter and returns an integer - mechanism to compare one object to another - integer returned is negative if first object is less than 2nd - 0 if they are equal - positive if greater

Life Cycle - Suspended

-A thread is waiting for an outside event to occur...-Common events: other threads complete execution, or if a thread receives a resume from another thread

Life Cycle - Wait

-Thread can be put into this state by calling wait()...-Will stay in a pool of waiting threads until a notify or notifyAll method is called by another thread

What are checked & unchecked exceptions.

1) Checked Exception is required to be handled by compile time while Unchecked Exception doesn't. 2) Checked Exception is direct sub-Class of Exception while Unchecked Exception are of RuntimeException.

Class visibility revolves around whether code in one class can:

1) create an instance of another class 2) extend (or subclass) another class 3) access methods and variables of another class

Name 3 reasons why favor composition over inheritance

1. Almost all inheritance can be rewritten 2. Less about modeling the real world and more about modeling interactions in a system and roles and responsibilities 3. Inheritance is difficult to maintain V52

What are the rules for forming a structured program?

1. Begin with the simplest activity diagram { @->(action state)->(@)} 2. Any action state can be replaced by two action states in sequence. (A.K.A stacking rule) 3. Any action state can be replaced by any control statement. (A.K.A the nesting rule) 4. Rules 2 and 3 can be applied as often as you like and in any order.

Describe 2 classes can have.

1. Is a - inheritance 2. Has a - composition / aggregation V47

Name to things about strings in Java.

1. Treated like a primitive type (can be assigned w/o the New keyword) but it's an object 2. They're immutable (can't be changed). If you give a string a different value, it create an new string in memory. Java Fundamentals - v22

int

4 bytes, stores integer values

float

4 bytes, stores less precise floating-point numbers

Moden can transfer speed up to ______

56,000 bps (bits per second).

long

64 bit integer

Nested Classes

A class written inside another class Enclosing Classes The class that the nested class is nested in

ARPANET

A computer network developed by the Advanced Research Project Agency (now the Defense Advance Research Projects Agency) in the 1960s and 1970s as a means of communication between research laboratories and universities. ARPANET was the predecessor to the Internet.

boolean

A data type of logical values (true, false).

Method

A group of programming statements given a name.

b()

A method called b

What is a requirements document?

A precise specification of what the software should do.

this Reference

A reference variable that lets an object refer to itself

Escape Sequence

A sequence used to represent special characters.

The Java Runtime Environment (JRE)

A set of libraries that define the application programming interface (API) of the Java language. The JRE also contains the JVM application.

Programming language:

A set of rules, symbols, and special words.

Complete Code Coverage

A set of test in which every line in a program is executed at least once. ex: { int a, b; a=2; b=5; if (a<0) && (b>2) { System.out.println("Example"); } else { System.out.println("Example"); } } this insures quality assurance

Data type:

A set of values together with a set of operations.

Arithmetic Overflow

A situation that arises when the computer's memory cannot represent the number resulting from an arithmetic operation. ex: when an error occurs when trying to do an arithmetic problem when the final result number is too large for the primitive storage type to store. Also, Data too large for the data type chosen

Operator

A special symbol (+, *, ++, --) that is used to indicate an operation to be performed on one or more values. Study the order of operations in Java!!!

Variable

A storage place that can hold information, which may change.

Hashing

A technique used to efficiently store and retrieve data in an array.

Static (Class) Variable

A variable shared among all the objects in a class. If the value changes in one object, it changes in all of the others.

+=

Add and assign operator

Hash Table

An array used for hashing.

Attributes and Behaviors

An object contains these two things.

General Java variable naming conventions would suggest that a variable named NICKEL_VALUE would most probably be declared using which of the following combinations of modifiers? A) public void final B) public static final double C) private static double D) private static

Ans: B Section Ref: 8.2

Why can't Java methods change parameters of primitive type? A) Java methods can have no actual impact on parameters of any type. B) Parameters of primitive type are considered by Java methods to be local variables. C) Parameters of primitive type are immutable. D) Java methods cannot accept parameters of primitive type.

Ans: B Section Ref: Quality Tip 8.3

Fill in the if condition that will only access the array when the index variable i is within the legal bounds. if (____________________) data[i] = value; A) 0 <= i < data.length() B) 0 <= i && i < data.length C) 0 <= i < data.length D) 0 <= i && i < data.length()

Ans: B Section Ref: Section 7.1 Arrays

What is the type of a variable that references an array list of strings? A) ArrayList[String]() B) ArrayList<String>() C) ArrayList<String> D) ArrayList[String]

Ans: C Section Ref: Section 7.2 Array Lists

To create a subclass, use the ____ keyword. A) inherits B) implements C) interface D) extends

Ans: D Section Ref: 10.2

The ____reserved word is used to deactivate polymorphism and invoke a method of the superclass. A) this B) my C) parent D) super

Ans: D Section Ref: 10.3

Engaging in OOP

Breaking down computer programs in the same way a pie chart is broken down.

Class Interface Implementation

By providing method implementation for each of the abstract methods defined in the interface. Uses reserved word -implements- followed by the interface name in the class header.

string.length

Calculates the length of a string.

Public modifier

Can be applied to a class and/or individual data members and methods within a class; indicates that the given item is accessible across package boundaries, the following class and method are both accessible outside the package in which they're defined. package domain; public class Book { public void checkOut() { } }

instruction

Commands that the processors understand

//

Comment (??) ignore the elephant

Casting

Converting information from one form to another.

Declaration

Creating a variable of the type that you want to use, reserves a memory location for that variable.

Overloading the method?

Creating multiple definitions for the same method name, using different parameter types

What kind of value and how much will be stored?

Data Type

Primitive Data Types

Eight commonly used data types.

Logical Operator

Either of the logical connective operators && (and), || (or), or ! (negation) ex: (in use) (exsampleClassA >= 0 || > exsampleClassB), or (exsampleClassA >= 0 && > exsampleClassB) or (exsampleClassA >= 0! > exsampleClassB)

Floating Point Literals

Either written with a whole and fractional part separated by a dot '45.98' or with scientific notation which allows significant digits that are multiplied by a power of 10 specified after the character 'e'. 'double speedOfLight = 2.998e8'. It seems that both double and float use the same literals, unlike C++.

Inheritance

Enables one object to inherit behavior and attributes from another object.

What are Encapsulation, Inheritance and Polymorphism?

Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions.

Double var = input.nextDouble();

Establishes value inputed into scanner as a variable

Logical Expression

Evaluates to either 'true' or 'false' (boolean literals). Can be used for conditional processing in flow control structures.

Class definition

Every Java program is a ___________________________.

Predefined Java classes

Example of 2: Object class & String class

Exercise: 1. Create a printer class w/ a modelNumber property & a method to print that model #. 2. From you main method, assign a value to the modelNumber & invoke the Print() method.

Exercise. v(32)

Data Type Sizes

Fixed in Java, to ensure portability across implementations.

Applet

Graphical Java program that runs in a web browser or viewer. To run one must have an HTML file with an applet tag.

>

Greater than

>=

Greater than or equal to

switch selector value

Has to be a constant value (usually a literal) that is compatible with the argument type. The statements within the case are executed if it is logically equivalent to the argument '=='.

switch argument

Has to be an expression of type int, char, short or byte. Notably not float, double and long (too imprecise or large).

Time Efficiency

How long it takes an algorithm to run.

encapsulation

I prefer my instance variables private.

-Must start with a letter -Can contain letters, numbers, and underscore character -Cannot contain spaces -Cannot contain reserved (key) words

Identifiers (name) Rules

Constants

Identifiers that always have the same value.

' '

Identifies a string of text to be presented to the user

Name the variable NOTE: starts with lower case, new word starts with capital letter (numDays)

Identity

switch fall-through

If a 'break' keyword is missing after a case, processing will continue through to the next case and until it reaches a break statement or the end of the switch statement.

What is a primitive type in Java?

In java, we have primitive types & objects. Primitive types hold the actual value in memory. Object hold references in memory.

What is the perferred method of storing datat in an array?

In most cases, the ArrayList is the preferred method of storing data in an array.

2.10.4 a. 0x01004020 " b. 0x8E690004 2.10.5 a. R-type b. I-type 2.10.6 a. op=0x0, rd=0x8, rs=0x8 , rt=0x0, funct=0x0 b. op=0x23, rs=0x13, rt=0x9, imm=0x4

In the following problems, the data table contains MIPS instructions. You will be asked to translate the entries into the bits of the opcode and determine the MIPS instruction format. a. addi $t0, $t0, 0 b. sw $t1, 32($t2) 2.10.4 [5] <2.4, 2.5> For the instructions above, show the binary then hexadecimal representation of these instructions. 2.10.5 [5] <2.5> What type (I-type, R-type, J-type) instruction do the instructions above represent? 2.10.6 [5] <2.5> What is the binary then hexadecimal representation of the opcode, Rs, and Rt fields in this instruction? For R-type instructions, what is the hexadecimal representation of the Rd and funct fields? For I-type instructions, what is the hexadecimal representation of the immediate field?

2.10.1 sw $t3, 4($s0) lw $t0, 64($t0) 2.10.2 a. I-type " b. I-type 2.10.3 a. EOB0004 b. 8D080040

In the following problems, the data table contains bits that represent the opcode of an instruction. You will be asked to interpret the bits as MIPS instructions into assembly code and determine what format of MIPS instruction the bits represent. a. 0000 0010 0001 0000 1000 0000 0010 0000two b. 0000 0001 0100 1011 0100 1000 0010 0010two 2.10.1 [5] <2.5> For the binary entries above, what instruction do they represent? 2.10.2 [5] <2.5> What type (I-type, R-type, J-type) instruction do the binary entries above represent? 2.10.3 [5] <2.4, 2.5> If the binary entries above were data bits, what number would they represent in hexadecimal?

Where is the Scanner Class stored ?

In the java.util package. import java.util.Scanner;

operating system

Interface between user's program and hardware providing a variety of services and supervision functions

Just-in-Time Compilation

JIT - Technique used to translate byte code into machine language - Once program is saved, computer remembers it and program will run faster

Java Virtual Machine

JVM - Program needed to run Java byte code - Comes with Mac - Acts like a computer

Modifier

Java keyword • Specifies the properties of data, methods, & classes + how they can be used. EX: public, private, & static.

Prompt the user

Java: System.out.println

arc cos x

Math.acos(x);

arc sin x

Math.asin(x);

By Value

Objects passed to a method "by value" meaning that the current value of the actual parameter is copied to the formal parameter in the method header

;

Semicolon

method

Specifies the actions of an object.

set x and y window scale to -R , R

StdDraw.setXscale(-R , R); StdDraw.setYscale(-R, R);

draw "text" at (x, y)

StdDraw.text(x, y, "text");

Print statement

System.out.println("");

While Loop

Tests the condition at the beginning of each repetition of a section of a program.

2.2.1 a. add f, f, f add f, f, i b. add f, j, 2 add f, f, g 2.2.2 a. 2 b. 2 2.2.3 a. 6 b. 5

The following problems deal with translating from C to MIPS. Assume that the variables g, h, i, and j are given and could be considered 32-bit integers as declared in a C program. a. f = g - f; b. f = i + (h - 2); 2.2.1 [5] <2.2> For the C statements above, what is the corresponding MIPS assembly code? Use a minimal number of MIPS assembly instructions. 2.2.2 [5] <2.2> For the C statements above, how many MIPS assembly instructions are needed to perform the C statement? 2.2.3 [5] <2.2> If the variables f, g, h, and i have values 1, 2, 3, and 4, respectively, what is the end value of f?

Polymorphism

The idea that we can refer to objects of different but related types in the same way.

Operator Precedence

The rules that govern the order in which operations are done.

java.util.*;

To work with collections framework, event model, and date/time facilities.

subclasses of the RuntimeException and Error classes and are usually thrown by the Java runtime itself.

Unchecked exceptions

String operator '+'

Used for concatenation. If either operand is a String type, both operands will be turned into strings, concatenated and then added to a newly created String object. E.g. String aString = "Jon" + 2; would output 'Jon2'.

Initialization

When you first store something in a variables memory location.

for(i=10; i > 5; i++){ System.out.println(i); }

Write an endless for loop where i=10

More than One Parameter

You can send more than one thing to a method: first argument is passed to the first parameter, second argument to the second parameter, and so on.

developmental environment

a set of tools that help you write programs by providing features such as displaying a languages keywords in color

short hand a = a - 1;

a--;

Graphical user interfaces (GUIs)

allow users to interact with a program in a graphical environment

Type casting

allows one data type to be explicitly converted to another

Default members can be accessed only by ...

classes in the same package.

hardware

computer equipment such as a keyboard

String s = in.nextLine();

declares and inputs a line (a string of characters)

Create a program that computes the area of a number and prints it out to the screen

double radius; double area; radius=20; area= radius * radius *3.14; System.out.println(area);

HashMap<String,String>: iterate and print keys/values

for (String key : loans.keySet()) { System.out.println("key: " + key + " value: " + loans.get(key)); }

if else structure

if (thisEnter > 10) system.out.println("yep>10"); else system.out.println("nope<10"); and

if statement (many commands)

if (true) { }

\n

indicates a newline character

when writting multiple catch clauses you should always start with ______

more specific subclass exceptions and end with more general superclass exception catches (because if you start with a superclass exception catch you wont know what the specific exception was.

ArrayList: replace item at index i with new item

myArr.set(i, newItem);

-

operator for subtraction

source code

programming statements written in a high level programming language

syntax

rules of a computer language

;

semicolon; marks the end of a complete programming statement

//comment

short comments

Math.sin(x)

sine of x (x in radians)

Statements

smallest executable unit in Java, each one ends in a semicolon.

Are members of a class static or non static?

they can be static or non static. static members belongs to the class itself, while nonstatic members are associated with the instance of the class (fields and methods)

escape character

used when including 'special characters' in string literals

What are static variables?

variables local in a static method

The amount of space bw pixels. If higher/lower = better resolution

• Dot pitch • Smaller the dot pitch → better the display.

String combination identifier

"+"

Integer value: 65

'A'

switch...case form

'switch ([argument]) { case [selector]: [statements;] break; default: [statements;] break; }'. Where many cases can be written and the 'default' case is selected if none of the other cases are selected.

Statement

- Sentence in the program Ex: System.out.println("Hello World");

Life Cycle - Sleeping

-Thread has issued a sleep method call...-Will sleep AT LEAST as long as the time requested (may be longer due to waiting to become Active)...-Once the sleep method is over, thread enters the Runnable state

Thread of creation

1) Create class that extends Thread 2) Override the run() method -Method that the thread executes 3) Create an object of this class 4) Call the start() method -start() invokes the run() method -You choose when the thread starts -Doesn't start when object is created

Constructor vs Method

A Constructor is a member function of a class that is used to create instances of that class. It has the same name of the class itself, has no return type and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, return type (which may be void), and is invoked using the dot operator.

String

A collection of characters. Surrounded by double quotation marks.

Source file:

A file containing the source code, having the file extension .java.

Array

A group of related variables that share the same type and are being arranged.

Variable

A location in memory used to hold a data value.

Nested Loop

A loop as one of the statements in the body of another loop. Random rnd = new Random(); while (true) { System.out.println(rnd) if(true){ } System.out.print(rnd) }

Truth Table

A means of listing all of the possible values of a Boolean expression ex: (based off of the code from page 246) Look up for more detail: Ex:

Variable:

A memory location whose content may change during program execution.

Computer program:

A sequence of statements whose objective is to accomplish a task.

Casting Float Types to Integral Types

Always requires a cast. Will result in the loss of the fractional part of the number.

...

An ArrayList object can have any element in it removed and will automatically move the other elements.

Logical Invariant

An assertion that expresses a relationship between variables that remains constant throughout all iterations of the loop. ex: for(int j=0;j<=10;j++ ) { J++ } J in this case would change and check a counter which will add 1 to J and check if J is less than or equal to 10.

Loop Variant

An assertion whose truth changes between the first and final execution of the loop. ex: During a loop when executed Such as a for loop when a value has matched the final requirement either by making a value true or proving it false.

Off-by-one Error

An error that occurs because indexes begin at zero and not one.

Run-time error

An error that occurs when a program asks the computer to do something that it considers illegal, such as dividing by 0

object

An individual instance of a class. An object can only exist during runtime.

What is the purpose of this algorithm? double total = 0; for (double element : data) { total = total + element; } A) Computing the sum. B) Finding a value. C) Locating an element. D) Counting matches.

Ans: A Section Ref: Section 7.6 Common Array Algorithms

What is the purpose of this algorithm? for (BankAccount a : accounts) { if (a.getAccountNumber() == accountNumber) return a; } return null; A) Finding a value. B) Counting matches. C) Computing the sum. D) Inserting an element.

Ans: A Section Ref: Section 7.6 Common Array Algorithms

Which of the following represents the hierarchy of GUI text components in the hierarchy of Swing components? A) JTextField and JTextComponent are subclasses of JTextArea. B) JTextArea and JTextComponent are subclasses of JTextField. C) JTextField and JTextArea are subclasses of JTextComponent. D) JTextField, JTextArea, and JTextComponent are subclasses of JPanel.

Ans: C Section Ref: 10.1

Which of the following is true regarding subclasses? A) A subclass inherits methods from its superclass but not instance variables. B) A subclass inherits instance variables from its superclass but not methods. C) A subclass inherits methods and instance variables from its superclass. D) A subclass does not inherit methods or instance variables from its superclass.

Ans: C Section Ref: 10.2

Consider the following code snippet: public class Demo { public static void main(String[] args) { Point[] p = new Point[4]; p[0] = new Colored3DPoint(4, 4, 4, Color.BLACK); p[1] = new ThreeDimensionalPoint(2, 2, 2); p[2] = new ColoredPoint(3, 3, Color.RED); p[3] = new Point(4, 4); for (int i = 0; i < p.length; i++) { String s = p[i].toString(); System.out.println("p[" + i + "] : " + s); } return; } } This code is an example of ____. A) overloading B) callback C) early binding D) polymorphism

Ans: D Section Ref: 9.3

When an array is created, all elements are initialized with ___. A) zero B) array elements are not initialized when an array is created C) null D) a fixed value that depends on the element type

Ans: D Section Ref: Section 7.1 Arrays

~

Bitwise Not operator

Arithmetic Expression Type

Depends on the types of the variables or literals used in the expression. E.g 3/4 would be 0, integral, and the fractional part discarded. However if an expression mixes integrals and floating points, the expression will return a floating point type.

matrix.length pixels.length

Example of getting the number of rows

Relational Operators and Floating Points

Floating point values have limited precision, they are approximations, therefore using relational operators requires care (e.g. might be best to check within a precision range).

1.3.4 IPC = 1/CPI = No. instr./(time x clock rate) IPC(Pl) = 1.42 IPC(P2) = 2 IPC(P3) = 3.33 1.3.5 Time new/Time old = 7/10 = 0.7. So f new = f old/0.7 = 1.5 GHz/0.7 = 2.14 GHz 1.3.6 Time new/Time Old = 9/10 = 0.9. So Instructions new = Instructions old x 0.9 = 30 x 109 x 0.9 = 27 x 109

For problems below, use the information in the following table. Processor Clock Rate No. Instructions Time a. P1 3 GHz 20.00E+09 7 s P2 2.5 GHz 30.00E+09 10 s P3 4 GHz 90.00E+09 9 s b. P1 2 GHz 20.00E+09 5 s P2 3 GHz 30.00E+09 8 s P3 4 GHz 25.00E+09 7 s 1.3.4 Find the IPC (instructions per cycle) for each processor. 1.3.5 Find the clock rate for P2 that reduces its execution time to that of P1. 1.3.6 Find the number of instructions for P2 that reduces its execution time to that of P3.

- Left alignment 0 show leading zeroes + show a plus sign for positive numbers ( enclose negative numbers in parentheses , show decimal separators ^ convert letters to uppercase

Format flags (printf)

d decimal integer f fixed floating-point e exponential floating-point (very large or very small values) g general floating-point s string

Format types (printf)

What syntax error should you be aware of when entering parameters for a method?

If you set two variables as the same type, but don't use two type indentifiers then it creates a syntax error. You should always use a type identifier for each variable: double x, y = NO double x, double y = YES

What are the 3 selection statements? And the 3 Repetition Statements?

If, If...else, and Switch While, do...while, and for

import java.util.Scanner;

Import the ability to use a scanner from database

selection sort

In _____________________ sort the program scans through the list from the first element to the last element and identifies the smallest element in the list (keeping track of that element's index). That element is swapped with the first element. The process repeats starting with the second element to the last element - swapping the next smallest for the second element. And continues to repeat this on ever smaller list sizes until the last element (and hence largest) is in place.

?

In a ternary operation, if the boolean condition is true, the value after the _ is returned.

2.12.4 a. 17367056 b. 23661772 2.12.5 $t0 , $tl , $0 $tl, 12($t0) 2.12.6 a. R-type, op=0x0, rt=0x9 b. I-type, op=0x23 , rt=0x8

In the following problems, the data table contains hexadecimal values. You will be asked to determine what MIPS instruction the value represents, and find the MIPS instruction format. a. 0x01090012 b. 0xAD090012 2.12.4 [5] <2.5> For the entries above, what is the value of the number in decimal? 2.12.5 [5] <2.5> For the hexadecimal entries above, what instruction do they represent? 2.12.6 [5] <2.4, 2.5> What type (I-type, R-type, J-type) instruction do the binary entries above represent? What is the value of the op field and the rt field?

++

Increment by one

Software

Incudes programs and the data those programs use

Inner & Anonymous Classes

Inner classes are defined within the context of another class. package domain; public class Book extends LibraryItem implements AuthorableItem, PrintedMaterial { BookReader reader = new BookReader(); // .rest of Book definition public String nextLine() { return reader.readNextLine(); } // Note that this is not a "public" class- //only an instance of Book can access the BookReader class BookReader { public BookReader() { } public String readNextLine() { // Implementation of this method. } } // BookReader } // Book Anonymous classes are also inner classes that are defined within the context of another class, but these classes do not have a name, hence the name anonymous. Anonymous inner classes are often used as event handlers in the implementation of graphical user interfaces.

IPv4

Internet Protocol version 4, , Uses a header format that is 20 octets and combined with the TCP segment forms an IP PDU or IP Datagram or IP Packet. The source and destination address field is 32 bits. Is now actually obselete.

IPv6

Internet Protocol version 6, IPv6 An extended scheme of IP addresses, using 128-bit IP addresses, that allows for more IP addresses than current system, IPv4, which uses 32-bit IP addresses.

Command invoking the INTERPRETER to run a Java program from the command line. - vs. invoking the COMPILER

Interpreter → java command Compiler → JAVAC command

In a (for), (while), or, (do...while) statement what does the break statement do? and a continue statement?

It breaks out of the loop using an if statement ' Ex: if (count==5) break; 1 2 3 4 It skips the number defined Ex: if (count==5) continue; 1 2 3 4 6 7 8 9 10

What is a package?

It is a namespace, a name for a group of classes, interfaces and enum types that can be used to distinguish those from other classes, interfaces and enum types of the same name.

What does a UML activity diagram do?

It models the workflow(also called the activity) of a portion of a software system.

pass by value

It really means 'make a copy'.

Package

Items of related functionality, each item in the package has a unique name. Thus, a package is a namespace, where a namespace is a collection of uniquely named items. One of main packages is "java", does not contain any data types, it's used to aggregate other packages that are nested within it. java.applet java.awt java.beans java.io java.util nested package example: java.util.concurrent.locks other nested packages do contain type definitions: - java.util contains the Date class (and other classes) - java.util.concurrent contains the Semaphore class (and other classes) - java.util.concurrent.locks contains the LockSupport (and other classes)

LinkedList: iterate through list of strings and print each one

Iterator<String> iter = list.iterator(); while(iter.hasNext()){ System.out.println(iter.next()); } don't forget: iterators have a remove() function!

Read an int from the Scanner object and store it in an int

Java: Int varx= input.nextint();

<=

Less than or equal to

LinkedHashMap

Like a regular HashMap, except it can remember the order in which elements (name/value pairs) were inserted, or it can be configured to remember the order in which elements were last accessed.

public static void main(String[] args){

Line 2 of program, opens programming block

LinkedList<String>: Instantiation

LinkedList<String> myList = new LinkedList<String>();

A constant value that appears directly in the program

Literal • may be numeric, character, boolean, or **null** for object type.

A variable declared in a method is said to be a ____________________.

Local variable

Define how java classes are connected.

Loosely connected objects that interact with each other.

public static void main(String args[])

Main Method

-All must have one (except apps) -Follows the class, where execution begins -Must h ave { and }

Main method

toUpperCase

Method which converts any String to uppercase equivalent by creating a new String object

-Segments of code that perform some action -Always followed by parenthesis EX: System.out.println("abc") <--- print is the ?

Methods

All objects in a class have the same _______ and same types of _______.

Methods && Instance Variables

Static (Class) Method

Methods that can be called through the class name. An example would be the squared method. By Value Objects passed to a method "by value" meaning that the current value of the actual parameters copied to the formal parameter in the method header

multicore processors

Microprocessors containing several processors in the same chip

-Cannot put a bigger box into a smaller box -Data type on RIGHT side of = has to be less than the type on the LEFT side EX: 64bits = 32bits <---CORRECT EX: 32bits = 64bits <--- WRONG

Mixing Data Types Rules

-short and char are not interchangeable -char is unsigned (only positive values), short has both positives and negatives

Mixing Data Types Rules

*

Multiplication

Extended "if" Statement

Nested selection in which additional "if-else" statements are used in the else option. ex: if(j<=0) { System.out.println("Example"); } else { System.out.println("Example"); if(m<10) System.out.println("Example"); else { System.out.println("Example"); } }

Reason Brackets are missing

Not required for single statement IF statements or Loops.

A literal of a reference variable that does not reference any concrete object.

Null

Reasons to use "long"

Numbers greater then ±2 billion

Logical Operators

Operate on boolean values and can be unary or binary. Often used to combines logical expressions with relational operators.

Precedence and Parentheses

Operations in parentheses are carried out first and can therefore be used by the programmer to control the order in which an expression is evaluated. This is preferable so that anyone using the code doesn't have to remember orders of precedence and it helps avoid obfuscation.

Increment and Decrement Unary Operators

Operators available in postfix and prefix forms. The *postfix version* returns the *old value* of the variable before applying the addition or subtraction of 1. Note that these operators *do change* the variable that the y operate on, as well as returning values for the expression to use. E.g. 'int a = myInt++;' where a will be assigned the old value of the variable and the variable will also be incremented.

high-level language

Portable language composed of words and algebraic expressions that must be translated into assembly language before run in a computer

if...else if... statement

Possible to chain many if..else statements by using 'else if...' statements. In the form 'if(logical_expression) { statements; } else if (logical_expression) { statements; } else { statements; }'. Note that you can have as many 'else if' statements as you like, and you don't have to end with an else code block.

HashSet

Prevents duplicates in the collection, and given an element, can find that element in the collection quickly.

Java Type Categories

Primitive Types & Reference Types. It is possible for the user to create further reference types but there is a limited number of pre-defined Java primitive types.

If an instance variable or method is _____ then it cannot be directly referenced anyplace except in the definition of a method of the same class.

Private

Difference between public, protected and private?

Public: are globally accessible. Protected: are accessible by classes and subclasses. Private: are accessible only from its own class.

What is the code to read input from a user using the Scanner class to create an object to read input from System.in ?

Scanner input = new Scanner(System.in);

Initialize scanner

Scanner keyboard= new Scanner (System.in);

declared scanner class

Scanner myScanner=new Scanner(System.in); System.out.println("Please enter #:");

How to declare variables with the same data type on the same line?

Separate them with commas. ex. int number, salary, hoursWorked; (end with semi-colon)

long totalMilliseconds = System.currentTimeMillis();

Sets total number of milliseconds since midnight, January 1, 1970, as a variable

Selection Sort

Sorts a list of values by successively putting particular values in their final, sorted positions.

else if

Specifies a new condition if the first condition is false

...

Standard Java arrays can be initialized by placing the values that will populate the array in curly brackets. Example: int[ ] myArray = {1,2,3,4}

Char Type

Store single unicode characters (international character set) and can be initialised with character literals enclosed in '. E.g. 'a'.

Command-line Arguments

Stored in an array of String objects and are passed to the main method.

declare and initialize string variables

String itemToCheck; itemToCheck = "";

String declaration

String name = "";

Promotion

Term used when casting a smaller memory type to a larger memory type and therefore a cast is not needed (in the reverse case, a cast is needed).

short-circuit

The && and || are known as _____-________ operators

Chapter 12: ______ is a compound pattern consisting of the Observer, Strategy and Composite patterns.

The Model View Controller Pattern (MVC)

Destination

The converted version of the source in a new form.

Iterator

The counter variable used to control a loop.

CPU

The device that executes the individual commands of a program

what is an enum type.

The enum type is a type defined with the enum keyword that list by name each possible value for the type.

Robust

The state in which a program is protected against most possible crashes from bad data and unexpected values. ex: This is part of the maintenance process of a program. There is no such thing as a perfect bug free program, but programs can be created to the best of their own ability. This can be seen with a theoretical perfect program. It should also include valid error messages for invalid data input

What is the difference between the state and the behavior of a class?

The state of a class consists of the values of its fields. The behavior of a class is defined by its methods.

Explain what Scanner input = new Scanner(System.in); does.

The syntax new Scanner(System.in) creates an object of the Scanner type. The whole line Scanner input = new Scanner(System.in) creates a Scanner object and assigns its reference to the variable input.

Edit, Compile, Run

The three steps to creating a program are ___ (e), ____ (c), and ____ (r).

countryName = countryName.trim();

The trim method returns the string with all white space at the beginning and end removed.

Element Type

The type of values stored in an array.

Data Fields

These fields (46 to 1500 bytes) contain the encapsulated data from a higher layer, which is a generic Layer 3 PDU, or more commonly, an IPv4 packet. , variables you declare with a class, but outside of any method.

return, argument

This can be implicitly promoted.

Exception

This class indicates issues that an application may want to catch. A subclass of the class Throwable.

Object-oriented programming

This language paradigm lets you extend a program without having to touch previously-tested, working code.

Do While Execution

This loop will always execute at least once, even if the conditions are not met.

What are Transient and Volatile Modifiers?

Transient: The transient modifier applies to variables only and it is not stored as part of its object's Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

T or F: The name of a local variable can be reused outside of the method in which it is declared ?

True

True or False, by catching a exception superclass you can also catch any subclass exceptions that are thrown?

True

False

True or False? + and - have higher precendence than *,/, and %

True

True or False? The || won't evaluate the right operand if the left operand is true.

Boolean Values

Type of variable that cannot be used in any Casting.

Prefix Operator

Unary operator that appears before it's operand. E.g. the negation operator '-' which negates the value to it's right. e.g. 'int negative speed = -speed;'

//

Used to comment out a line.

/* */

Used to comment out a paragraph or longer

int

Used to declare and initialize a non fraction interager Ex: int canVolume = 5;

'

\'

\

\\

overloaded

a class having more than one method with the same name

Interfaces cannot extend ...

a class, or implement a class or interface.

method

a group of one or more programming statemetnts that collectively has a name

int

a primitive data type, integer

system software

a program that manages the computer itself -ex.Windows

What is the difference between procedural and object-oriented programs?

a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.

System.out.println("ab\\c"); prints out

ab\c

System.out.println("abc"); prints out

abc

How do you make loops?

for (int i; i < 10; i++) { //Program }

The if Statement

if (condition) statement; else statement;

'abstract' methods are declared, with a signature, a return type, and an optional throws but are not ...

implemented.

Graphics context

in java, an object associated with a component where the images for that component are drawn

What is an interface? Where have we seen these before?

interface - a collection of constants and abstract methods. - a class can implement an interface We have used the Panel interface, and interfaces with our classes - getters/setters

Is the break statement on a switch needed for the last statement/default?

no

displays the sequence of method calls that led to the statement that generated the exception.

printStackTrace()

Applets

programs imbedded in a web page

write and instance field

public double r;

if...else statement

The if statement can be extended to include an alternative code block to be executed if the header argument evaluates to false. For example 'if(isFlying) { flapWings(); } else { closeWings(); }'.

The for Statement

The increment section can perform any calculation: for (int num = 100; num > 0; num -= 5) System.out.println (num); A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance

Attribute

The information that describe the object and show how it is different than other objects.

class hierarchy

The instanceof operator can be used only to test objects (or null) against class types that are in the same _____ ___________

Index/Subscript

The number for each position of a stored array value. Always starts from zero.

Quality Assurance

The ongoing process of making sure that a software product is developed to the highest standards possible subject to the ever present constraints of time and money. ex: The Maintenance part of a program's lifetime. As time goes on software companies try and fix bugs or problems with programs. This can be seen with java. When it was first created it had many security hole many of which have been patched up, making the product closer to perfection.

int [] [] matrix Pixel [] [] pixels

Examples of 2D array declarations

Throwing & Catching Exceptions

Exceptions can be thrown either by the Java API or by your code. To throw an exception examples: throw new Exception(); throw new Exception("Some message goes here"); throw new LoginFailedException("User not authenticated"); Once an exception is thrown, the JVM starts looking for a handler in the call stack to transfer execution of the program. Exception handlers are declared in the context of a try/catch block. Catching Exceptions Java supports the catching of exceptions in what's known as a try/catch block or also known as a try/catch/finally block. Syntax for a try/catch block: try { ... } catch (SomeException e) { ... } The interpretation of the try/catch block is the following: the statements between the try and catch are executed sequentially, and if no exception occurs, then execution continues with the first statement that follows the try/catch block. On the other hand, if an exception occurs while executing the statements between the try/catch, execution transfers to the catch block, and then once the catch block finishes executing, execution continues with the first statement after the try/catch block.

a.b()

Execute a method b which belongs to object a

Loop

This causes a computer program to return to the same place more than once.

Network

(broadcasting) a communication system consisting of a group of broadcasting stations that all transmit the same programs

encapsulation

-is the enclosure of data and methods within an object, this allows you to treat all of an objects methods and data as a single entity -also refers to the concealment of an object's data and methods from an outside source

What are the two meanings of + sign

1 is for additions, the other is for string concatenation operator. System.out.println("Introduction to Java Programming, " + "by Y. Daniel Liang"); or System.out.println("j is " + j + " and 8 k is " + k);

byte

8 bit integer

boolean

A data type that represents a true or false value.

double

A data type that represents decimals.

Platform Independent

A program that does not have to be written for a specific operating system.

Application

A program that runs locally, on your own computer.

Aliases

A reference to an object that is also referred to by another reference. Each reference is an alias of each other.

An object is this type of variable

A reference variable

Fourth-generation language

A report generator is a type of:

What are do loops, while loops, etc.

A while loop is a control structure that allows you to repeat a task a certain number of times. -the loop might not ever run. a do...while loop will run at least once before checking the while. A for loop is useful when you know how many times a task is to be repeated.

J2EE

Acronym for Java 2 Platform, Enterprise Edition.

Statements that describe how a problem is solved in terms of the actions to be executed, & specifies the order in which these actions should be executed.

Algorithm - Helps plan a program before writing code

flow control structures

Allow different segments of code to be executed under different circumstances. Keywords : if...else, switch..case (all selection statements).

Casting

Allows you to convert a data type into another one; you can change a double to an int by typing (int) 3.25.

What are bounded types in Java?

Allows you to restrict the types that can be used in generics based on a class or interface. v60

Machine Language

Also called Machine code is the most basic set of instructions a computer can execute -a low-level programming language

Blocks

Also known as compound statement, are marked by delimiting with braces { }.

Element

An item in an Array.

Which of the following statements about abstract methods is true? A) An abstract method has a name, parameters, and a return type, but no code in the body of the method. B) An abstract method has parameters, a return type, and code in its body, but has no defined name. C) An abstract method has a name, a return type, and code in its body, but has no parameters. D) An abstract method has only a name and a return type, but no parameters or code in its body.

Ans: A Section Ref: 9.1

Objects example illustrated

CLASS Book title: String author: String isCheckedOut: boolean checkOut(): void checkIn(): void If a user checks out 2 books, each of them are assigned the class properties: Book Book title: Call of the Wild title: Gone with the Wind author: J. London author: M. Mitchell isCheckedOut: true isCheckedOut: true class is a type, and objects are instances of those types

1.2.4 2 microseconds from cache==> 20 microseconds from DRAM. 1.2.5 20 microseconds from DRAM ==> 2 seconds from magnetic disk. 1.2.6 20 microseconds from DRAM=> 2 ms from flash memory.

Cache DRAM Flash Memory Magnetic Disk a. 5 ns 50 ns 5 μs 5 ms b. 7 ns 70 ns 15 μs 20 ms 1.2.4 Find how long it takes to read a file from a DRAM if it takes 2 microseconds from the cache memory. 1.2.5 Find how long it takes to read a file from a disk if it takes 2 microseconds from the cache memory. 1.2.6 Find how long it takes to read a file from a flash memory if it takes 2 microseconds from the cache memory.

Hash Function

Calculates the hash code from properties of the data itself.

What does the 'new' key word do here when creating an instance? Printer myPrinter = new Printer();

Calls the default constructor on the Printer class.

Comparing Characters

Characters in Java are based on the Unicode character set Unicode establishes a particular numeric value for each character, and therefore an ordering We can use relational operators on character data based on this ordering For example, the character 'a' is less than the character 'b' because 'a' comes before 'b' in the Unicode character set In Unicode, the digit characters ('0'-'9') are contiguous and in order Likewise, the uppercase letters ('A'-'Z') and lowercase letters ('a'-'b') are contiguous and in order

Relational Operators

Check relationships between values of *the same type* and will be part of a logical expression. Can be used with floating points, integers and characters (including >, <, <=, >=). booleans only use '==' and '!=' which can also be used with other types.

matrix[0].length pixels[0].length

Example: get the number of columns

used to create a subclass for an existing class.

Define the keyword "extends"

/

Division operator

Quick Check: Are the following assignments valid?

Double value = 15.75; Yes, the double literal is autoboxed into a Double object. Character ch = new Character('T'); char myChar = ch; Yes, the char in the object is unboxed before the assignment. Integer i = new Integer(5); int j = i + 3; Yes, the int value in the object is unboxed before arithmetic computation.

int value = matrix [3] [2]; Pixel pixel = pixels[r] [c];

Example: Accessing two elements

for( insert argument here) { insert code here }

For loop

Java Collection Framework

Group of interfaces, classes, and algorithms that together provide a rich set of abstractions for grouping objects. Maps - A collection whose entries are accessed by some unique identifier. Lists - A collection whose entries can be accessed with an index. Sets - A collection whose entries are guaranteed to be unique. Queues - A collection whose entries are ordered, based on some scheme.

4

How many times does HI print?: int x = 3; int y = ++x; for(int a=0; a<y; a++){ System.out.println("HI"); }

List Interface

Implemented by classes that represent an ordered collection of element such as numbers or strings.

:

In a ternary operation, if the boolean condition is false, the value after the _ is returned.

Import the Scanner Class

Java: import java.util.Scanner;//at top of the file

Create a Method called methodX

Java: public static void methodX(){

Concatenating

Joining one string to another string. Also known as pasting.

Object class

Object is base class of all Java classes. All Java classes extend (inherit) class Object either directly or indirectly. these 2 definitions are exactly the same: public class Book {...} public class Book extends Object {...}

A class is a type whose values are ______

Objects

Coercion Polymorphism : ad-hoc

Occurs when a value of one type is implicitly converted to a value of another type when the context requires that other type. ie: 22 + 3.3 it interprets the plus operator as a floating point addition, requiring both operands to be either type float or type double. So it "coerces" the 22 into being 22.0 and then performs the operation

Declare the data type of a variable.

Primitive types are used to declare the data types of variables where a variable is a named memory location. datatype variableName = initialvalue; The following statements illustrate the use of Java's eight primitive data types in variable declarations: char c = 'a'; Boolean succeeded = false; byte age = 0; short index = 0; int ssn = 0; long length = 0; float pi = 3.14159f; double d = 0.0; floating point literals are defaulted to a "double" data type. To compile certain types, such as float, add a suffix to the literal: float pi = 3.14159f;

Integral Types

Primitive types, all signed : byte, short, int, long. Fixed length, regardless of platform. Can all take integer literals. An integer variable can hold the result of an *arithmetic expression*.

assembler

Program that translates symbolic instructions to binary instructions

draw a filled rectangle centered at (x, y) width = w height = h

StdDraw.filledRectangle(x, y, w, h);

draw point at (x, y)

StdDraw.point(x, y);

set pen color

StdDraw.setPenColor();

pen size to 0.05

StdDraw.setPenRadius(0.05);

boolean for empty

StdIn.isEmpty()

Precedence

The binding power of an operator, which determines how to group parts of an expression. -- Multiplicative operators (*, / , %) have higher precedence. -- Additive operators are evaluated from left to right.

Infinite Loops

The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program (Control+C) This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally

multiple instances

The case when there are multiple objects from the same class instantiated at runtime.

The Conditional Operator

The conditional operator evaluates to one of two expressions based on a boolean condition Its syntax is: condition ? expression1 : expression2; If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression The conditional operator is similar to an if-else statement, except that it is an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger May serve as a shortcut for if-else statement

The switch Statement

The general syntax of a switch statement is: The type of a switch expression must be char, byte, short and int (Question 4) You cannot use a switch with a boolean or a floating point value The value of each case must be a constant; it cannot be a variable or other expression You cannot perform relational checks (<, >) with a switch statement A switch statement can have an optional default case at the end The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch

What escape sequence makes the tab character?

\t

Chapter 1: We often try to take what varies in a system and

encapsulate it

Use a multiplication assignment operator to make c=8 when c=2

c*=4

Use a subtraction assignment operator to make c=5 when c=7

c-=2

The 'strictfp' modifier applies only to ...

classes and methods.

Method signature

combo of → name of method + its parameters

if a method might throw multiple exceptions you declare them all in the throws clause separated by ______

commas

method toString()

default behavior is to return the object's fully qualified name followed by the object's hash code. book1.toString(); //returns: Book@1ea2df3 book2.toString(); //returns: Book@1ea2df3 this information is typically not useful, it's common to override toString().

semantics

define the rules for interpreting the meaning of statements

polymorphism

describes the feature of languages that allows the same word or symbol to be interpreted correctly in different situations based off context

Chapter 1: Patterns aren't invented, they are

discovered

/=

divide and assign operator

Comments

explanatory sentences inserted in a program in such a manner that the compiler ignores them

Mixed-mode arithmetic

expressions imvolving integers and floating-point values

If 1 of the operands of an && is false then the expression is _____?

false--- this is also known as the short-circuit AND operator

What is final, finalize() and finally?

final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can't be overridden. A final variable can't change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.

optional 3rd block of code in a try/catch that executes NO MATTER WHAT:

finally{ }

primitive data types

first category of Java variables such as numbers, characters, and Booleans

!

logical NOT operator is unary and returns the opposite of its operand. Ie. if operand is true, returns false and vice-versa. E.g. 'boolean isWoman = !hasBeard;' where isWoman would equal false if hasBeard is true.

-64 bits Range: -big to big No rules

long

length() method

method which counts the number of characters in a String

trim() method

method which removes leading and trailing spaces from a String

'final' is the only ...

modifier available to local variables.

+

operator to concatenate strings

Interface constant declaration of 'public', 'static', and 'final' are ...

optional in any combination.

Chapter 1: Patterns provide a shared language that can maximize the value of your communication with

other developers

'final' methods cannot be ...

overridden in a subclass.

'protected' = ...

package + kids (kids meaning subclasses)

What is the difference between pass by reference and pass by value?

pass by value - the current value of the actual parameter is copied into the formal parameter - java only does pass by value pass by reference - references an object, just looks at the values, cant edit

argument

pieces of information that are sent into a method, usually because the method needs the information to perform its task-arguments always appears within parenthesis

How do you create a method?

public void (method name)((arguments)) { } For example, public void greetYou(String greeting) { //Your program here! }

Given this method below, implements 'continue' or 'break' statement if color is 'green' public void printColors() { String[] colors = new String[] {"red","blue", "green","yellow"}; for (String c : colors) { System.out.println(c); } }

public void printColors() { String[] colors = new String[] {"red","blue", "green","yellow"}; for (String c : colors) { if("green".equals(c)) continue; System.out.println(c); } }

access modifier

public, protected,private

Queue Interface

represents an ordered collection based on some known order: e.g., first in first out (FIFO), last in first out (LIFO, a.k.a. a stack), priority. A subset of the Queue API is shown below (not including the methods inherited from interface Collection). <<interface>> Queue +element() : E +offer(E) : boolean +peek() : E +poll() : E +remove() : E order of the queue is determined by the implementing class. Classes that implement the Queue interface include LinkedList and PriorityQueue. As an example, suppose the Library system solicits user suggestions, and these suggestions need to be processed in a FIFO basis. private Queue suggestions = new LinkedList(); public void addSuggestion(Suggestion suggestion) { suggestions.add(suggestion); } The above method adds the new Suggestion to the Queue. Because the implementing class is a LinkedList, each suggestion is added to the end of the queue.

Declaring Exceptions

required that if a method throws an exception without catching it, the exception must be declared in the method signature to notify users. method that authenticates logins, throws an exception named LoginFailedException without catching it: public bool authenticate(Login login) throws LoginFailedException {...} Any exception that occurs in a method must either be handled (caught) by that method or be declared in its signature as "throws" (see above). method throws (and does not handle) multiple exception types, instead of listing all the exceptions in the method signature, the base exception class Exception can be listed: public bool authenticate(Login login) throws Exception {...} declaration covers all possible exception types, and thus prevents you from having to list the individual exceptions when multiple exceptions can be thrown.

return volume;

return statement that returns the result of a method and terminates the method call

Switch statement

switch (variable you're check against) { case label: code; break; default:

for (initialization; condition; update) { statements }

terminating loop

syntax

the rules for combining words into sentences

What are switch statements?

the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types ex. switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break;

For subclasses outside the package, the protected member can be access only ...

through inheritance.

Why do we use interfaces?

to formally define the way we can edit a class

double blah = (int) (blah + 3)

typecast; change variable type

WAN

undisciplined; unrestrained; reckless

char answer = 'y'

variable answer = y (*single quotes!)

final

variable is defined with the reserved word its value can never change. Ex: final double .canVolume = 0.335;

Assignment

variableName = value;

Importing packages

when classes are in defined in different packages. In order for ClassA, in packageA, to have visibility to ClassB, in packageB, one of three things must happen; either: - the fully qualified name of ClassB must be used, - fully qualified name of ClassB be must be imported with an import statement, - entire contents of packageB must be imported with an import statement. first technique is to use the FQN of the class. The FQN of ClassB is packageb.ClassB. to declare: package packagea; public class ClassA { packageb.ClassB b = new packageb.ClassB(); } better technique is to use an "import" statement: package packagea; import packageb.ClassB; public class A { ClassB b = new ClassB(); } import statements must appear after the package statement, and before the data type (class, interface) definition more efficient technique is to import all the data types from a given package using the * notation: import packageb.*; if multiple packages have classes with the same name, use long way (FQN) of importing package: package1.ClassXYZ xyz = new package1.ClassXYZ()

'protected' members can be accessed by ...

other classes in the same package, plus subclasses regardless of package.

Classes can have only ...

public or default access.

An example of a switch statement:

switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; default: misc++; }

'private' methods can be accessed only by ...

the code in the same class.

'this .' always refers to ...

the currently executing object.

logic errors

when the computer is unable to express an answer accruately

What is the ASCII value of 'A'?

65

Unary operator:

An operator that has only one operand.

Encapsulation?

Data and actions combined into a class whose implementation details are hidden

3

How many times does HI print?: int x = 3; int y = x++; for(int a=0; a<y; a++){ System.out.println("HI"); }

Inheritance

How one class can be created from another.

Round to the largest integer not greater than number input?(round down)

Math.floor(#)

Two-Dimensional Array

Rows and columns.

Array: convert from Collection strs to Array

String[] arr = new String[strs.size()]; strs.toArray(arr);

Class

The data type of an object

Before you implement the methods

When do you write test code?

When naming variables, what is camel case?

When the words following the first word having a captial first letter: alphaQuadron

"

\"

What does /* suggest

a comment

literal string

a series of characters that will appear in the output exactly as entered, must be in quotation marks

Local (method, automatic, or stack) variable declarations cannot have ...

access modifiers.

'static' methods do not have direct ...

access to non-static members.

Instance Field Declaration

accessSpecifier class ClassName { accessSpecifer fieldType fieldName; }

Class Definition

accessSpecifier class ClassName { constructors methods fields }

Method Definition

accessSpecifier returnType methodName(parameterType parameterName, . . .) { method body }

A 'protected' member inherited by a subclass from another package is not ...

accessible to any other class in the subclass package, except for the subclass' own subclasses.

if your method has been declared with a throws clause, don't forget to:

actually throw the exception in the body of your method using the throw statement.

+

add operator

friends.add (i, "Cindy"); String name = friends.get(i); friends.set(i, "Harry"); friends.remove(0);

adds element to arrayList at pos i (w/out i will add element to end); obtains element at i; redefines element at i as "Harry"; removes element

Alphabetic characters that can be stored as a numeric value?

char

Escape Sequence

characters marked by a backslash \ that represent special information such as non-standard unicode characters, e.g. '\u00A9'. Also non-printable characters, e.g. newline '\n'.

public class _____

class header; indicates a publicly accessible class named "_____"

How do you make a Hello World program?

class helloWorld { public static main (String[] args) { String hw = "Hello, World!"; System.out.println(hw); } }

Declaring a class to a package

class is declared to belong to a package by including a package statement at the beginning of the source file, it must be the first statement in the file: package mypackage; public class MyClass { ... } If package is not declared, the class will belong to the "default package". Not recommended for larger programs.

Instantiating an object

class name object name = classname();

Interfaces are ...

contracts for what a class can do, but they say nothing about the way in which the class must do it.

Math.toRadians(x)

convert x degrees to radians (ie, returns x* p/180)

Boxing

converting a primitive value to a wrapper obj.

int i = in.nextInt();

declares and inputs integer value

Semantic rules:

determine the meaning of instructions in a programming language.

How could you define a real number named numero and initialize it to 867.5?

double numero = 867.5

keywords

each languages limited vocabulary

Collection Interface

general abstraction for a collection of objects. It provides a handful of methods that operate over all interfaces that extend Collection. <<interface>> Collection +add(E) : boolean +addAll(Collection) : boolean +clear() : void +contains(Object) : boolean +containAll(Collection) : boolean +isEmpty() : boolean +remove(Object) : boolean +size() : int Java API does not provide any direct class implementations of interface Collection. Instead, implementations are provided for interfaces that extend Collection, namely, List, Set, and Queue. Nevertheless, the Collection interface is often used to pass collections around since it represents the base behavior of all collections. We'll now take a look at List, Set, and Queue and see how they might be used in our Library application.

I return something by definition.

getter

These help create encapsulation.

getter, setter, public, private

/t

horizontal tab; causes the curson to skip over to the next tab stop

How do you make if...else statements?

if (arg) { } else { } if (arg) { } if (arg) { } else if (arg) { } else { } For example if (e < 10) { //What happens if e < 10 } else { //What happens otherwise } Switch statements are better for if...else if...else.

==

Boolean equals

Identifier:

A Java identifier consists of letters, digits, the underscore character ( _), and the dollar sign ($), and must begin with a letter, underscore, or the dollar sign.

JDK

A bundled set of development utilities for compiling, debugging, and interpreting Java Applications.

What must a class name always start with?

A capital letter then camel case with no spaces.

fields and methods

A class can be viewed as a collection of data (or state) and code to operate on that state. the data is stored in fields and the cold is organized into methods.

instance variables, getter, setter, method

A class can have any number of these.

Subclass

A class that inherits from another class.

What is an interface?

An interface is a special form of an abstract class which does not implement any methods. An interface is an empty shell, there are only the signatres of the methods. It can't do anything.

New operator

An operator that constructs new objects

Three types of Loops

For, While, and Do-While.

Increment/Decrement Operators

Increase/decrease the value of a variable by a particular amount. Addition: x += 1 will accomplish x = x + 1. Subtraction: x -= 2 will accomplish x = x - 2. Multiplication: x *= 5 will accomplish x = x * 5. To increment or decrement by one, do: x++ x---

Package

Java classes grouped together in order to be imported by other programs

Portable, Secure, Robust

Java is _____ (p), _______ (s), and ______ (r). - Makes Java a good language to learn/program to use

Create a Scanner object that reads from System.in

Java: Scanner input= new Scanner(System.in)

Read a double from the Scanner object and store it in a double

Java: double varX= input.nextDouble();

Capable of compiling each byte code once, & then reinvoking the compiled code repeatedly when the byte code is executed.

Just-in-Time compiler

What type of structure are stacks usually known as?

LIFO structures (Last-in, First-out) which means that the last item pushed onto the stack is the first to be taken off.

A _____________ is like a blank in a method definition...

Parameter

desktop computers

Personal computer delivering good performance to single users at low cost.

Operating System

The main software of a computer.

Octal

The numbering system using 8 as its base, using the numerals 0-7 as its digits. In programs written in the Java programming language, octal numbers must be preceded with 0.

Scope

The part of a program in which a particular declaration is valid. Static methods can be placed in any order; variables, however, are only valid up until the next curly right brace.

Sorting

The process of arranging a list of items in order.

Casting

The process of explicitly converting one primitive type to another. Involves writing the desired type of an expression in parentheses e.g. '(int)'. This can result in the *loss of information* and therefore is worth avoiding by choosing appropriate types.

short hand a = a - n;

a -= n;

bytecode

a binary program

interpreter

a computer program that translates one computer statement at a time and executes each statement as it is trasnlated

compiler

a computer program that translates the WHOLE code into machine language and then carries out the statement

concatenation operator

allows strings to be combined in Java

Instance variables can't be ...

abstract, synchronized, native, or strictfp.

/** */

opening comments

first line of program, HelloWorld

public class HelloWorld

Build a return method

public return

Public Interface

specifies what you can do with its objects

How do you set up a switch method?

switch () Case #: (statement)(++acount) (break;) Case #: (statement) (break;) Case #: (statement)

_______\t________ is the escape sequence

tab

Math.tan(x)

tangent of x

boolean

true or false

An interface can have only ...

abstract methods, no concrete methods allowed.

A legal non-abstract implementing class has the following properties:

1) It provides concrete implementations for the interface's methods. 2) It must follow all legal override rules for the methods it implements. 3) It must not declare any new checked exceptions for an implementation method. 4) It must not declare any checked exceptions that are broader than the exceptions declared in the interface method. 5) It may declare runtime exceptions on any interface method implementation regardless of the interface method. 6) It must maintain the exact signature (allowing for covariant returns) and return type of the methods it implement (but does not have declare the exceptions of the interface).

There are four access levels:

1) public 2) protected 3) default 4) private

The do Statement

A do statement has the following syntax: do { statement-list; } while (condition); The statement is executed repeatedly until the condition becomes false The statement-list is executed once initially, and then the condition is evaluated

Method With Parameters

A method can use/accept parameters, where the parameter list specifies the type and name of each parameter If a method takes a parameter, the caller must pass argument (the value passed to the method) of the compatible type: Dog d = new Dog(); d.bark(3);

Method Declaration

A method declaration specifies the code that will be executed when the method is invoked (called) When a method is invoked, the flow of control jumps to the method and executes its code When complete, the flow returns to the place where the method was called and continues The invocation may or may not return a value, depending on how the method is defined

Instance Variables

A variable declared at the class level (such as size) is called an instance variable Each time a Dog object is created, a new memory space is reserved for variable size in this particular object The objects of a class share the same method definitions, but each object maintains its own (different) values for its instance variables, and thus its own state

The while Statement

A while statement has the following syntax: while ( condition ) statement; If the condition is true, the statement is executed then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false An example of a while statement: int count = 1; while (count <= 5) { System.out.println (count); count++; } If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times

Another Example

Another example: If count equals 1, the "Dime" is printed If count is anything other than 1, then "Dimes" is printed Even when the conditional operator is a viable alternative, you should use it carefully because it may be less readable than an if-else statement.

Assignment Conversion

Assignment conversion occurs when a value of one type is assigned to a variable of another Only widening conversions can happen via assignment int dollars = 20; double money = dollars;// OK long y = 32; int x = y; // won't compile

Casting

Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value being converted double money = 84.69; int dollars =(int) money; // dollars = 84 Example of widening conversion: int total = 50; float result = (float) total / 6; (reads float, then division, then equals) Without the cast, the fractional part of the answer would be lost

Classes Revisited

Each class declares -Instance variables: descriptive characteristics or states of the object -Methods: behaviors of the object, i.e., what it can do

Quick Check: Nested Loops

How many times will the string "Here" be printed?

Instance v.s. Local Variables

Instance variables always get a default value. If you don't explicitly assign a value to an instance variable, the instance variable still has a value. -integers: 0 -floating points: 0.0 -booleans: false -references: null

Enumerated Types

Java allows you to define an enumerated type, which can then be used as the type of a variable An enumerated type declaration lists all possible values for a variable of that type The values are identifiers of your own choosing The following declaration creates an enumerated type called Season enum Season {winter, spring, summer, fall}; Any number of values can be listed Once a type is defined, a variable of that type can be declared: Season time; And it can be assigned a value: time = Season.fall; The values are referenced through the name of the type Enumerated types are type-safe - you cannot assign any value other than those listed An enumerated type is a special type of class, and each variable of that type is an object The ordinal method returns the ordinal value of the object The first value in an enumerated type has an ordinal value of 0, the second 1, and so on time.ordinal(); // 3 The name method returns the name of the identifier corresponding to the object's value time.name(); // "fall"

In Java, data conversions can occur in three ways: -assignment conversion -promotion -casting

Numeric data types: double > float > long > int > short > byte Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short)

Promotion

Promotion happens automatically when operators in expressions convert their operands Example: int count = 12; double sum = 490.27; double result = sum / count; The value of count is converted to a floating point value to perform the division calculation

Comparing Strings

Remember that in Java a character string is a String object The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order The equals method returns a boolean result if (name1.equals(name2)) System.out.println ("Same name"); We cannot use the relational operators to compare strings The String class contains the compareTo method for determining if one string comes before another A call to name1.compareTo(name2) -returns zero if name1 and name2 are equal (contain the same characters) -returns a negative value if name1 is lexically before name2 -returns a positive value if name1 is lexically after name2

Repetition Statements

Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: while, do, and for loops

Nested Loops

Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop while ( condition1 ) { while ( condition2 ) statement; } For each iteration of the outer loop, the inner loop iterates completely

Data Conversion

Sometimes it is convenient to convert data from one type to another For example, in a particular situation we may want to treat an integer as a floating point value These conversions do not change the type of a variable or the value that's stored in it - they only generate a value as part of a computation

Formatting Parameters

The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number DecimalFormat fmt = new DecimalFormat("0.###"); -0 means at least one digit should be printed to the left of the decimal point (.), and should be a zero if the integer portion of the value is zero -### means the fractional part of the value should be rounded to three digits (trailing zeros are not printed) format method in the DecimalFormat class can then be used to format a particular value fmt.format(2.0/3); // "0.667" fmt.format(3.3/6); // "0.55"

Wrapper Classes

The java.lang package contains wrapper classes that correspond to each primitive type: The following declaration creates an Integer object which represents the integer 40 as an object int age = 40; Integer ageWrap = new Integer(age); An object of a wrapper class can be used in any situation where a primitive value will not suffice Unwrap a wrapper value int age = ageWrap.intValue(); Other wrapper classes have similar methods Wrapper classes also contain static methods that help manage the associated type The Integer class contains a method to convert an integer stored in a String to an int value: String str = "234"; int num = Integer.parseInt(str); The Double class contains a method to convert a double value stored in a String to an double value: double d = Double.parseDouble("30.24");

Writing Classes

The programs we've written in previous examples have used classes defined in the Java standard class library Now we will begin to design programs that rely on classes that we write ourselves The class that contains the main method is just the starting point of a program True object-oriented programming is based on defining classes that represent objects with well-defined characteristics and functionality

The Return Statement

The return type of a method indicates the type of value that the method sends back to the caller; void type means it does not return a value A return statement specifies the value that will be returned return result; The expression must be compatible with the return type in the method header You must use an explicit cast when the return type is smaller than what you are trying to return Even if the method has a non-void return type, the return value can be ignored

Comparing Floating Point Values

You should rarely use the equality operator (==) when comparing two floating point values (float or double) because two floating point values are equal only if their underlying binary representations match exactly (0.1 + 0.2) == 0.3 // false To determine the equality of two floats, use the following technique: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); If the difference between the two floating point values is less than the tolerance, they are considered to be equal The tolerance could be set to any appropriate level, such as 0.000001

An interface is like ...

a 100-percent 'abstract' class, and is implicitly abstract whether you type the 'abstract' modifier in the declaration or not.

Let's write a program to read a series of integer values from the user, sums them up, and computes their average

What variables do we need to maintain? -Current value from the user input -The sum of values entered so far -The number of values entered so far A sentinel value is a special input value that represents the end of input

Comparing Data

When comparing data using boolean expressions, it's important to understand the nuances of certain data types Let's examine some key situations: -Comparing floating point values for equality -Comparing characters -Comparing strings (lexicographic order) -Comparing object references

Formatting Output

When printing float point values System.out.println(2.0/3); It prints 0.6666666666666666 to the monitor screen The DecimalFormat class can be used to format a floating point value in various ways For example, you can specify that the number should be truncated to three decimal places It is part of the java.text package

'this . aMethod()' is the same as ...

just invoking 'aMethod()'.

name.length

Get the number of rows

Space Efficiency

The amount of space an algorithm uses.

Capital Letter

All java file names must have this at the beginning.

Members accessed without a dot operator (.) must ...

belong to the same class.

Primitive data types

numbers, characters, and Booleans. combined in expression with operators

jump

up and down

What try and catch effectively mean is:What try and catch effectively mean is:

"Try this bit of code that might cause an exception.If it executes okay, go on with the program. If the code doesn't execute, catch the exception and deal with it."

remainder or modulus operator

%, fourth highest precedence, left to right association

Difference between & and &&

& is bitwise. && is logical. & evaluates both sides of the operation. && evaluates the left side of the operation, if it's true, it continues and evaluates the right side.

What are LOGICAL operators of Java? What does each one mean?

&& which is the Conditional AND operator-Statement is only true when both conditions are true (true && true) | |-the Conditional OR operator-Statement is only true as long as one of the statements are true(true || false) (true || true) (false || true) & which is the Boolean logical AND operator-... | which is the boolean logical inclusive OR operator-... ^- the boolean logical exclusive operator OR -Statement is only true when one condition is false and one is true (true ^ false) (false ^ true) ! which is the logical NOT operator- does the same function as != except this operator comes before the statement (!(statement))

switch example

'char control = 'a'; switch (control) { case 'a': invokeA(); break; default: invokeError(); break; }' Note that because 'a' is logically equivalent to the switch argument 'control', that case would be selected and, once the statements executed, break would transfer control to the end of the switch statement, skipping the default: case.

str.equals("test")

(boolean) returns true if the string "test" matches string str, false otherwise

cast operator

(double),(int), third highest precedence, right to left association

pass-by-value

(i.e., call-by-value) • copy of the value of the argument is passed to the method. For a parameter of a: • primitive type → actual value is passed; • reference type → reference for the object is passed

s is a string. Expression whose value is true if & only if the value comes bw "mortgage" & "mortuary" in the dictionary.

(s.compareTo("mortgage") > 0 && s.compareTo("mortuary") < 0 )

What operator multiplies two numbers?

*

Software Layers and responsibilities

* Presentation Layer - rendering the user interface, responding to user event, creating and populating domain objects, and invoking the business layer. * The Business Layer - managing workflow by coordinating the execution of services located in the service layer. * The Service Layer - service interfaces and implementations, the movement of objects in and out of the application, and the hiding of technology choices. * The Domain Layer - abstracting domain objects (i.e., the nouns) as they appear in the problem space. Data types for: user interface ->> Presentation Layer; manage use case workflow ->>Business Layer; move objects in and out of application ->>Service Layer; abstract the "nouns" of problem space ->> Domain Layer

unary plus operator

+, third highest precedence

Portable

- A programing language is ____ if it can be used on more than one type of computer without having to be changed

System.out

- Computer sends message out to screen

Integer

- Name for a whole number Ex: 4, 10

Print

- Name of message will be sent - Cursor placed right after the last character typed in the code

Parameter

- Sends a message to object - Between (parentheses) Ex: System.out.println("Hello World");

Variable

- Storage for one value - Refers to data, value, or objects Ex: double fahrenheit

Readability

- The ability for other programmers to read and understand your program - Easier to read = easier to understand and learn

Terminal I/O User Interface

- View as seen from Java compiler - Less pleasing to the eye and harder for users to understand

unary minus operator

-, third highest precedence

Rules to defining a Java class

-a Java identifier cannot begin with a digit -a Java identifier can only contain letters, digits, underscores, or dollar signs -a Java identifier cannot be a reserved keyword -a Java identifier cannot be one of the following values: true, false, or null

LinkedList: add item to beginning of list

-addFirst(item);

Thread creation via implementing Runnable

1) Create a class that implements Runnable -Runnable only declares the run() method sig 2) Define the run() method 3) Create an object of this class 4) Pass this object to the Thread constructor 5) Call the start() method of the Thread object

Create an array called 'colors' and add to it :"red","blue", "Green" 2. 1. Create a foreach loop the writes out the contents of the arra

1. String[] colors = new String[] {"red","blue", "Green"}; 2. for (String c : colors){ System.out.println(c); } v42

Reasons to use "double"

1023 digits after the decimal point

petabyte

10^15 or 2^50 bytes

float

32 bit real number

double

64 bit real number

double

8 bytes, stores floating-point numbers

Assignment/Declaration

<type> <name> = <expression> Declares a variable (names it), and assigns it a value.

Abstract data type

= class

Comparison operators: Equal to, Not equal to, greater than, greater than or equal to, less than, less than or equal to

== != > >= < <=

Data type

A name for a category of data values that are all related. Ex. "int" is the category of integers.

servers

A class of computers composed of hundred to thousand processors and terabytes of memory and having the highest performance and cost

Programs

A class that can be used as a template for the creation of new objects.

Superclass

A class that is inherited from.

Screen coordinate system

A coordinate system used by most programming languages in which the origin is in the upper-left corner of the screen, window, or panel, and the y values increase toward the bottom of the drawing area

int

A data type of integers (whole numbers).

double

A data type of real numbers (1/2, 99.9, -0.1).

char

A data type of single characters ('a', 'b', '?').

Anonymous inner class

A local class whose definition and use are combined into a single expression

Class

A master copy of the object that determines the attributes and behavior an object should have.

return

A method can have only one of these.

Combinatorial Explosion

A multiplicative growth. ex: If in A is introduced it has two possible states true or false. When B is introduced there are 4 possible states.

Java bytecode

A platform independent instruction set that's produced when Java source code is compiled.

Output Assertion

A postcondition for a loop ex: As in a do-while loop, the while is post conditional, therefore the final value (if not instantiated correctly) will contain a off-by-one error. A do-while loop performs postcondition

What is the definition of an algorithm?

A procedure for solving a problem in terms of: The actions to execute and the order in which these actions execute

Applet

A program that runs on a web page.

Declaration

A request to set aside a new variable with a given name of type; you must do this before assigning a value to a variable.

Nested "if" Statement

A selection statement used within another selection statements. ex: ex: if(j<=0) { System.out.println("Example"); if(m<10) System.out.println("Example"); else { System.out.println("Example"); } else { System.out.println("Example"); } } else { System.out.println("Example"); }

The Java Software Development Kit (JDK)

A set of command line tools (e.g., compilers, de-compilers, debuggers) used to develop Java programs. The JDK also contains the JRE, which contains the JVM.

Unicode

A standardized 16-bit character set that represents the character sets of most major languages in the world. The letters entered have to be above 192.

appletviewer

A tool included in the JDK that's supported in NetBeans, which will test applets.

Byte

A variable type that is a sequence of 8 bits (enough to represent one character of alphanumeric data) processed as a single unit of information, Range [-127,128]

Multi-thread

A way for the computer to do more than one thing at the same time.

Method

A way of doing something

Object

A way of organizing a program so that it has everything it needs to accomplish a task.

Method

A way to accomplish a task in a Java program.

Private instance variables can be accessed from outside their class through ______ methods and changed with _________ methods

Accessor methods && Mutator methods

Concatenation

Adding one string to another.

8 primitive data types

All of Java's numeric primitive data types are signed. Boolean (1 bit): true, false char (2 bytes): Unicode characters, ranging from 0 TO 65,535 byte (1 byte): -128 to 127 short (2 bytes): -32,768 TO 32,767 int (4 bytes): -2,147,483,648 TO 2,147,483,647 long (8 bytes): -9,223,372,036,854,775,808 TO +9,223,372,036,854,775,807 float (4 bytes): 1.40129846432481707e-45 TO 3.40282346638528860e+38 (+ or -) double (8 bytes): 4.94065645841246544e-324d TO 1.79769313486231570e+308d (+ or -)

...

An ArrayList object can have its internal capacity adjusted manually to improve efficiency.

modular application

An application that uses components that are separately written and maintained.

client code

An application that uses one or more classes.

classpath

An enviroment variable that includes an argument set telling the Java virtual machine where to look for user defined classes/packages.

Reference Variable

An identifier that represents a location in memory which itself has a *reference* to another location in memory where an object resides. Multiple reference variables can reference the same object and so affect its reference count. An object with no references can be garbage collected.

Peripherals

An input device, output device, or secondary storage device that is not part of the central processing unit (CPU)

Class method vs Instance method

An instance method is declared without the static modifier and is invoked using the name of the object to which it is bound.

Exception

An object defining a problem that can usually be fixed

Binary operator:

An operator that has two operands.

Consider the following code snippet: Vehicle aVehicle = new Auto(4,"gasoline"); String s = aVehicle.toString(); Assume that the Auto class inherits from the Vehicle class, and neither class has an implementation of the toString() method. Which of the following statements is correct? A) The toString() method of the Object class will be used when this code is executed. B) The toString() method of the String class will be used when this code is executed. C) This code will not compile because there is no toString() method in the Vehicle class. D) This code will not compile because there is no toString() method in the Auto class.

Ans: A Section Ref: 10.7.1

Which of the following types of side effects potentially violates the rule of minimizing the coupling of classes? A) Standard output. B) Modification of implicit parameters. C) Modification of explicit parameters. D) Modification of both implicit and explicit parameters.

Ans: A Section Ref: 8.4

Which of the following statements describes an assertion? A) A logical condition in a program that you believe to be true. B) A guarantee that the object is in a certain state after the method call is completed. C) A requirement that the caller of a method must meet. D) A set of criteria defined by the caller of a method.

Ans: A Section Ref: 8.5

Why is a static variable also referred to as a class variable? A) There is a single copy available to all objects of the class. B) It is encapsulated within the class. C) Each class has one and only one static variable. D) It is stored in the separate class area of each object.

Ans: A Section Ref: 8.7

Which of the following is an event source? A) A JButton object. B) An event listener. C) An inner class. D) An event adapter.

Ans: A Section Ref: 9.7

What is the error in this array code fragment? double[] data; data[0] = 15.25; A) The array referenced by data has not been initialized. B) A two-dimensional array is required. C) An out-of-bounds error occurs. D) A cast is required.

Ans: A Section Ref: Section 7.1 Arrays

What is the type of a variable that references an array of integers? A) int[] B) integer() C) integer[] D) int()

Ans: A Section Ref: Section 7.1 Arrays

Wrapper objects can be used anywhere that objects are required instead of ____. A) primitive data types B) clone methods C) array lists D) generic classes

Ans: A Section Ref: Section 7.3 Wrappers and Auto-boxing

Rewrite the following traditional for loop header as an enhanced for loop, assuming that ArrayList<String> names has been initialized. for (int i = 0; i < names.size(); i++) { // process name } A) for (String s : names) B) for (int i = 0; i < names.size(); i++) C) for (s : names) D) for (names : String s)

Ans: A Section Ref: Section 7.4 The Enhanced for Loop

What is the purpose of this algorithm? int m = 0; for (BankAccount a : accounts) { if (a.getBalance() >= atLeast) m++; } A) Counting matches. B) Finding a value. C) Computing the sum. D) Locating an element.

Ans: A Section Ref: Section 7.6 Common Array Algorithms

Which of the following statements about a superclass is true? A) An abstract method may be used in a superclass when there is no good default method for the superclass that will suit all subclasses' needs. B) An abstract method may be used in a superclass to ensure that the subclasses cannot change how the method executes. C) An abstract method may be used in a superclass when the method must have identical implementations in the subclasses. D) An abstract method may not be used in a superclass.

Ans: A Section Ref: Special Topic 10.1

A static method can have which of the following types of parameters? A) Only implicit parameters. B) Only explicit parameters. C) Both implicit and explicit parameters. D) A static method cannot have parameters.

Ans: B Section Ref: 8.6

Which of the following statements about a Java interface is NOT true? A) A Java interface defines a set of methods that are required. B) A Java interface must contain more than one method. C) A Java interface specifies behavior that a class will implement. D) All methods in a Java interface must be abstract.

Ans: B Section Ref: 9.1

You have a class which extends the JComponent class. In this class you have created a painted graphical object. Your code will change the data in the graphical object. What additional code is needed to ensure that the graphical object will be updated with the changed data? A) You must call the component object's paintComponent() method. B) You must call the component object's repaint() method. C) You do not have to do anything - the component object will be automatically repainted when its data changes. D) You must use a Timer object to cause the component object to be updated.

Ans: B Section Ref: Common Error 9.6

Consider the following code snippet: public class Coin { . . . public boolean equals(Coin otherCoin) { . . . } . . . } What is wrong with this code? A) A class cannot override the equals() method of the Object class. B) The equals method must be declared as private. C) A class cannot change the parameters of a superclass method when overriding it. D) There is nothing wrong with this code.

Ans: C Section Ref: 10.7.2

Which of the following questions should you ask yourself in order to determine if you have named your class properly? A) Does the class name contain 8 or fewer characters? B) Is the class name a verb? C) Can I visualize an object of the class? D) Does the class name describe the tasks that this class will accomplish?

Ans: C Section Ref: 8.1

Which of the following describes an immutable class? A) A class that has no accessor or mutator methods. B) A class that has no accessor methods, but does have mutator methods. C) A class that has accessor methods, but does not have mutator methods. D) A class that has both accessor and mutator methods.

Ans: C Section Ref: 8.3

Which of the following statements describes a precondition? A) A logical condition in a program that you believe to be true. B) A guarantee that the object is in a certain state after the method call is completed. C) A requirement that the caller of a method must meet. D) A set of criteria defined by the caller of a method.

Ans: C Section Ref: 8.5

Under which of the following conditions can you have local variables with identical names? A) If their scopes are nested. B) If they are of different data types. C) If their scopes do not overlap. D) If they both reference the same object.

Ans: C Section Ref: 8.8

When you use a timer, you need to define a class that implements the ____ interface. A) TimerListener B) TimerActionListener C) ActionListener D) StartTimerListener

Ans: C Section Ref: 9.10

Consider the following code snippet: class MouseClickedListener implements ActionListener { public void mouseClicked(MouseEvent event) { int x = event.getX(); int y = event.getY(); component.moveTo(x,y); } } What is wrong with this code? A) The mouseClicked method cannot access the x and y coordinates of the mouse. B) repaint() method was not called. C) The class has implemented the wrong interface. D) There is nothing wrong with this code.

Ans: C Section Ref: 9.11

Which of the following statements will compile without error? A) public interface AccountListener() { void actionPerformed(AccountEvent event); } B) public interface AccountListener() { void actionPerformed(AccountEvent); } C) public interface AccountListener { void actionPerformed(AccountEvent event); } D) public abstract AccountListener { void actionPerformed(AccountEvent event); }

Ans: C Section Ref: 9.7

____ are generated when the user presses a key, clicks a button, or selects a menu item. A) Listeners B) Interfaces. C) Events. D) Errors.

Ans: C Section Ref: 9.7

How do you specify what the program should do when the user clicks a button? A) Specify the actions to take in a class that implements the ButtonListener interface. B) Specify the actions to take in a class that implements the ButtonEvent interface . C) Specify the actions to take in a class that implements the ActionListener interface. D) Specify the actions to take in a class that implements the EventListener interface.

Ans: C Section Ref: 9.9

You access array list elements with an integer index, using the __________. A) () operator B) [] operator C) get method D) element method

Ans: C Section Ref: Section 7.2 Array Lists

Which of the following is true regarding inheritance? A) When creating a subclass, all methods of the superclass must be overridden. B) When creating a subclass, no methods of a superclass can be overridden. C) A superclass can force a programmer to override a method in any subclass it creates. D) A superclass cannot force a programmer to override a method in any subclass it creates.

Ans: C Section Ref: Special Topic 10.1

The ____ reserved word in a method definition ensures that subclasses cannot override this method. A) abstract B) anonymous C) final D) static

Ans: C Section Ref: Special Topic 10.2

Consider the following code snippet: final RectangleComponent component = new RectangleComponent(); MouseListener listener = new MousePressListener(); component.addMouseListener(listener); ______________ frame.add(component); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); Which of the following statements completes this code? A) private static final int FRAME_WIDTH = 300; B) private static final int FRAME_HEIGHT = 400; C) Frame frame = new Frame(); D) JFrame frame = new JFrame();

Ans: D

Which of the following is true regarding subclasses? A) A subclass may call the superclass constructor by using the this reserved word. B) A subclass cannot call the superclass constructor. C) If a subclass does not call the superclass constructor, it must have a constructor with parameters. D) If a subclass does not call the superclass constructor, it must have a constructor without parameters.

Ans: D Section Ref: 10.4

Which of the following statements generally describes the scope of a variable? A) The ability of a variable to access other variables in the same program. B) The amount of data in bytes that the variable can contain. C) The range of data types that the variable can legally be cast into. D) The region of a program in which the variable can be accessed.

Ans: D Section Ref: 8.8

Which of the following is not a reason to place classes into a package? A) to avoid name clashes (most important) B) to organize related classes C) to show authorship of source code for classes D) to make it easier to include a set of frequently used but unrelated classes

Ans: D Section Ref: 8.9

A method that has no implementation is called a/an ____ method. A) interface B) implementation C) overloaded D) abstract

Ans: D Section Ref: 9.1

Which of the following code statements creates a graphical button which has "Calculate" as its label ? A) Button JButton = new Button("Calculate"). B) button = new Button(JButton, "Calculate"). C) button = new JButton("Calculate"). D) JButton button = new JButton("Calculate").

Ans: D Section Ref: 9.9

Which of the following is considered by the text to be the most important consideration when designing a class? A) Each class should represent an appropriate mathematical concept. B) Each class should represent a single concept or object from the problem domain. C) Each class should represent no more than three specific concepts. D) Each class should represent multiple concepts only if they are closely related.

Ans:B Section Ref: 8.1

Constructors are special methods defined in a class that are used to initialize ___ ___.

Answer: object instances Constructors must have the same name as the class name; the class Book will have constructors named Book (must be identical). Constructs are not allowed to explicitly declare that they return a type; rather, the implicit type they return is the enclosing class type in which they're defined.

ArrayList<String>: Instantiation

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

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

ArrayList<typeParameter> variableName = new ArrayList<typeParameter>(); typeParameter cannot be a primitive type

One-Dimensional Array

Arrays that store a simple list of values.

UML Diagrams - list the behavior diagrams

Behavior Diagrams - STIACUS Sequence Timing Interactive Activity Communication Use Case State

Name 9 primitive types

BSILF DB CS byte short int long float double boolean char String

|

Bitwise Or operator

What is the difference between black box and white box testing?

Black Box - test cases are developed without regard to internal workings - test as if we don't know the working of the program White Box - exercises internal structure and implementation of method - test as if we do know the working of the program

Scope

Block of code in which a variable is in existence and may be used.

static fields and methods

By default, data members and methods are "instance" members and are said to be "non static." Non static instance data members are copied to each object instance of the class, so each object has its own copy. Non static methods can reference these copied data members through an implicit object reference (but you can access it via "this" when necessary). The concept of non static instance members is illustrated below. public class Book { private String title = ""; public void setTitle(String title) { this.title = title; } } When there's a need to not copy data members to each object instance, such as constants. They can remain in the class definition. Data members and methods that are not associated with object instances are call "class" members; they are local to the class and are not affiliated with the objects. Annotated with the keyword "static": public static final int CHECKOUT_DURATION = 21; Because the above data member is a class variable, it can be accessed through the class name as follows: int duration = Book.CHECKOUT_DURATION; Methods can also be designated as static: private static int nextId = 1; public static int getNextId() { return nextId++; } Above, method getNextId() provides access to the static data member and manages its next value. IMPORTANT: "static only sees static" but "non-static sees everything" static members can only access other static members; in particular, static members cannot access non-static members. Non-static members have access to all members (both static and non-static).

Default (no modifier)

Can be applied to a class and/or individual data members and methods within a class; indicates that the given item is not accessible across package boundaries (i.e., it limits access to members of the same package) e.g., the following class and method are NOT accessible outside the package in which they're defined. package domain; class Book { void checkout() { } }

Protected modifier

Can be applied to individual data members and methods (but cannot be applied to a class); when applied, it restricts access to members of the same class and any derived class; e.g., the following method, setHashCode, is only accessible to members of the LibraryItem class and any derived classes (e.g., Book). package domain; public class LibraryItem { protected void setHashCode() { } } package domain; public class Book extends LibraryItem { public LibraryItem () { setHashCode(); } }

Private

Can be applied to individual data members and methods (but cannot be applied to a class); when applied, it restricts access to members of the same class; e.g., the following data member, isbn, is only accessible to members of the Book class, and nowhere else. package domain; public class Book { private String isbn; public void getIsbn() { return isbn } }

Strings and escape sequences

Can be included in a string as if they were another character using the backslash \. E.g. "\"This is a string\"" uses \" to include double quotation marks as characters in the sequence.

switch default case

Can be included to perform some processing if none of the other cases in the switch statement are selected, such as throwing an exception. It isn't a requirement but is good style.

Primitive Variables

Can store data values.

to convert data type

Casting

What are the TWO types of data contained by classes?

Characteristics and Behavior

-All programs start with a ? -Must have { and } -Identifier (name) begins with a CAPITAL letter EX: public class Westlake

Class

Chapter 2: Observable is a ____ not a interface.

Class

What are Class, Constructor and Primitive data types?

Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.

UML Class diagram w/ general syntax

ClassName Properties Here Behaviors Here Book title: String author: String isCheckedOut: boolean checkOut(): void checkIn(): void Each property name is followed by its data type (e.g., String, boolean). Each method name is followed by its return type (e.g., void).

Object Construction

ClassName objectName = new ClassName(parameters);

How do you call a method from a class?

ClassName.methodName(arguments)

Static method call

ClassName.methodName(parameters);

Overview of Classes

Classes are the most fundamental structural element of java programs. you cant write a java code without defining a class. Java statements appear within classes, and all methods are implemented within classes

In OOP, describe is-a or has-relationships?

Classes in OOP, are related to each other & they're going to be related through an "IS-A" relationship or "HAS-A" relationship. > IS-A relationship result from inheritance > HAS-A relationship result from composition This comes from the need to reuse code. v47

signature

Combination of identifiers, return value, name and parameters of a method. Example: public int calculateMonth(String name)

1.2.1 8 bits x 3 colors = 24 bits/pixel = 4 bytes/pixel. 1280 x 800 pixels = 1,024,000 pixels. 1,024,000 pixels x 4 bytes/pixel = 4,096,000 bytes (approx 4 Mbytes). 1.2.2 2 GB = 2000 Mbytes. No. frames = 2000 Mbytes/4 Mbytes = 500 frames. 1.2.3 Network speed: 1 gigabit network ==> 1 gigabit/per second = 125 Mbytes/second. File size: 256 Kbytes = 0.256 Mbytes. Time for 0.256 Mbytes = 0.256/125 = 2.048 ms.

Configuration Resolution Main Mem Ethernet Network a. 1 640 × 480 2 GB 100 Mbit 2 1280 × 1024 4 BG 1 Gbit b. 1 1024 × 768 2 GB 100 Mbit 2 2560 × 1600 4 GB 1 Gbit 1.2.1 For a color display using 8 bits for each of the primary colors (red, green, blue) per pixel, what should be the minimum size in bytes of the frame buffer to store a frame? 1.2.2 How many frames could it store, assuming the memory contains no other information? 1.2.3 If a 256 Kbytes file is sent through the Ethernet connection, how long it would take?

1.7.4 C = P/V^2 x clockrate 80286: C = 0.0105 x 10^-6 80386: C = 0.01025 x 10^-6 80486: C = 0.00784 x 10^-6 Pentium: C = 0.00612 x 10^-6 Pentium Pro: C = 0.0133 x 10^-6 Pentium 4 Willamette: C = 0.0122 x 10^-6 Pentium 4 Prescott: C = 0.00183 x 10^-6 Core 2: C = 0.0294 x 10^-6 1.7.5 3.3/1.75 = 1.78 (Pentium Pro to Pentium 4 Willamette) 1.7.6 Pentium to Pentium Pro: 3.3/5 = 0.66 Pentium Pro to Pentium 4 Willamette: 1.75/3.3 = 0.53 Pentium 4 Willamette to Pentium 4 Prescott: 1.25/1.75 = 0.71 Pentium 4 Prescott to Core 2: 1.1/1.25 = 0.88 Geometric mean = 0.68

Consider the following values for voltage in each generation. Processor Voltage 80286 (1982) 5 80386 (1985) 5 80486 (1989) 5 Pentium (1993) 5 Pentium Pro (1997) 3.3 Pentium 4 Willamette (2001) 1.75 Pentium 4 Prescott (2004) 1.25 Core 2 Ketsfield (2007) 1.1 1.7.4 Find the average capacitive loads, assuming a negligible static power consumption. 1.7.5 Find the largest relative change in voltage between generations. 1.7.6 Find the geometric mean of the voltage ratios in the generations since the Pentium.

1.3.1 P2 has the highest performance performance of Pl (instructions/sec)= 2 x 10^9/1.5 = 1.33 x 10^9 performance of P2 (instructions/sec)= 1.5 x 10^9/1.0 = 1.5 x 10^9 performance of P3 (instructions/sec)= 3 x 10^9/2.5 = 1.2 x 10^9 1.3.2 No. cycles = time x clock rate cycles(Pl) = 10 x 2 x 10^9 = 20 x 10^9 s cycles(P2) = 10 x 1.5 x 10^9 = 15 x 10^9 s cycles(P3) = 10 x 3 x 10^9 = 30 x 10^9 s time= (No. instr. x CPI)/clock rate, then No. instructions= No. cycles/CPI instructions(Pl) = 20 x 109/1.5 = 13.33 x 109 instructions(P2) = 15 x 109/1 = 15 x 109 instructions(P3) = 30 x 109/2.5 = 12 x 109 1.3.3 time new = time old X 0.7 = 7 s CPI= CPI x 1.2, then CPI(Pl) = 1.8, CPI(P2) = 1.2, CPI(P3) = 3 f = No. instr. x CPI/time, then f(Pl) = 13.33 X 109 X 1.8/7 = 3.42 GHz f(P2) = 15 X 109 X 1.2/7 = 2.57 GHz f(P3) = 12 x 109 x 3/7 = 5.14 GHz

Consider three different processors P1, P2, and P3 executing the same instruction set with the clock rates and CPIs given in the following table. Processor Clock Rate CPI a. P1 3 GHz 1.5 P2 2.5 GHz 1.0 P3 4 GHz 2.2 b. P1 2 GHz 1.2 P2 3 GHz 0.8 P3 4 GHz 2.0 1.3.1 Which processor has the highest performance expressed in instructions per second? 1.3.2 If the processors each execute a program in 10 seconds, find the number of cycles and the number of instructions. 1.3.3 We are trying to reduce the time by 30% but this leads to an increase of 20% in the CPI. What clock rate should we have to get this time reduction?

var

Creates a variable and optionally gives it an initial value. Cannot start with a number.

What are the class relationships? Dependency Aggregation

Dependency - method of one class invokes methods of another (depends on other) Aggregation - an object made up of other objects it depends on

Definition of class

Describes the properties and behavior of a prototypical object. During runtime, the application creates individual instances of classes where the instances are called objects. For example: class - Book properties - title, author behaviors - checkOut(), checkIn() Then at runtime, the application creates a separate object for each book as they are requested by users.

Operator precedence rules:

Determine the order in which operations are performed to evaluate an expression.

multiplicity

Each class involved in a relationship may specify a multiplicity. A multiplicity could be: • a number or an interval that specifies how many of the class's objects are involved in the relationship.

Thread

Each part of a program which takes care of a different task.

What is camel casing?

Each time a new word begins start it with a capital letter

What does a scanner do for a program?

Enables the program to read data (ints, dbls, char etc.)

String Literal

Enclosed in double quotation marks. E.g. "Jonathan withey". This actually creates a String object to be referenced, for example 'String aString = "Character Sequence";'.

internal problems involving the Java virtual machine (the runtime environment). These are rare and usually fatal to the program; there's not much that you can do about them.

Errors

new int [5] [8] new Pixel [numRows] [numCols]

Examples of creation of 2D arrays

What class should be the superclass of any exceptions you create in Java?

Exception

2.19.1 a. compare: addi $sp, $sp , -4 sw $ra , 0($sp) add $s0, $a0 , $0 add $s1, $a1, $0 jal sub addi $t1, $0, 1 beq $v0, $0, exit slt $t2, $0, $v0 bne $t2, $0, exit addi $t1, $0, $0 exit: add $v0, $t1, $0 lw $ra , 0($sp) addi $sp , $sp , 4 jr $ra sub: sub $v0, $a0, $al jr $ra b. fib_iter : addi $sp , $sp, -16 sw $ra , 12($sp) sw $s0, 8($sp) sw $s1, 4($sp) sw $s2, 0($sp) add $s0 , $a0, $0 add $s1, $a1, $0 add $s2, $a2, $0 add $v0, $s1, $0 bne $s2 , $0 , exit add $a0, $s0, $sl add $al, $s0, $0 add $a2 , $s2, -1 ja l fib_iter exi t : lw $s2, 0($sp) lw $s1, 4($sp) lw $s0, 8($sp) lw $ra , 12($sp) addi $sp , $sp, 16 jr $ra 2.19.2 a. compa re: addi $sp , $sp, -4 sw $ra , 0($sp) sub $t0, $a0, $a1 addi $tl, $0, 1 beq $t0, $0 , ex i t slt $t2 , $0, $t0 bne $t2, $0 , ex i t addi $tl, $0, $0 ex i t : add $v0, $tl, $0 lw $ra, 0($sp) addi $sp, $sp, 4 jr $ra b. Due to the recursive nature of the code. Not possible for the compiler to in line the function call. 2.19.3 a. after calling function compare: old $sp => 0x7ffffffc ??? $sp => -4 contents of register $ra after calling function sub: old $sp => 0x7ffffffc ??? -4 contents of register $ra $sp => -8 contents of register $ra #return to compare b. after calling function fib_iter: old $sp => 0x7ffffffc ??? -4 contents of register $ ra -8 contents of register $s0 -12 contents of register $s1 $sp => -16 contents of register $s2 2.19.4 a. f: addi $sp, $sp, -8 sw $ra, 4($sp) sw $s0, 0($sp) move $s0, $a2 jal func move $a0, $v0 move $a1, $s0 jal func lw $ra, 4($sp) lw $s0, 0($sp) addi $sp, $sp, 8 jr $ra b. f: addi $sp, $sp, -12 sw $ra, 8($sp) sw $sl, 4($sp) sw $s0, 0 ($sp) mov e $s0, $a1 mov e $sl, $a2 jal func move $a0, $s0 move $a1, $s1 mov e $s0, $v0 jal func add $v0, $v0, $s0 lw $ra, 8($sp) lw $s1, 4($sp) lw $s0, 0($sp) addi $sp, $sp, 12 jr ra 2.19.5 a. We can use the tail-call optimization for the second call to func, but then we must restore $ra and $sp before that call. We save only one instruction (jr $ra). b. We can NOT use the tail call optimization here, because the value returned from f is not equal to the value returned by the last call to func. 2.19.6 Register $ra is equal to the return address in the caller function, registers $sp and $s3 have the same values they had when function f was called, and register $t5 can have an arbitrary value. For register $t5, note that although our function f does not modify it, function func is allowed to modify it so we cannot assume anything about the of $t5 after function func has been called.

For the following problems, the table holds C code functions. Assume that the first function listed in the table is called first. You will be asked to translate these C code routines into MIPS assembly. a. int fib(int n){ if (n==0) return 0; else if (n == 1) return 1; else fib(n-1) + fib(n-2); b. int positive(int a, int b) { if (addit(a, b) > 0) return 1; else return 0; } int addit(int a, int b) { return a+b; } 2.19.1 [15] <2.8> Implement the C code in the table in MIPS assembly. What is the total number of MIPS instructions needed to execute the function? 2.19.2 [5] <2.8> Functions can often be implemented by compilers "in-line." An in-line function is when the body of the function is copied into the program space, allowing the overhead of the function call to be eliminated. Implement an "in-line" version of the the C code in the table in MIPS assembly. What is the reduction in the total number of MIPS assembly instructions needed to complete the function? Assume that the C variable n is initialized to 5. 2.19.3 [5] <2.8> For each function call, show the contents of the stack after the function call is made. Assume the stack pointer is originally at address 0x7ffffffc, and follow the register conventions as specified in Figure 2.11. The following three problems in this Exercise refer to a function f that calls another function func. The code for C function func is already compiled in another module using the MIPS calling convention from Figure 2.14. The function declaration for func is "int func(int a, int b);". The code for function f is as follows: a. int f(int a, int b, int c, int d){ return func(func(a,b),c+d); } b. int f(int a, int b, int c, int d){ if(a+b>c+d) return func(a+b,c+d); return func(c+d,a+b); } 2.19.4 [10] <2.8> Translate function f into MIPS assembly language, also using the MIPS calling convention from Figure 2.14. If you need to use registers $t0 through $t7, use the lower-numbered registers first. 2.19.5 [5] <2.8> Can we use the tail-call optimization in this function? If no, explain why not. If yes, what is the difference in the number of executed instructions in f with and without the optimization? 2.19.6 [5] <2.8> Right before your function f from Problem 2.19.4 returns, what do we know about contents of registers $t5, $s3, $ra, and $sp? Keep in mind that we know what the entire function f looks like, but for function func we only know its declaration.

Graphical User Interface

GUI - PC users view of the "out" screen

name[0].length

Get the number of columns

Arrays

Group (or collection) of items that are the same type. declares an array object, daysOfWeek, as an array of seven String objects: String [ ] daysOfWeek = new String[7]; assign the seven elements as follows: daysOfWeek[0] = "Sunday"; daysOfWeek[1] = "Monday"; daysOfWeek[2] = "Tuesday"; daysOfWeek[3] = "Wednesday"; daysOfWeek[4] = "Thursday"; daysOfWeek[5] = "Friday"; daysOfWeek[6] = "Saturday"; values could be initialized at the point of declaration: private String [ ] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday" , "Thursday", "Friday", "Saturday"}; The size of the array is available via the length property (e.g., daysOfWeek.length), allowing you to iterate through its values in a "for loop": for (int i = 0; i<daysOfWeek.length; i++) { System.out.println(daysOfWeek[i]); } Array downside, once declared, their size is fixed. Can create a new, larger array and move the contents of the first array into the second, but that is clumsy. Typically used only for grouping items whose size is fixed.

What compilation error should you be aware of when using arguments and parameters?

If the amount of arguments(maximum(a, b, c) does not match the amount of parameters(maximum( double x, double, y, double z, double d) this creates a compilation error

2.12.1 Type opcode rs rt rd shamt func a)R-type 6 3 3 3 5 6 total bits = 26 b)R-type 6 5 5 5 5 6 total bits = 32 2.12.2 Type opcode rs rt immed a) i-type 6 3 3 16 total bits = 28 b) i-type 6 5 5 10 total bits = 26 2.12.3 a. less registers --> less bits per instruction --> could reduce code size less registers --> more register spills --> more instructions b. smaller constants --> more lui instructions --> could increase code size smaller constants --> smaller opcodes --> smaller code size"

In the following problems, the data table contains various modifications that could be made to the MIPS instruction set architecture. You will investigate the impact of these changes on the instruction format of the MIPS architecture. a. 128 registers b. Four times as many different instructions 2.12.1 [5] <2.5> If the instruction set of the MIPS processor is modified, the instruction format must also be changed. For each of the suggested changes above, show the size of the bit fields of an R-type format instruction. What is the total number of bits needed for each instruction? 2.12.2 [5] <2.5> If the instruction set of the MIPS processor is modified, the instruction format must also be changed. For each of the suggested changes above, show the size of the bit fields of an I-type format instruction. What is the total number of bits needed for each instruction? 2.12.3 [5] <2.5, 2.10> Why could the suggested change in the table above decrease the size of an MIPS assembly program? Why could the suggested change in the table above increase the size of an MIPS assembly program?

2.5.1 a. Address Data temp = Array[3]; 12 1 Array [3] = Array[2] 8 6 Array [2] = Array[1] 4 4 Array[1] = Array[0] 0 2 Array [0] = temp; b. Address Data temp = Array[ 4]; 16 1 Array [4] = Array[0]; 12 2 Array[0] = temp ; 8 3 temp = Array[ 3]; 4 4 Array[ 3] = Array[ 1]; 0 5 Array [1] = temp; 2.5.2" a. Address Data temp = Array[ 3]; lw $t0, 12($s6) 12 1 Array [3] = Array[2]; lw $tl, 8($s6) 8 6 Array [2] = Array[1]; sw $tl, 12($s6) 4 4 Array[1] = Array[0]; lw $tl, 4($s6) 0 2 Array [0] = temp; sw $tl, 8($s6) lw $tl, 0($s6) sw $tl, 4($s6) sw $t0, 0($s6) b. Address Data temp = Array[4]; lw $t0, 16 ($s6) 16 1 Array [4]= Array[0]; lw $tl, 0($s6) 12 2 Array [0] = temp; sw $tl, 16 ($s6) 8 3 temp = Array[3]; sw $t0, 0($s6) 4 4 Array [3] = Array[1]; lw $t0, 12($s6) 0 5 Array [1]= temp; lw $tl, 4($s6) sw $tl, 12($s6) sw $t0, 4($s6) 2.5.3 a. Address Data temp = Array[3]; lw $t0, 12($s6) 12 1 Array[3] = Array[2] lw $tl, 8($s6) 8 6 Array[2] = Array[1] sw $tl, 12($s6) 4 4 Array[1] = Array[0] lw $tl, 4($s6) 0 2 Array[0] = temp ; sw $tl, 8($s6) lw $tl, 0($s6) sw $tl, 4($s6) sw $t0. 0($s6) 8 mips instructions , +1 mips instruction for every non- zero offset lw/sw pair (11mips inst.) b. Address Data temp = Array[4]; lw $t0, 16($s6) 16 1 Array [4] = Array[0]; lw $t1, 0($s6) 12 2 Array[0] = temp; sw $t1, 16($s6) 8 3 temp = Array[ 3]; sw $t0, 0($s6) 4 4 Array[ 3] = Array[1]; lw $t0, 12($s6) 0 5 Array [1] = temp; lw $t1, 4($s6) sw $tl, 12($s6) sw $t0, 4($s6) 8 mips instructions , +1 mips inst. for every non-zero offset lw/sw pair (11 mips inst.)

In the following problems, we will be investigating memory operations in the context of an MIPS processor. The table below shows the values of an array stored in memory. Assume the base address of the array is stored in register $s6 and offset it with respect to the base address of the array. a. Address Data 20 4 24 5 28 3 32 2 34 1 b. Address Data 24 2 38 4 32 3 36 6 40 1 2.5.1 [10] <2.2, 2.3> For the memory locations in the table above, write C code to sort the data from lowest to highest, placing the lowest value in the smallest memory location shown in the figure. Assume that the data shown represents the C variable called Array, which is an array of type int, and that the first number in the array shown is the first element in the array. Assume that this particular machine is a byte-addressable machine and a word consists of four bytes. 2.5.2 [10] <2.2, 2.3> For the memory locations in the table above, write MIPS code to sort the data from lowest to highest, placing the lowest value in the smallest memory location. Use a minimum number of MIPS instructions. Assume the base address of Array is stored in register $s6. 2.5.3 [5] <2.2, 2.3> To sort the array above, how many instructions are required for the MIPS code? If you are not allowed to use the immediate field in lw and sw instructions, how many MIPS instructions do you need?

Access Modifiers

Information hiding is achieved through the use of access modifiers, which are keywords that are used to augment the visibility of various constructs. Public Default (no modifier) Protected Private

What is meant by Inheritance and what are its advantages?

Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.

Integer Literals

Integers embedded into Java source code, can be expressed as a decimal number by any sequence of digits 1-9. Are considered 32 bits long but can be converted by following them with a "L".

What's the purpose of the Finally Block

It's useful to force code to execute whether or not an exception is thrown. It's useful for IO operations to close files.

String class

Java's String class is used to represent a sequence (i.e., string) of characters. A simplified class diagram of String is shown below: STRING count : int value : char[] String() String(orig:String) length : int charAt(index:int) : char concat(st : String) : String equals(obj : String) : boolean indexOf(str : String) : int isEmpty() : boolean lastIndexOf(str : String) : int length() : int replace(oldChar : char , newChar : char) : String substring(beginIndex : int, endIndex : int) : String toLowerCase() : String toUpperCase() : String toString : String * Extends class Object and thus inherits Object's properties and behavior, including method equals(Object); * Encapsulates private fields (e.g., count and value), prevents direct access to these fields by other objects; indirect access is provided through public methods; e.g., the method length() provides access to the count field; * Has two overloaded constructors, String() and String(String s). The first constructor takes no parameters, and the second takes a String object that is copied into the new String object; * Overrides methods toString() and equals() inherited from class Object by providing its own implementations; * Exhibits polymorphism (one interface, multiple behaviors) with methods toString() and equals();

Cosine?

Math.cos(#)

find the max

Math.max (x, y);

larger value of x and y?

Math.max(x,y)

find the min

Math.min (x, y);

x^y

Math.pow (x, y);

Power or Exponent

Math.pow(x,y)

Random Number

Math.random()

Sine?

Math.sin(#)

sin x

Math.sin(x);

Square Root

Math.sqrt

Tangent?

Math.tan(x)

degrees to radians

Math.toRadians();

%

Mod/Remainder. Where: 1) Numerator is smaller than the denominator, % returns the numerator. 2) Numerator is 0, % returns 0. 3) Denominator of 0, % returns an error.

Binary Search

More efficient than a linear search, but only works if the indexes are in order/ are sorted.

switch....case use-age

Multi-coniditional branching. Used instead of the 'if' statement when a large number of outcomes need to be tested. Each case contains code that is executed if the switch argument takes on a particular value.

...

Multi-dimensional arrays can be initialized by placing the values that will populate the array in curly brackets. Each dimension is represented by a nested set of curly brackets. Example: int[ ][ ][ ] threeDArray = {{{1,2}, {3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}

...

Multi-dimensional arrays can declared with the new operator by placing the size of each dimension in square brackets. Example: int[ ][ ][ ] threeDArray = new int[3][2][2]

...

Multi-dimensional arrays do not have to declare the size of every dimension when initialized. Example: int[ ][ ][ ] array5 = new int[3][ ][ ]

...

Multi-dimensional arrays do not have to have the same size sub arrays. Example: int[ ][ ] oddSizes = {{1,2,3,4},{3 },{6,7}}

Class scope variables

Name for variables that are used in a class.

Parametric Polymorphism

Occurs with generic methods, where an actual type is substituted in for a type parameter. static <T> void print(T[] a) { for(T t : a) { System.out.printf("%s", t); } System.out.println(); }

'if' statement

Of the form 'if( [logical_expression] ) { statements; }'. where the statements in the *body* are executed if the logical expression argument in the header parentheses evaluates to true. Note that the entire structure is considered a single statement.

The break Statement

Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

Inheritance

One of the 3 main pinnacles of object-oriented programming (the others being encapsulation and polymorphism). Inheritance is a means by which a class extends another class, it acquires the properties and behavior of the class that's being extended. Sometimes called generalization/specialization, also called an "is a" relationship. For example, the class declarations of Book, Audio, and Periodical are shown below: package domain; public class Book extends LibraryItem { // properties and behavior of Book go here } package domain; public class Audio extends LibraryItem { // properties and behavior of Audio go here } package domain; public class Periodical extends LibraryItem { // properties and behavior of Periodical go here } class can only extend one other class -- cannot extend multiple classes

next()

One word String

public class{

Opens and names your program

Initializer List

Provides the initial values for the elements within an array.

declare a class

Public Class MemorizeThis {

Access Control

Public or Private; Determines how other objects made from other classes can use the variable, or if at all.

set up main method

Public static void main (string[], args) {

What are the three types of class variables?

Public, Allows them to be used in your own classes Static, allows them to be accessed vie that class name and a dot (.) separator Final, indicates that they are constants--- their values cannot change after they are initiated.

Double "

Quotation type used for string values.

Caching truth or falsity

Rather than constantly checking the truth of a logical expression, sometimes it is better to store the result in a boolean and use that subsequently. For example 'boolean isFlying = height > 0.5f; if(isFlying == true) { flapWings(); }'

Stores (points to) the memory address of an object

Reference variable

>

Relational operator: greater than

!=

Relational operator: not equals

boolean

Relational operators always result in a ________ value.

Syntax

Rules for combining words into sentences

Semantics

Rules for interpreting the meaning of statements

exceptions that usually occur because of code that isn't very robust.

Runtime Exceptions

When something goes wrong while the program is running. (Also known as exception)

Runtime error

Differences in String

S is Capitalized. Type of Object.

Data Type 'String'

Sequence of characters, a reference data type.

Java vocabulary

Set of all words and symbols in the language

name [row] [col] = value

Set the value of an element

Operators

Sets of which are associated with primitive datatypes, can be either unary or binary, depending on whether they require one variable or two (operands). E.g. addition, multiplication or increment.

What is a Vector?

Similar to ArrayList, but synchronized

Suppose that, when you run the following program, you enter input 2 3 6 from the console. What is the output? public class Test { public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); double x = input.nextDouble(); double y = input.nextDouble(); double z = input.nextDouble(); System.out.println((x < y && y < z) ? "sorted" : "not sorted");

Sorted

if

Specifies a block of code to be executed if a certain condition is true

What is program control?

Specifying the order in which statements(actions) execute in a program.

...

Standard Java arrays can be initialized with the new operator and their size in square brackets after the type. Example: int[ ] myArray = new int[4]

How many dimensions can standard Java arrays have?

Standard Java arrays can have one or many dimensions.

What can standard Java arrays store?

Standard Java arrays can store both objects and primitives.

Syntax to create a String

String s1 = new String("Hello World"); Can be created and initialized without using new: String s2 = "Hello World"; Can be concatenated with the + operator: String s3 = "Hello " + "World"; Operator == compares object references (and not the object's state), and since s1, s2 and s3 reference different String objects, == returns false: (s1 == s2); // returns false (s2 == s3); // returns false (s1 == s3); // returns false String's implementation of equals(Object) examines the values of the strings, this is true: s1.equals(s2); s2.equals(s3); s1.equals(s3); Strings objects created with the "new" operator that have the same value (the same string of characters) are always "equals()" to each other, but since they are different objects, they are never "==" to each other. One last subtle point: strings created using the double quote syntax with the same value without the new operator are always = = to each other. String s4 = "Hello World"; String s5 = "Hello World"; (s4 == s5); // returns true

How could you define a String variable named wrd and initialize it to the word cats?

String wrd = "cats";

string Array: Instantiation

String[] myArr = new String[numberOfItems]; String[] myArr = {"a","b","c"};

declare and initial string array, names, with length N

String[] names = new String [N];

Variable names

Strings of any length of letters, digits, underscores, and dollar signs that begin with a a letter, underscore, or dollar sign.

UML Diagrams - list the structure diagrams

Structure Diagrams - CCCODPP Composite Structure Class Component Object Deployment Profile Package

__________ method cannot throw more exceptions (either exceptions of different types or more general exception classes) than its superclass method.

Subclass

-

Subtraction operator

When you type something wrong and java doesn't compile (LANGUAGE)

Syntax error

Set of print commands to print to the console on two different lines?

System.out.print("Hello"); //no "ln" System.out.print("World"); //Has the "ln"

How do you print something in the output?

System.out.print("Something to print"); or System.out.println("Something to print with a line (LiNe)");

print (return) a command line input

System.out.println (args[0]);

Command to print to the console? (what letter is capitalized)

System.out.println("Hello");

Given: String firstName = "reynald"; Writhe the line of code to out the index of letter 'a'

System.out.println(firstName.indexOf('e')); v23

Create a generic class as in v58

TODO

Create an example of changing inheritance to composition by using interfaces. See exampled in v54.

TODO

Create an example of composition. Create a car class that HAS a gas tank. After the car runs 200miles, make it request to add gas.

TODO inspired by v49 (paper tray example)

Create an example of inheritance and using a constructor by writing a method that print the name passed into the constructor. In the super class, use the keyword 'protected'

TODO v48

Create an example using 'wild cards'

TODO v61

What is erasure?

TODO v62

Create an IllegalAurgumentException (with some error message) in a method & on the calling method, add a try / catch block to display your error.

TODO - video on Excepions -->Try / Catch

What is a 'Queue' in Java?

TODO: Create a queue

^

The ___ operator, called the "logical XOR", returns true if exactly one operand is true

What is the purpose of declaring a field private and declaring a mutator method that allows the public to change it.

The advantage of forcing the public to use a mutator method to change a field is that you can control how the field is changed.

What is the difference between exception and error?

The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.

2.4.1 a. lw $s0, 16($s7) add $s0, $s0, $sl add $s0, $s0, $s2 b. lw $t0, 16($s7) lw $s0, 0($t0) sub $s0, $sl, $s0 2.4.2 a. 3 b. 3 2.4.3 a. 4 b. 4

The following problems deal with translating from C to MIPS. Assume that the variables f, g, h, i, and j are assigned to registers $s0, $s1, $s2, $s3, and $s4, respectively. Assume that the base address of the arrays A and B are in registers $s6 and $s7, respectively. a. f = -g - A[4]; b. B[8] = A[i-j]; 2.4.1 [10] <2.2, 2.3> For the C statements above, what is the corresponding MIPS assembly code? 2.4.2 [5] <2.2, 2.3> For the C statements above, how many MIPS assembly instructions are needed to perform the C statement? 2.4.3 [5] <2.2, 2.3> For the C statements above, how many different registers are needed to carry out the C statement?

2.6.1 a. lw $s0, 4($s7) sub $s0, $s0. $sl add $s0, $s0, $s2 b. add $t0, $s7, $sl lw $t0, 0($t0) add $t0, $t0, $s6 lw $s0, 4($t0) 2.6.2 a. 3 b. 4 2.6.3 a. 4 b. 5

The following problems deal with translating from C to MIPS. Assume that the variables f, g, h, i, and j are assigned to registers $s0, $s1, $s2, $s3, and $s4, respectively. Assume that the base address of the arrays A and B are in registers $s6 and $s7, respectively. Assume that the elements of the arrays A and B are 4-byte words: a. f = f + A[2]; b. B[8] = A[i] + A[j]; 2.6.1 [10] <2.2, 2.3> For the C statements above, what is the corresponding MIPS assembly code? 2.6.2 [5] <2.2, 2.3> For the C statements above, how many MIPS assembly instructions are needed to perform the C statement? 2.6.3 [5] <2.2, 2.3> For the C statements above, how many registers are needed to carry out the C statement using MIPS assembly code?

2.4.4 a. f += g + h + i + j b. f = A[1] 2.4.5 a. no change b. no change 2.4.6 a. 5 as written, 5 minimally b. 2 as written, 2 minimally

The following problems deal with translating from MIPS to C. Assume that the variables f, g, h, i, and j are assigned to registers $s0, $s1, $s2, $s3, and $s4, respectively. Assume that the base address of the arrays A and B are in registers $s6 and $s7, respectively. a. sll $s2, $s4, 1 add $s0, $s2, $s3 add $s0, $s0, $s1 b. sll $t0, $s0, 2 # $t0 = f * 4 add $t0, $s6, $t0 # $t0 = &A[f] sll $t1, $s1, 2 # $t1 = g * 4 add $t1, $s7, $t1 # $t1 = &B[g] lw $s0, 0($t0) # f = A[f] addi $t2, $t0, 4 lw $t0, 0($t2) add $t0, $t0, $s0 sw $t0, 0($t1) 2.4.4 [10] <2.2, 2.3> For the MIPS assembly instructions above, what is the corresponding C statement? 2.4.5 [5] <2.2, 2.3> For the MIPS assembly instructions above, rewrite the assembly code to minimize the number if MIPS instructions (if possible) needed to carry out the same function. 2.4.6 [5] <2.2, 2.3> How many registers are needed to carry out the MIPS assembly as written above? If you could rewrite the code above, what is the minimal number of registers needed?

2.6.4 f = 2i + h ; f = A[ g - 3] ; 2.6.5 $so = 110 $so = 300 2.6.6 a. Type opcode rs rt rd immed add $s0, $s0, $sl R-type 0 16 17 16 add $s0, $s3, $s2 R-type 0 19 18 16 add $s0, $s0, $s3 R-type 0 16 19 16 b. addi $s6, $s6, -20 i-type 8 22 22 -20 add $s6, $s6 , $sl R-type 0 22q 17 22 lw $s0, 8($s6) i-type 35 22 16 8

The following problems deal with translating from MIPS to C. Assume that the variables f, g, h, i, and j are assigned to registers $s0, $s1, $s2, $s3, and $s4, respectively. Assume that the base address of the arrays A and B are in registers $s6 and $s7, respectively. a. sub $s0, $s0, $s1 sub $s0, $s0, $s3 add $s0, $s0, $s1 b. addi $t0, $s6, 4 add $t1, $s6, $0 sw $t1, 0($t0) lw $t0, 0($t0) add $s0, $t1, $t0 2.6.4 [5] <2.2, 2.3> For the MIPS assembly instructions above, what is the corresponding C statement? 2.6.5 [5] <2.2, 2.3> For the MIPS assembly above, assume that the registers $s0, $s1, $s2, and $s3 contain the values 0x0000000a, 0x00000014, 0x0000001e, and 0x00000028, respectively. Also, assume that register $s6 contains the value 0x00000100, and that memory contains the following values: Address Value 0x00000100 0x00000064 0x00000104 0x000000c8 0x00000108 0x0000012c Find the value of $s0 at the end of the assembly code. 2.6.6 [10] <2.3, 2.5> For each MIPS instruction, show the value of the opcode (OP), source register (RS), and target register (RT) fields. For the I-type instructions, show the value of the immediate field, and for the R-type instructions, show the value of the destination register (RD) field.

2.3.4 a. f = h - g b. f = g - f - 1 2.3.5 a. 1 b. 0

The following problems deal with translating from MIPS to C. Assume that the variables g, h, i, and j are given and could be considered 32-bit integers as declared in a C program. a. addi f, f, -4 b. add i, g, h add f, i, f 2.3.4 [5] <2.2> For the MIPS statements above, what is a corresponding C statement? 2.3.5 [5] <2.2> If the variables f, g, h, and i have values 1, 2, 3, and 4, respectively, what is the end value of f?

2.1.4. a. f = g + h b. f = g + h 2.1.5. a. 5 b. 5

The following problems deal with translating from MIPS to C. Assume that the variables g, h, i, and j are given and could be considered 32-bit integers as declared in a C program. a. addi f, f, 4 b. add f, g, h add f, i, f 2.1.4 For the MIPS assembly instructions above, what is a corresponding C statement? 2.1.5 If the variables f, g, h, and i have values 1, 2, 3, and 4, respectively, what is the end value of f?

2.2.4 a. f += h; b. f = 1 - f; 2.2.5 a. 4 b. 0

The following problems deal with translating from MIPS to C. For the following exercise, assume that the variables g, h, i, and j are given and could be considered 32-bit integers as declared in a C program. a. addi f, f, 4 b. add f, g, h sub f, i, f 2.2.4 [5] <2.2> For the MIPS assembly instructions above, what is a corresponding C statement? 2.2.5 [5] <2.2> If the variables f, g, h, and i have values 1, 2, 3, and 4, respectively, what is the end value of f?

2.5.4 a. 305419896 b. 319907022 2.5.5 a. Little-Endian Big-Endian Address Data Address Data 12 12 12 78 8 34 8 56 4 56 4 34 0 78 0 12 b. Address Data Address Data 12 be 12 0d 8 ad 8 f0 4 f0 4 ad 0 0d 0 be

The following problems explore the translation of hexadecimal numbers to other number formats. a. 0xabcdef12 b. 0x10203040 2.5.4 [5] <2.3> Translate the hexadecimal numbers above into decimal. 2.5.5 [5] <2.3> Show how the data in the table would be arranged in memory of a little-endian and a big-endian machine. Assume the data is stored starting at address 0.

2.1.1. a. add f, g, h add f, f, i add f, f, j b. addi f, h, 5 addi f, f, g 2.1.2. a. 3 b. 2 2.1.3. a. 14 b. 10

The following problems explore translating from C to MIPS. Assume that the variables f, g, h, and i are given and could be considered 32-bit integers as declared in a C program. a. f = g - h; b. f = g + (h - 5); 2.1.1 For the C statements above, what is the corresponding MIPS assembly code? Use a minimal number of MIPS assembly instructions. 2.1.2 For the C statements above, how many MIPS assembly instructions are needed to perform the C statement? 2.1.3 If the variables f, g, h, and i have values 1, 2, 3, and 4, respectively, what is the end value of f?

1.7.1 Geometric mean clock rate ratio= (1.28 x 1.56 x 2.64 x 3.03 x 10.00 x 1.80 x 0.74) 117 = 2.15 Geometric mean power ratio= (1.24 x 1.20 x 2.06 x 2.88 x 2.59 x 1.37 x 0.92) 117 = 1.62 1.7.2 Largest clock rate ratio = 2000 MHz/200 MHz = 10 (Pentium Pro to Pentium 4 Willamette) Largest power ratio= 29.1 W/10.1 W = 2.88 (Pentium to Pentium Pro) 1.7.3 Clock rate: 2.667 x 10^9/12.5 x 10^6 = 212.8 Power: 95 W/3.3 W = 28.78

The following table shows the increase in clock rate and power of eight generations of Intel processors over 28 years. Processor Clock Rate Power 80286 (1982) 12.5 MHz 3.3 W 80386 (1985) 16 MHz 4.1 W 80486 (1989) 25 MHz 4.9 W Pentium (1993) 66 MHz 10.1 W Pentium Pro (1997) 200 MHz 29.1 W Pentium 4 Willamette (2001) 2 GHz 75.3 W Pentium 4 Prescott (2004) 3.6 GHz 103 W Core 2 Ketsfield (2007) 2.667 GHz 95 W 1.7.1 What is the geometric mean of the ratios between consecutive generations for both clock rate and power? (The geometric mean is described in Section 1.7.) 1.7.2 What is the largest relative change in clock rate and power between generations? 1.7.3 How much larger is the clock rate and power of the last generation with respect to the first generation?

Target

The item being searched for in a search

return value

The value that comes back from a method after it is run. In the following method: public int calculateMonth(String name), the return value is an integer.

state

The values of all of the variables in an object at a given time.

Class Statement

The way you give your computer program a name.

Hexadecimal

These digits operate on a base-16 number These numbers use the letters A, B, C, D, E, and F along with the numbers 0 to 9 to create their 16 different digits, where A represents 10 and F represents 15. In programs written in the Java programming language must be preceded with 0x.

Floating Point Types

Those that contain fractional parts using significand digits and an exponent which represents its magnitude. Includes floats and doubles (32 and 64 bits respectively).

javax.swing.*;

To create lightwieght components for a GUI.

java.net.*;

To develop a networking application.

Collision

Two or more data values that hash to the same cell.

Variables

Used to store values that can be used repeatedly in a class

The comparing method: equals(Object)

Using equals(Object): boolean areEqual = book1.equals(book2); It compares object references, compares to see if book1 and book2 reference the same Book object in memory. In the example above, book1 and book2 reference different Book objects, so the boolean variable areEqual is set to false. This one would be true: Book book1 = new Book(); Book book2 = book1; boolean areEqual = book1.equals(book2);

What are the three ways to call a method?

Using the method name itself within the same class Using the object's variable name followed by a dot (.) and the method name to call a non static method of the object. Using the class name and a dot(.) to call a static method of a class: Math.pow

parameter

Variable passed to a method that provides more information for the method.

Float

Variable type of 32 bits and a range of [-3.4E38,3.4E38]

Double

Variable type of 64 bits and a range of [-1.7E308, 1.7E308]

Long

Variable type of 64 bits and with a range of [-9223372036854775808, 9223372036854775807]

Boolean

Variable type used to represent a single true or false value. Size of 1 bit.

Short

Variable type with a size of 16 bits and a range [-32768,32767 ]

Char

Variable type with a size of 16 bytes whose range is all Unicode characters. It has a minimum value of '\u0000' (or 0) and a maxiumum value of '\uffff' (or 65,534 inclusive)

Constants

Variables that do not change in value; typed in all-caps.

A remote control

What does a reference variable liken to?

The bits representing a way to get to an object on the heap.

What does a reference variable value have?

What an object knows and what an object does

What does an class define

It must return a value compatible with the declared return type.

What happens if a method declares a non-void return type?

A return type

What is always required with a method?

i

What is the standard convention for un-named variables?

A name and a type

What must variables must always be declared with?

false

What will print (or ERROR)?

At Runtime

When a Java program is nothing more than objects 'talking' to other objects.

What is counter controlled repetition?

When a loop is controlled by a counter such as x>3

What is sentinel controlled repetition?

When a loop is controlled by a sentinel value such as s!=3

Operator Precedence

When an expression includes one or more operators, this governs in what order the operations are carried out. For example, multiplication has a higher precedence than addition and so is carried out first. Each language has rules of precedence for all of it's operators.

What is Garbage Collection and how to call it explicitly?

When an object is no longer referred to by any variable, java automatically reclaims memory used by that object.

Truncation

When casting a larger type to a smaller type there may be a loss of information due to the truncation of additional bits or the fractional part of the number when casting from a floating point number to an integral number.

Unicode

When comparing characters, Java uses the ________ value of the character as the numerical value

object

When comparing reference variables, == returns true only if both references refer to the same ______

When should camel case be used?

When defining the type of an input: int greatNumber, dbl, char etc. When naming a method or class: class( QuadraticFormula), Method(equationProcessor)

Conditional Processing

Whereby a program can respond to changes due to the data on which it operates.

Strongly Typed

Whereby, in a language (Java), every variable and expression has a type *when the program is compiled*. You cannot arbitrarily assign the value of one type to another.

while(insert argument here) { insert code here }

While loop

Nesting Conditional Constructs

Within a code block, additional flow control structures can be nested. For example an if statement could be nested within the code block of another if statement, or a switch statement within the case of another switch statement. Note that stylistically, nesting results in further indentation so that flow can be followed easily.

Reserved words

Words that have predefined meanings that cannot be changed

int i = 10; do{ i = i + 5; System.out.print(i); } while (i > 5);

Write an endless do loop where i=10

int i = 10; while(i > 5){ i = i + 5; System.out.print(i); }

Write an endless while loop where i=10

if (i=10) { //do something } else { //do something else }

Write an if then else statement where i=10

if(i=10){ //do stuff }

Write an if then statement where i=10

System

a class that holds objects/methods to perform system-level operations, like output

'final' reference variables cannot refer to ...

a different object once the object has been assigned to the 'final' variable.

Coordinate system

a grid that allows a programmer to specify positions of points in a plane or of pixels on a computer screen

low-level programming language

a language that corresponds closely to a computer processors's circuitry

application software

a program that performs tasks for a user -ex. word processing, playing a games

A subclass outside the package cannot access ...

a protected member by using a reference to superclass instance.

A ________ is used to terminate all java

a semi colon ;

'abstract' methods end in ...

a semicolon - no curly braces.

object

a specific concrete instance of a class

procedural programming

a style of programming in which operations are executed one after the other in sequence

class

a term that describes a group or collection of objects with common properties

values[i] = 0;

access element of array at position i (count starts from 0)

What does ++c do? and what is it called? And --c?

adds 1 to c then prints out result. Prefix increment subtracts 1 from c then prints out result. Prefix decrement

The assert keyword must be followed by one of three things:

an expression that is true or false, a boolean variable, or a method that returns a boolean.

object-oriented programming

an extension of procedural programming in which you create classes, creating objects for those classes, and creating applications for the object

Associations

allow classes (and their objects) to form relationships with one another. These relationships facilitate object collaboration. two types of associations: "Has a" relationships: Abstracts/models the concept of containment (e.g., a Customer has an Account; or in other words, the Customer contains an Account). "Uses a" relationships: Abstracts/models the concept of using (e.g., a Workflow manager uses various services to accomplish a task [to get some work done]). "has a" relationship with another class if it has a data member of that particular type. package domain; public class User { private Account account = new Account(); } abstracting a Login class that contains the user's credentials (username, password) and associating it with the User by declaring Login data member: package domain; public class User { private Login login = new Login(); private Account account = new Account(); } Once you declare a data member as an object type, you have essentially created a "has a" relationship between the two objects. "uses a" relationship, only difference between a "has a" and "uses a" relationship is where the declaration is made. "uses a" relationships are defined within method declarations (and not as data members of the enclosing class). So for instance, suppose a particular method needs to use a Date object to timestamp a message: package domain; public class Logger { public generateLogMessage(String message) { Date date = new Date(); } } The above method instantiates a Date object locally within the scope of the method, not as a data member (at the class/object level). "uses a" relationship. So we can summarize "has a" and "uses a" relationships as follows: "Has a" relationships are realized as object declarations located at the class level (i.e., as data members). "Uses a" relationships are realized as object declarations located within the scope of a method.

high-level programming language

allows you to use a vocabulary of reasonable terms instead of sequences of 1s and 0s

Exception

an abnormal state or error that occurs during runtime and is signaled by the operating system

Logic error

an error such that a program runs, but unexpected results are produced. Also referred to as a design error

A method can have many of these.

argument

Array Element Access

arrayReference[index]

Arithemetic overflow

assigning a value to a variable that is outside of the ranges of values that the data type can represent

Iterable Interface

base interface for all interfaces of the Java collection framework (excluding Map). Iterable defines exactly one method, namely: Iterator iterator(); This allows you to get an Iterator for iterating over the elements of a collection. Since all other collection interfaces extend Iterable (either directly or indirectly), they all inherit the above method; that is, they all provide an iterator for iterating over their elements. For example, the Collection interface directly extends Iterable, and hence, if you have a Collection, you can get an iterator to iterate over its elements: Collection<Book> coll = getOverdueBooks(); Iterator<Book> iter = coll.iterator(); while (iter.hasNext()) { Book book = iter.next(); } Because the need to iterate over all items in a collection is a common practice, the method iterator() is placed in the base interface Iterable, and then through inheritance, it's made available to all collections that extend Collection (because Collection extends Iterable). The extension of Iterable by Collection (and then List, Set, and Queue) is known as interface inheritance.

Objects

belong to classes

True False data type

boolean

declare a boolean variable, isAscending

boolean isAscending;

&&, ||, !

boolean operators; and, or, not

Logical Type

boolean, with literals 'true' and 'false'. A logical variable can hold the result of a *logical expression*.

An open brace is always followed by a close

brace }

Never put a semi-colon before an open

brace{

Use a remainder assignment operator to make c=3 when c=12

c%=9

Application defined classes

classes that you create for your specific application Login -username : String -password : String +setUsername : (username : String) +getUsername () : String +setPassword : (password : String) +getPassword () : String +validate() : boolean +equals(Login Login) : boolean two private data members: username and password; the minus sign means the properties are hidden in the class, cannot access them outside of class. When a class does not explicitly provide a constructor, Java implicitly provides a default constructor (one that takes no arguments). The default constructor is available for use even though it's not shown.

Method returning an integer greater than, equal to, or less than 0 to indicate whether this string is greater than, equal to, or less than s1.

compareTo(s1) - it compares character by char. until difference in string letters found. - Then → returns an integer representing the difference in characters

variables

computer memory locations that hold values

software

computer programs

Interfaces can have ...

constants, which are always implicitly 'public', 'static', and 'final'.

Polymorphism

describes the way an object or variable my be treated in different contexts as though it was a different type. For example: inheritance allowes an argument of type B to be passed to a parameter of type A if B extends A. It is an object oriented programming feature that allow types to be treated as their parents or extending object.

What is the format of System.out.printf("%3d#%2s#%3.2f\n", 1234, "Java", 51.6653);

displays 1234#Java#51.67

declare and define a double, a, from command line argument

double a = Double.parseDouble(args[0]);

Exception Handling

events (e.g., errors) that disrupt the normal flow of execution. Examples of software exceptions: - Dividing by zero. - Using an unassigned object reference (that points to null) to invoke a method. - Failure to open/read/write/close a file. - Failure to open/read/write/close a socket connection. - Database errors. when a program executes, described as a call stack, ordered list of the active methods called up to the current point in time. stack starts with the main entry point and documents the active methods that are currently under call. once an exception occurs, it must be handled, or the program aborts. the JVM marches through the call stack looking for the nearest handler for the exception. If one is found, control is transferred. Otherwise, the program terminates.

In Java, the strange events that might cause a program to fail are called

exceptions

Defining Exceptions

exceptions are classes that extend the class Exception either directly or indirectly. For example, just a few of the many exceptions defined by the Java API. public class ClassNotFoundException extends Exception {...} public class IOException extends Exception {...} public class NullPointerException extends Exception {...} public class NumberFormatException extends Exception {...} The Exception class, most of its behavior is inherited from a base class named Throwable, which defines a message (String) property and a corresponding accessor, getMessage(). defining a custom exception that denotes a failed login: public class LoginFailedException extends Exception { public LoginFailedException() { super(); } public LoginFailedException(String msg) { super(msg); } } when defining your own exceptions, provide at least two constructors, default constructor and a constructor that takes a message string as a parameter. In both cases, the base constructor of Exception is invoked using the keyword super.

String variables name1 & name2 Write a fragment of code assigning the larger of the 2 to the variable first (NOTE: "larger" here means alphabetically larger, not "longer". Thus, "mouse" is larger than "elephant" bc "Mouse" comes later in the dictionary than "elephant"!)

if (name1.compareTo(name2) > 0 ) { first = name1; } else { first = name2; }

The first non-abstract (concrete) class to extend an 'abstract' class must ...

implement all the 'abstract' class' 'abstract' methods.

what are the members of a class?

include fields and methods and may also include constructors and initializers

++/--

increment/decrement; add 1 to/subtract 1 from the variable

\t

indicates a tab character

What does the keyword, Extends, do?

indicates that the class before the keyword is an enhanced type of the class following the keyword meaning that the methods and data from the class before the keyword are added on to the methods of the class after the keyword.

procedures

individual operations grouped together for connivence -in Java also called methods

What is a Class

is a collection of data fields that hold values and methods that operate on those values. A class defines a new reference type.

What is the body of a class

is a set of members enclosed in curly braces

ArrayList: grab item at index i

myArr.get(i);

ArrayList: get first index of item

myArr.indexOf(item);

ArrayList: get last index of item

myArr.lastIndexOf(item);

ArrayList: delete item at index i

myArr.remove(i);

ArrayList: get size

myArr.size();

HashMap: get a Set of the keys

myMap.keySet();

Keyword: new

new - creates Class objects and a constructor as shown below: Book book1 = new Book(); Book book2 = new Book("SomeTitle", "SomeAuthor", false); Constructors are invoked with the "new" keyword as shown below: Book book1 = new Book(); Book book2 = new Book(1); Book book3 = new Book(1, "Gone with the Wind", "Margaret Mitchell"); Using a constructor that allows you to initialize the object with passed-in parameters. Using the default constructor, followed by the invocation of set(...) methods.

Array Construction

new tymeName[length];

instantiation operator

new, third highest precedence, right to left association

String input = in.next();

next() reads the next string; returns any charas that are not white space

byte input

nextByte()

double input

nextDouble()

float input

nextFloat()

int input

nextInt()

short input

nextShort()

System.out.println( _____ );

prints the content in the parentheses ( _____ ) and moves to the next line

System.out.print( _____ );

prints the content in the parentheses ( _____) and remains on the same line

Constructor syntax

public class Book { // properties private String title = null; private String author = null; private boolean isCheckedout = false; // constructors public Book() { } public Book(String title, String author, boolean isCheckedout) { this.title = title; this.author = author; this.isCheckedout = isCheckedout; } } Two constructors: Book(), which is known as the default constructor Book(String title, String author, boolean isCheckedout) Default constructor - typically used to initialize properties to their "null" values, unless it is done when they are declared, then there is no need to have the first constructor. The 2nd constructor above, takes the passed parameters and assigns them to the class's properties (i.e., data members) using the keyword "this".

Basic definition of class for Book (library program)

public class Book { // properties private String title = null; private String author = null; private boolean isCheckedOut = false; // behavior public void checkOut () { isCheckedOut = true; } public void checkIn () { isCheckedOut = false; } }

Syntax to define a class

public class SomeClassName { // class properties and behaviors (methods) go here } keyword "public" is an access modifier, keyword "class" identifies the construct (i.e., the item) as a class definition, class name may contain alpha numeric characters, underscore, and $ (last two are rarely used). By convention, class names always start with an upper case letter, using CamelCase if there are more than one word.

Enum: Instantiate Enum for days of the week

public enum Day{ Monday(0),Tuesday(1), Wednesday(2), Thursday(3),Friday(4),Saturday(5),Sunday(6); private int value; private Day(int v){value = v;} public int getValue(){return this.value;} } //values() returns array of all constants defined in enum // valueOf() returns Enum with name matching to String passed to valueOf // Day.name() returns string name of enum

Write a class method

public static double radiansToDegrees (double radians) { return radians * 180 / PI; }

Constants declaration

public static final NAME = value;

Write a class field

public static final double PI=3.14159

How do you make a main method?

public static main(String[] args) { //Your program goes here! }

Standard Starting, to start code block?

public static void main(String[] args) { //code goes here }

Build a void method

public void main

access modifiers?

public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can't be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package.

'final' variables cannot be ...

re-initialized once assigned a value.

Set Interface

represents a collection of objects with no duplicates. By default, duplicates are identified by their equals(Object) method whose default behavior is defined in the root class Object. In other words, if equals(Object) is not overridden, object references will be used to determine if list entries are equal. If this behavior is not desired, equals(Object) needs to be overridden in the class for which objects are added to the set. A portion of the Set API is shown below. <<interface>> set +add(E) : boolean +addAll(Collection) : boolean +clear() : void +contains(Object) : boolean +containAll(Collection) : boolean +isEmpty() : boolean +remove(Object) : boolean +size() : int suppose the Library system has a business rule that prevents users from checking out more than one copy of a given book. During the checkout process, the user's books could be added to a Set collection where duplicate books are not added to the set. private Set booksCheckedOut = new HashSet(); public boolean checkout(Book book) { return booksCheckedOut.add(book); } The above method returns true if the book is not already in the set; otherwise, it returns false. If false is returned, the user would be notified that the duplicate book could not be checked out. Implementations of the Set interface include HashSet and TreeSet. The order of elements in a Set depends on the underlying implementation, and thus, will vary across implementations. If order is important, the interface SortedList should be used.

List Interface

represents an ordered sequence of objects. That is, elements are added to the list in a particular order, and the list maintains that order. suppose we have a List, booksCheckedIn, which contains all the books that are checked-in on a given day. Then, if we add books to the list as they are checked-in, the list will maintain the order in which they were checked-in. private List booksCheckedIn = new ArrayList(); public void checkin(Book book) { booksCheckedIn.add(book); } Implementations of the List interface include ArrayList, LinkedList, Stack, and Vector. List collections do not check for duplicate entries, so if an object is added multiple times, it will appear in the list multiple times (i.e., have multiple entries). Therefore, if it's important for a given object to appear only once in the collection, the Set interface should be used as explained below.

What keyword is used to jump out of a try block and into a finally block?

return

str.charAt(pos)

returns the character (char) at position pos (int) in the given string

str.length()

returns the number of characters in the given string (int)

str.indexOf(text)

returns the position (int) of the first occurrence of string (text) in string str (output -1 if not found)

str.substring(start, end)

returns the string starting at position (start) and ending at position (end-1) in the given string

How do we test things?

review - many people meet and examine/evaluate a code defect testing - test suite, a variety of user inputs and actions We should know the desired output first

LinkedList: remove methods

same as arraylist remove methods, but also: remove(); // removes first item from list removeLast(); //removes last item from list

String: get char at index i

str.charAt(i);

String: get first index of substring

str.indexOf(char); // returns -1 if doesn't exist

String: get last index of substring

str.lastIndexOf(char); // returns -1 if doesn't exist

String: get substring "He" from "Hello"

str.subString(0,2); // begin index is inclusive, end index is exclusive

String: concatenate two strings

str1.concat(str2); str1 + str2;

String: compare two strings

str1.equals(str2)

Class Constructors

special methods that are called when a class is created. Must have the same name as the enclosing class, and are declared with no return value (the implied return type of the constructor is the enclosing class type). public Book() {...} public Book(int id) {...} public Book(int id, String title) {...} public Book(int id, String title, String author) {...} public Book(int id, String title, String author, int pages) {...} Constructors can be overloaded. Once you define at least one constructor (whether default or not), the implicit, hidden default constructor is not provided for you. used to initialize the data members of the newly created object either by assigning default values or by using the passed-in parameters. Constructors can also invoke other constructors either in the same class or in a base class. public Book(int id) { super(id); } Above uses "super" keyword to invoke a constructor in the base class LibraryItem. Constructors are invoked with the "new" keyword

Java Applications

stand-alone programs which be subdivided into: -console applications which support character output to a computer screen in a DOS window -windowed applications which create GUI with elements such as menus, tool bars, and dialogue boxes

Calling a thread's _____ method causes its _____ method to be called

start() & run()

To run a thread what method must be callled?

start() method

Character.isDigit(ch)

statement (boolean), ch (char); allows you to check if ch is a digit or not

Character.isLetter(ch); Character.isUpperCase(ch); Character.isLowerCase(ch); Character.isWhiteSpace(ch);

statement (boolean), ch (char); allows you to check if ch is a letter/uppercase/lowercase/whitespace

while (condition) { statements }

statements = body of while loop; braces not needed for a single statement

Thread creation example

static public void main(String [] args) { // Not necessary to use an array Thread [] thAry = new Thread[3]; for(int i = 0; i < 3; i++) { Thread th = new MyThread(i); // create the thread thAry[i] = th; th.start(); // start the thread running } ... }

Runnable creation example

static public void main(String [] args) { for(int i = 0; i < 3; i++) { Runnable r = new MyRunnable(i); // create the Runnable object Thread th = new Thread(r); // create the thread for the object th.start(); // start the thread running }

Object references

stored in Object variables and denotes the memory location of an Object

It is legal to declare a local variable with ...

the same name as an instance variable; this is called shadowing.

state

the values and properties of an object

method

the verbs of a program

Chapter 1: Patterns don't give you code

they give you general solutions to design problems. You apply them to your specific application.

Keyword: this

this - used to disambiguate the overloaded use of variable names; in particular, "this" can be used to reference a data member (defined in the class) when that name is identical to a passed parameter. assigns the input parameter, title, to the data member, title: private String title = ""; public void setTitle(String title) { this.title = title; } inside the method setTitle(String title), the passed parameter, title, hides the data member, title, defined in the class. To access to the title data member, the keyword "this" is used to indicate a data member of the object is being referenced (and not a local variable inside the method).

If 1 of the operands of an || is false then the expression is _____?

true -- this is also known as the short-circuit OR operator

to "catch" a exception you must surround it with a ____ & _______

try & catch

Variable definition

typeName variableName = value;

What is method overloading? How do we accomplish this?

using the same method name with different parameter lists for multiple methods example, these two methods with same name can be used. public int sum(int numb1, int numb2){ } public int sum(int numb1, int numb2, int numb3){ }

string Var = "Hello"

variable Var = Hello (*double quotes!)

Method call/actual and formal for method name; No value, send parameters

variableName = methodName();

Chapter 1: Most patterns allow some part of a system to

vary independently of all other parts

Chapter 1: Patterns give us a shared _______

vocabulary

run-time errors

when a computer is asked to do something that is considered illegal

Method Overriding

when a method in a base class is repeated (redefined) in a derived class signature of both methods must match identically override its behavior in the LibraryItem to output the item's id and title as shown below: public class LibraryItem { ... public String toString() { return "LibraryItem, id=" + id + ", title: " + title; } } can invoke toString() to get a meaningful description of the object. Also true if the object is a Book, Audio, or Periodical because they inherit LibraryItem. Object obj = new Book(1, "Catch-22", "Joseph Heller", 485); String s = obj.toString(); actual instance is a Book and Book "is a" LibraryItem which overrides toString(), the LibraryItem's toString() method is called. Example of polymorphic dynamic binding; dynamic because it's not known until runtime which toString() method is invoked; it depends on whether the method is overridden, and if so, where. Can override toString in each of the more specialized classes: Book, Audio, and Periodical: public class Book extends LibraryItem { public String toString() { return super.toString() + ", Author, =" + author; } } super.toString() in the above return statement; its purpose is to invoke the toString() method in the base class LibraryItem. So the Book's overridden toString() method calls the LibraryItem's toString() method and then appends to it the author information that's contained in the Book. This time, since Book has overridden toString(), which overrides LibraryItem.toString(), which overrides Object.toString(), it's Book.toString() that gets called, and not the ones declared in Object or LibraryItem: Object obj = new Book(1, "Catch-22", "Joseph Heller"); String s = obj.toString(); another example of method overriding, consider the method equals(Object obj) defined by the Object class. to compare the state of two objects, overriding equals(Object obj) as shown below for LibraryItem: public class LibraryItem { public boolean equals(Object obj) { if (this == obj) return true; if ( ! (obj instanceof LibraryItem)) return false; LibraryItem item = (LibraryItem)obj; if ( this.id != item.id ) return false; if ( ! this.title.equals(item.title)) return false; return true; } } @override annotation - applied to methods that are intended to override behavior defined in a base class. annotation forces the compiler to check that the annotated method truly overrides a base class method. package domain; public class LibraryItem { @Override public String equals(Object obj) { ... } @Override public String toString() { ... } }

What is this "x+=3" the equivalent of?

x = x + 3;

Example using compound assignment

x+=1 • which is the same as → x = x + 1

A decrement operator

x--

Postdecrement

x-- "Give me x, then decrement"

Math.pow(x,y)

x^y (x>0, or x=0 and y>0, or x<0 and y is an integer)

Can you have 2 action listeners?

yes, but not ideal

Method overloading

you can define methods w.the SAME NAME in a class IF: • Enough difference in their parameter profiles.


Kaugnay na mga set ng pag-aaral

AP World History Chapter 9 Buddhism and Hinduism

View Set

ECN 001B Ch.5 Measuring a Nation's Income Quiz

View Set