Section 1

Preview this deck

Source file:

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

1

All-time users

2

Favorites

0

Last updated

5 years ago

Date created

Mar 1, 2020

Cards (750)

Section 1

(50 cards)

Source file:

Front

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

Back

Reserved words

Front

Words that have predefined meanings that cannot be changed

Back

Binary operator:

Front

An operator that has two operands.

Back

Syntax

Front

Rules for combining words into sentences

Back

Syntax rules:

Front

determine the validity of instructions in a programming language.

Back

Source code:

Front

The combination of the import statements and the program statements

Back

Computer program:

Front

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

Back

Arithemetic overflow

Front

assigning a value to a variable that is outside of the ranges of values that the data type can represent

Back

Cast operator:

Front

Used for explicit type conversion

Back

Objects

Front

sent messages

Back

Origin

Front

the point (0,0) in a coordinate system

Back

Mixed-mode arithmetic

Front

expressions imvolving integers and floating-point values

Back

Programming:

Front

A process of planning and creating a program.

Back

Name the 6 numeric data types

Front

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

Back

Semantic rules:

Front

determine the meaning of instructions in a programming language.

Back

Type casting

Front

allows one data type to be explicitly converted to another

Back

Operator precedence rules:

Front

Determine the order in which operations are performed to evaluate an expression.

Back

Data type:

Front

A set of values together with a set of operations.

Back

Primitive data types

Front

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

Back

Programming language:

Front

A set of rules, symbols, and special words.

Back

Run-time error

Front

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

Back

Variable declaration statement

Front

declares the identifier and data type for a variable

Back

What does /* suggest

Front

a comment

Back

Semantics

Front

Rules for interpreting the meaning of statements

Back

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

Front

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

Back

Unary operator:

Front

An operator that has only one operand.

Back

Screen coordinate system

Front

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

Back

Implicit type coercion:

Front

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

Back

Virus

Front

a program that can enter a computer and perhaps destroy information

Back

String concatenation

Front

append a string or value to another string

Back

Identifier:

Front

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.

Back

Pseudocode

Front

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

Back

How do you print something in the output?

Front

System.out.print("Something to print"); or System.out.println("Something to print with a line (LiNe)");

Back

Coordinate system

Front

a grid that allows a programmer to specify positions of points in a plane or of pixels on a computer screen

Back

Literals

Front

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

Back

Escape character (\)

Front

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

Back

Assignment operator:

Front

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

Back

Variable:

Front

A memory location whose content may change during program execution.

Back

Comments

Front

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

Back

Constants

Front

variables whose values cannot change

Back

Logic error

Front

an error such that a program runs, but unexpected results are produced. Also referred to as a design error

Back

Mixed expression:

Front

An expression that has operands of different data types.

Back

Named constant:

Front

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

Back

Exception

Front

an abnormal state or error that occurs during runtime and is signaled by the operating system

Back

console.nextDouble():

Front

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

Back

Graphics context

Front

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

Back

Token:

Front

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

Back

Arithmetic expressions

Front

a sequence of operands and operators that computes a value

Back

Package

Front

a group of related classes in a named directory

Back

Java vocabulary

Front

Set of all words and symbols in the language

Back

Section 2

(50 cards)

Application

Front

A program that runs locally, on your own computer.

Back

Describe 2 classes can have.

Front

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

Back

What are 6 assignment operators?

Front

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

Back

What is erasure?

Front

TODO v62

Back

Access Control

Front

Public or Private; Determines how other objects made from other classes can use the variable, or if at all.

Back

What is a 'set' in Java?

Front

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

Back

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

Front

Calls the default constructor on the Printer class.

Back

Name to things about strings in Java.

Front

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

Back

In OOP, describe is-a or has-relationships?

Front

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

Back

How do you create variables?

Front

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

Back

How do you make a Hello World program?

Front

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

Back

How do you create a method?

Front

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

Back

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

Front

int[] numbers = new int[3];

Back

Create an IllegalAurgumentException (with some error message) in a method & on the calling method, add a try / catch block to display your error.

Front

TODO - video on Excepions -->Try / Catch

Back

How do you make a main method?

Front

public static main(String[] args) { //Your program goes here! }

Back

What is a main method for?

Front

For letting your program run.

Back

How do you make loops?

Front

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

Back

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'

Front

TODO v48

Back

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.

Front

TODO inspired by v49 (paper tray example)

Back

Create an example using 'wild cards'

Front

TODO v61

Back

What are variables?

Front

Things that store information.

Back

Name 3 reasons why favor composition over inheritance

Front

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

Back

Applet

Front

A program that runs on a web page.

Back

Given: String firstName = "reynald"; Writhe the line of code to out the index of letter 'a'

Front

System.out.println(firstName.indexOf('e')); v23

Back

What's a method?

Front

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

Back

What is this "x+=3" the equivalent of?

Front

x = x + 3;

Back

What are checked & unchecked exceptions.

Front

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.

Back

Create an example of changing inheritance to composition by using interfaces. See exampled in v54.

Front

TODO

Back

What's a list in Java?

Front

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

Back

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

Front

TODO

Back

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.

Front

Exercise. v(32)

Back

What's the purpose of the Finally Block

Front

It's useful to force code to execute whether or not an exception is thrown. It's useful for IO operations to close files.

Back

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

Front

Map - Look in module about collections.

Back

Array

Front

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

Back

Create an example of Polymorphism that reflect v51

Front

TODO

Back

What is a 'Queue' in Java?

Front

TODO: Create a queue

Back

What is a primitive type in Java?

Front

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

Back

How do you make a Switch statement?

Front

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

Back

How do you make if...else statements?

Front

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.

Back

What are bounded types in Java?

Front

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

Back

How do you make a comment?

Front

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

Back

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

Front

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

Back

Name 9 primitive types

Front

BSILF DB CS byte short int long float double boolean char String

Back

appletviewer

Front

A tool included in the JDK that's supported in NetBeans, which will test applets.

Back

Argument

Front

Extra information sent to a program.

Back

How do you start a program?

Front

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

Back

Argument Storage

Front

An Array.

Back

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); } }

Front

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

Back

Create a generic class as in v58

Front

TODO

Back

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

Front

1. String[] colors = new String[] {"red","blue", "Green"}; 2. for (String c : colors){ System.out.println(c); } v42

Back

Section 3

(50 cards)

Object

Front

A way of organizing a program so that it has everything it needs to accomplish a task.

Back

Methods

Front

Part of an Object's behavior.

Back

Differences in String

Front

S is Capitalized. Type of Object.

Back

Unboxing

Front

Casts an object to the corresponding simple value.

Back

Multi-thread

Front

A way for the computer to do more than one thing at the same time.

Back

Autoboxing

Front

Casts a simple variable value to the corresponding class.

Back

Inheritance

Front

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

Back

Method

Front

A group of Attributes and Behaviors.

Back

main()

Front

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

Back

Attribute

Front

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

Back

Constants

Front

Variables that do not change in value; typed in all-caps.

Back

Thread

Front

Each part of a program which takes care of a different task.

Back

Subclass

Front

A class that inherits from another class.

Back

Casting

Front

Converting information from one form to another.

Back

Objects

Front

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

Back

Class

Front

A master copy of the object that determines the attributes and behavior an object should have.

Back

Source

Front

Information in it's original form.

Back

Concatenating

Front

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

Back

Boolean Values

Front

Type of variable that cannot be used in any Casting.

Back

Three types of Loops

Front

For, While, and Do-While.

Back

Attributes and Behaviors

Front

An object contains these two things.

Back

Class Statement

Front

The way you give your computer program a name.

Back

Single '

Front

Quotation type used for character values.

Back

Do While Execution

Front

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

Back

Variable

Front

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

Back

Double "

Front

Quotation type used for string values.

Back

Engaging in OOP

Front

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

Back

Ternary Operator

Front

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

Back

Comma

Front

Used to separate things within a section.

Back

Destination

Front

The converted version of the source in a new form.

Back

Superclass

Front

A class that is inherited from.

Back

Reason Brackets are missing

Front

Not required for single statement IF statements or Loops.

Back

Public int

Front

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

Back

char

Front

Any character. Surrounded by single quotation marks.

Back

OOP Program

Front

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

Back

String

Front

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

Back

Do While Loop

Front

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

Back

While Loop

Front

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

Back

Semicolon

Front

Used to separate sections.

Back

Behavior

Front

What an object does.

Back

Method

Front

A way to accomplish a task in a Java program.

Back

Statement

Front

An instruction you give a computer.

Back

Element

Front

An item in an Array.

Back

Loop

Front

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

Back

Iteration

Front

A single trip through a loop.

Back

Programs

Front

A class that can be used as a template for the creation of new objects.

Back

Platform Independent

Front

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

Back

For Loop

Front

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

Back

String

Front

A collection of characters. Surrounded by double quotation marks.

Back

Iterator

Front

The counter variable used to control a loop.

Back

Section 4

(50 cards)

public class{

Front

Opens and names your program

Back

Objects

Front

belong to classes

Back

System.out.print(" ");

Front

Prints a string of text

Back

Accessor

Front

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

Back

Object references

Front

stored in Object variables and denotes the memory location of an Object

Back

println

Front

Starts a new line after displaying the text.

Back

Identifiers may contain ...

Front

letters, digits and the underscore character

Back

Package

Front

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

Back

Assignment

Front

variableName = value;

Back

API documentation

Front

lists the classes and methods of the Java library

Back

Object reference

Front

a value that denotes the location of the object in memory

Back

Identifier

Front

name of a variable, method or class

Back

int

Front

a primitive data type, integer

Back

New operator

Front

An operator that constructs new objects

Back

Class Definition

Front

accessSpecifier class ClassName { constructors methods fields }

Back

Instance Field Declaration

Front

accessSpecifier class ClassName { accessSpecifer fieldType fieldName; }

Back

public static void main(String[] args){

Front

Line 2 of program, opens programming block

Back

length() method

Front

method which counts the number of characters in a String

Back

Method Definition

Front

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

Back

Method call

Front

object.methodName(parameters);

Back

Variable definition

Front

typeName variableName = value;

Back

toUpperCase

Front

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

Back

Cast

Front

(typeName) expression

Back

Declare a variable

Front

int n;

Back

trim() method

Front

method which removes leading and trailing spaces from a String

Back

Applet

Front

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

Back

Constant definition

Front

final typeName variableName = expression;

Back

Importing a Class from a Package

Front

import packageName.ClassName;

Back

Method

Front

a sequence of instructions that accesses the data of an object

Back

long totalMilliseconds = System.currentTimeMillis();

Front

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

Back

primitive

Front

data such as numbers and characters, NOT objects

Back

The RGB values of Color.RED

Front

255, 0, 0

Back

overloaded

Front

a class having more than one method with the same name

Back

Initialize a variable

Front

n = 5;

Back

The return Statement

Front

return expression;

Back

Declare & Initialize a variable

Front

int n = 5;

Back

JFrame

Front

used to show a frame(window)

Back

Expressions

Front

Statements that involve a mathematical equation and produce a result.

Back

-

Front

operator for subtraction

Back

Static method call

Front

ClassName.methodName(parameters);

Back

Variables

Front

Used to store values that can be used repeatedly in a class

Back

import java.util.Scanner;

Front

Import the ability to use a scanner from database

Back

Constructor Definition

Front

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

Back

*

Front

operator for multiplication

Back

Assignment operator

Front

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

Back

Object Construction

Front

ClassName objectName = new ClassName(parameters);

Back

Double var = input.nextDouble();

Front

Establishes value inputed into scanner as a variable

Back

Mutator

Front

Method that alters the attributes of an object.

Back

Public Interface

Front

specifies what you can do with its objects

Back

Scanner input = new Scanner(System.in);

Front

Adds scanner to program

Back

Section 5

(50 cards)

String: get last index of substring

Front

str.lastIndexOf(char); // returns -1 if doesn't exist

Back

String: concatenate two strings

Front

str1.concat(str2); str1 + str2;

Back

LinkedList: peek methods

Front

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

Back

HashMap: insert a key string and a value string

Front

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

Back

ArrayList: check if list contains item

Front

myArr.contains(item);

Back

||

Front

"Or" operator

Back

&

Front

Bitwise And operator

Back

The if Statement

Front

if (condition) statement; else statement;

Back

The while Statement

Front

while (condition) statement;

Back

LinkedList: iterate through list of strings and print each one

Front

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

Back

LinkedList<String>: Instantiation

Front

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

Back

ArrayList: replace item at index i with new item

Front

myArr.set(i, newItem);

Back

What is a Vector?

Front

Similar to ArrayList, but synchronized

Back

Array Element Access

Front

arrayReference[index]

Back

String: get first index of substring

Front

str.indexOf(char); // returns -1 if doesn't exist

Back

~

Front

Bitwise Not operator

Back

HashMap: get a Set of the keys

Front

myMap.keySet();

Back

The "for each" loop

Front

for (Type variable: collection) statement;

Back

ArrayList: add "hi" to ArrayList at index i

Front

myArr.add(i,"hi");

Back

HashMap<String, String>: Instantiation

Front

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

Back

ArrayList: delete item at index i

Front

myArr.remove(i);

Back

String: get char at index i

Front

str.charAt(i);

Back

ArrayList: get size

Front

myArr.size();

Back

HashMap: get value string from key string

Front

myMap.get("key");

Back

LinkedList: remove methods

Front

same as arraylist remove methods, but also: remove(); // removes first item from list removeLast(); //removes last item from list

Back

Enum: Instantiate Enum for days of the week

Front

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

Back

string Array: Instantiation

Front

String[] myArr = new String[numberOfItems]; String[] myArr = {"a","b","c"};

Back

LinkedList: add item to beginning of list

Front

-addFirst(item);

Back

HashMap: see if map contains a key

Front

myMap.contains("key");

Back

&&

Front

"And" operator

Back

ArrayList: get first index of item

Front

myArr.indexOf(item);

Back

ArrayList<String>: Instantiation

Front

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

Back

{}

Front

Defines a block of code

Back

!=

Front

Boolean not equal to

Back

HashMap: get a Collection of the values

Front

myMap.values();

Back

ArrayList: add "hi"

Front

myArr.add("hi");

Back

()

Front

used to surround perimeters

Back

Array Construction

Front

new tymeName[length];

Back

[]

Front

Declares arrays

Back

Block statement

Front

{ statement; statement; }

Back

|

Front

Bitwise Or operator

Back

String: remove whitespace

Front

str.trim();

Back

ArrayList: get last index of item

Front

myArr.lastIndexOf(item);

Back

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

Front

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

Back

String: get substring "He" from "Hello"

Front

str.subString(0,2); // begin index is inclusive, end index is exclusive

Back

Array: convert from Collection strs to Array

Front

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

Back

String: compare two strings

Front

str1.equals(str2)

Back

ArrayList: grab item at index i

Front

myArr.get(i);

Back

//

Front

comment

Back

The for Statement

Front

for (initialization; condition; update) statement;

Back

Section 6

(50 cards)

--

Front

Decrement by one

Back

Method that returns.

Front

Define the keyword "return"

Back

byte

Front

8 bit integer

Back

for( insert argument here) { insert code here }

Front

For loop

Back

;

Front

End of a statement

Back

*=

Front

Multiply and assign operator

Back

+

Front

add operator

Back

Method that does not return.

Front

Define the keyword "void"

Back

i

Front

What is the standard convention for un-named variables?

Back

=

Front

Assignment

Back

<

Front

Less than

Back

!

Front

Boolean not

Back

int i = 10; while(i > 5){ i = i + 5; System.out.print(i); }

Front

Write an endless while loop where i=10

Back

>=

Front

Greater than or equal to

Back

%

Front

Take remainder operator

Back

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

Front

Define the keyword "abstract"

Back

/=

Front

divide and assign operator

Back

short

Front

16 bit integer

Back

==

Front

Boolean equals

Back

int

Front

32 bit integer

Back

Null means nothing. It's a place holder.

Front

Define "Null"

Back

-

Front

Subtraction operator

Back

<=

Front

Less than or equal to

Back

if(i=10){ //do stuff }

Front

Write an if then statement where i=10

Back

%=

Front

Take remainder and assign operator

Back

.

Front

separates package names / adds folders

Back

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

Front

Define the keyword "catch"

Back

int i = 10; do{ i = i + 5; System.out.print(i); } while (i > 5);

Front

Write an endless do loop where i=10

Back

-=

Front

subtract and assign operator

Back

Only able to be modified inside the class.

Front

Define the keyword "private"

Back

boolean

Front

true or false

Back

if (i=10) { //do something } else { //do something else }

Front

Write an if then else statement where i=10

Back

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

Front

Define the keyword "public"

Back

while(insert argument here) { insert code here }

Front

While loop

Back

Does not change. Cannot make an instance of.

Front

Define the keyword "static"

Back

++

Front

Increment by one

Back

long

Front

64 bit integer

Back

public static void main(String args[])

Front

Main Method

Back

double

Front

64 bit real number

Back

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

Front

Write an endless for loop where i=10

Back

*

Front

Multiplication operator

Back

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

Front

Define the keyword "protected"

Back

used to implement an interface.

Front

Define the keyword "implements"

Back

+=

Front

Add and assign operator

Back

float

Front

32 bit real number

Back

/

Front

Division operator

Back

used to create a subclass for an existing class.

Front

Define the keyword "extends"

Back

char

Front

A single character

Back

do{ code here } while ( argument here);

Front

Do loop

Back

>

Front

Greater than

Back

Section 7

(50 cards)

for (initialization; condition; update) { statements }

Front

terminating loop

Back

Math.sqrt(x)

Front

square root of x

Back

System.out.print

Front

prints statement

Back

array.length

Front

gives the length of the array (no parentheses!)

Back

return volume;

Front

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

Back

values[i] = 0;

Front

access element of array at position i (count starts from 0)

Back

Math.exp(x)

Front

e^x

Back

string Var = "Hello"

Front

variable Var = Hello (*double quotes!)

Back

++/--

Front

increment/decrement; add 1 to/subtract 1 from the variable

Back

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

Front

compares equality of 2 strings

Back

char newChar = (char)(mychr + x)

Front

shift character by x numbers (use ASCII table values)

Back

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

Front

structure for commenting before methods (javadoc)

Back

/* */

Front

long comments

Back

str.substring(start, end)

Front

returns the string starting at position (start) and ending at position (end-1) in the given string

Back

str.equals("test")

Front

(boolean) returns true if the string "test" matches string str, false otherwise

Back

while (condition) { statements }

Front

statements = body of while loop; braces not needed for a single statement

Back

double blah = (int) (blah + 3)

Front

typecast; change variable type

Back

str.length()

Front

returns the number of characters in the given string (int)

Back

string1.compareTo (string2) < 0

Front

The compareTo method compares strings in lexicographic order.

Back

java SentinelDemo < numbers.txt

Front

redirects input

Back

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

Front

do/while loop

Back

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

Front

array declaration and initialization

Back

Math.sin(x)

Front

sine of x (x in radians)

Back

in.hasNextDouble()

Front

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

Back

&&, ||, !

Front

boolean operators; and, or, not

Back

public static double cubeVolume (double sideLength)

Front

header for method

Back

str.charAt(pos)

Front

returns the character (char) at position pos (int) in the given string

Back

char answer = 'y'

Front

variable answer = y (*single quotes!)

Back

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

Front

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

Back

if (condition) { statements1 } else { statements2 }

Front

if statement (else not required in all cases)

Back

Math.cos(x)

Front

cosine of x

Back

public static void boxString(String contents)

Front

void methods return no value, but can produce output

Back

final int VOLUME = 8

Front

names constant integer

Back

Math.tan(x)

Front

tangent of x

Back

int i = in.nextInt();

Front

declares and inputs integer value

Back

Math.pow(x,y)

Front

x^y (x>0, or x=0 and y>0, or x<0 and y is an integer)

Back

\

Front

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

Back

Character.isDigit(ch)

Front

statement (boolean), ch (char); allows you to check if ch is a digit or not

Back

String s = in.nextLine();

Front

declares and inputs a line (a string of characters)

Back

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

Front

% /number of spaces taken up/ Integer, variable

Back

double d = in.nextDouble();

Front

declares and inputs a real value (floating point #)

Back

import java.util.Scanner

Front

imports Scanner library

Back

Math.toRadians(x)

Front

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

Back

Math.toDegrees(x)

Front

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

Back

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

Front

body of method

Back

System.out.println

Front

prints statement and creates new line

Back

Scanner in = new Scanner(System.in);

Front

declares Scanner "in"

Back

str.indexOf(text)

Front

returns the position (int) of the first occurrence of string (text) in string str (output -1 if not found)

Back

//comment

Front

short comments

Back

Character.isLetter(ch); Character.isUpperCase(ch); Character.isLowerCase(ch); Character.isWhiteSpace(ch);

Front

statement (boolean), ch (char); allows you to check if ch is a letter/uppercase/lowercase/whitespace

Back

Section 8

(50 cards)

Constants

Front

Identifiers that always have the same value.

Back

new type [nRows] [nCols]

Front

Create a 2D array

Back

Class

Front

The data type of an object

Back

{ }

Front

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

Back

Void

Front

When a method does not return a value.

Back

Instantiation

Front

Creating an object.

Back

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

Front

Format types (printf)

Back

countryName = countryName.trim();

Front

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

Back

new int [5] [8] new Pixel [numRows] [numCols]

Front

Examples of creation of 2D arrays

Back

throws FileNotFoundException

Front

terminates main if FileNotFoundException occurs

Back

boolean

Front

A data type that represents a true or false value.

Back

Attribute

Front

A value an object stores internally.

Back

Concatenation

Front

Adding one string to another.

Back

Boolean Literal

Front

The words true and false.

Back

Encapsulation

Front

When each object protects its own information.

Back

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

Front

Example: Accessing two elements

Back

Assignment Statement

Front

A statement assigning a value to a variable.

Back

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

Front

ArrayList<typeParameter> variableName = new ArrayList<typeParameter>(); typeParameter cannot be a primitive type

Back

Integer.parseInt or Double.parseDouble

Front

obtains the integer value of a string containing the digits

Back

Arrays.copyOf(values, n)

Front

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.

Back

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

Front

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

Back

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

Front

writes output to a file "output.txt"

Back

Object

Front

An instance of a class.

Back

Method

Front

A group of programming statements given a name.

Back

Conversion

Front

Changing one type of primitive data to another.

Back

String input = in.next();

Front

next() reads the next string; returns any charas that are not white space

Back

int

Front

A data type that represents whole numbers.

Back

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

Front

restricts input to only letters, removes punctuation and numbers

Back

Polymorphism

Front

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

Back

Operator Precedence

Front

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

Back

name [row] [col]

Front

Access an element

Back

double

Front

A data type that represents decimals.

Back

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

Front

Example of setting the value of elements

Back

a.b()

Front

Execute a method b which belongs to object a

Back

Escape Sequence

Front

A sequence used to represent special characters.

Back

- 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

Front

Format flags (printf)

Back

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

Front

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

Back

b()

Front

A method called b

Back

name [row] [col] = value

Front

Set the value of an element

Back

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

Front

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

Back

String Literal

Front

Anything within double quotation marks.

Back

Inheritance

Front

How one class can be created from another.

Back

name.length

Front

Get the number of rows

Back

void

Front

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

Back

;

Front

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

Back

Primitive Data Types

Front

Eight commonly used data types.

Back

type[] [] name

Front

Declare a 2D array

Back

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

Front

Examples of 2D array declarations

Back

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

Front

elements separated by commas with brackets

Back

Variable

Front

A location in memory used to hold a data value.

Back

Section 9

(50 cards)

An open brace is always followed by a close

Front

brace }

Back

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

Front

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

Back

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

Front

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

Back

What escape sequence makes the backspace character?

Front

\b

Back

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

Front

double numero = 867.5

Back

______
______ is the escape sequence for

Front

new line

Back

...

Front

An ArrayList object can have its internal capacity adjusted manually to improve efficiency.

Back

...

Front

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}}}

Back

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

Front

System.out.println()

Back

How many dimensions can standard Java arrays have?

Front

Standard Java arrays can have one or many dimensions.

Back

...

Front

Multi-dimensional arrays do not have to have the same size sub arrays. Example: int[ ][ ] oddSizes = {{1,2,3,4},{3 },{6,7}}

Back

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

Front

// and / /

Back

What is the ArrayList class a representation of?

Front

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

Back

Can standard Java arrays be multi-dimensional?

Front

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

Back

What operator divides two numbers?

Front

/

Back

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

Front

funny

Back

Are there standard Java arrays built into the Java language?

Front

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

Back

_______\t________ is the escape sequence

Front

tab

Back

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

Front

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

Back

A ________ is used to terminate all java

Front

a semi colon ;

Back

...

Front

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}

Back

What is the ASCII value of 'A'?

Front

65

Back

...

Front

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]

Back

...

Front

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

Back

name[0].length

Front

Get the number of columns

Back

Never put a semi-colon before an open

Front

brace{

Back

What operator multiplies two numbers?

Front

*

Back

In Java, every program statement ends with what?

Front

; (a semicolon)

Back

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

Front

fun ny

Back

What is the ASCII value of 'a'?

Front

97

Back

...

Front

Multi-dimensional arrays do not have to declare the size of every dimension when initialized. Example: int[ ][ ][ ] array5 = new int[3][ ][ ]

Back

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

Front

"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.

Back

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

Front

abc

Back

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

Front

Example: get the number of columns

Back

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

Front

{ } (braces, or curly brackets)

Back

What escape sequence makes the newline character?

Front


Back

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

Front

\\

Back

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

Front

ab\c

Back

Work with ArrayList Objects and Their Methods

Front

...

Back

What can standard Java arrays store?

Front

Standard Java arrays can store both objects and primitives.

Back

matrix.length pixels.length

Front

Example of getting the number of rows

Back

Work with Java Arrays

Front

Chapter 6 Objective 1

Back

What package is the ArrayList part of?

Front

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

Back

....

Front

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

Back

What escape sequence makes the tab character?

Front

\t

Back

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

Front

ab"\c

Back

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

Front

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

Back

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

Front

int num = 394;

Back

How could you define a String variable named wrd and initialize it to the word cats?

Front

String wrd = "cats";

Back

...

Front

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]

Back

Section 10

(50 cards)

semantics

Front

define the rules for interpreting the meaning of statements

Back

double

Front

8 bytes, stores floating-point numbers

Back

objects

Front

second category of Java variables such as scanners and strings

Back

long

Front

4 bytes, stores long integer values

Back

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

Front

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

Back

Naming Methods?

Front

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

Back

Reasons to use "float"

Front

127 digits after the decimal point

Back

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

Front

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

Back

.java

Front

All Java file names have to have this extension.

Back

Define how java classes are connected.

Front

Loosely connected objects that interact with each other.

Back

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

Front

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

Back

How do you assign data to a variable?

Front

"=". ex. int number = 100

Back

Example of variable declaration and explanation.

Front

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

Back

How to define a class?

Front

public class "class name" (no extension)

Back

statements

Front

lines of code in java

Back

Private variable declaration?

Front

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

Back

concatenation operator

Front

allows strings to be combined in Java

Back

Command to print to the console? (what letter is capitalized)

Front

System.out.println("Hello");

Back

short

Front

2 bytes, stores integer values

Back

Standard Starting, to start code block?

Front

public static void main(String[] args) { //code goes here }

Back

Alphabetic characters that can be stored as a numeric value?

Front

char

Back

syntax

Front

the rules for combining words into sentences

Back

Capital Letter

Front

All java file names must have this at the beginning.

Back

What could a object be compared to for similarity?

Front

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

Back

Insert a comment? On multiple lines?

Front

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

Back

For numeric data types what declaration will always be used?

Front

double

Back

0 or more characters surrounded by double quotes?

Front

String (always capital "S")

Back

How to use sub-string function?

Front

...

Back

What must a class name always start with?

Front

A capital letter then camel case with no spaces.

Back

Surround all String text with?

Front

Double Quotes

Back

Reasons to use "double"

Front

1023 digits after the decimal point

Back

numeric data types

Front

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

Back

programming vs natural languages

Front

size, rigidity, literalness

Back

What must variable names have/not have?

Front

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

Back

int

Front

4 bytes, stores integer values

Back

True False data type

Front

boolean

Back

primitive data types

Front

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

Back

Set of print commands to print to the console on two different lines?

Front

System.out.print("Hello"); //no "ln" System.out.print("World"); //Has the "ln"

Back

Methods?

Front

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

Back

What is camel casing?

Front

Each time a new word begins start it with a capital letter

Back

Reasons to use "long"

Front

Numbers greater then ±2 billion

Back

What word is always capitalized in java syntax?

Front

String

Back

Reasons to use "int"

Front

Numbers -2 billion to, 2 billion

Back

vocabulary

Front

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

Back

4 Java Data Types?

Front

Numeric, String, Character, Boolean.

Back

String combination identifier

Front

"+"

Back

return function?

Front

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

Back

Numeric Data Sub-Types

Front

int, long, float, double

Back

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

Front

String

Back

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

Front

";"

Back

Section 11

(50 cards)

remainder or modulus operator

Front

%, fourth highest precedence, left to right association

Back

grouping operator

Front

( ), highest precedence

Back

multiplication operator

Front

*, fourth highest precedence, left to right association

Back

logic errors

Front

when the computer is unable to express an answer accruately

Back

method selector operator

Front

., second highest precedence, left to right association

Back

A no-argument constructor has....

Front

No parameters.

Back

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

Front

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

Back

division operator

Front

/, fourth highest precedence, left to right association

Back

A class is a type whose values are ______

Front

Objects

Back

Constructor?

Front

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

Back

Overloading the method?

Front

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

Back

unary plus operator

Front

+, third highest precedence

Back

Post Condition?

Front

What will be true after a method is called

Back

Private instance variables can be accessed from outside their class through ______ methods and changed with _________ methods

Front

Accessor methods && Mutator methods

Back

\t

Front

indicates a tab character

Back

assignment operator

Front

=, lowest precedence, right to left association

Back

literals

Front

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

Back

variable declaration statement

Front

when a program declares the type of a variable

Back

A local variable disappears when...

Front

a method invocation ends.

Back

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

Front

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

Back

Encapsulation?

Front

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

Back

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

Front

Parameter

Back

import x.y.z

Front

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

Back

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

Front

Methods && Instance Variables

Back

syntax errors

Front

when a syntax rule is violated

Back

Parameters are filled in with _________________ when invoking a method.

Front

Arguments

Back

arithmetic expression

Front

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

Back

Helper methods should be

Front

marked as private

Back

escape character

Front

used when including 'special characters' in string literals

Back

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.

Front

Private

Back

float

Front

4 bytes, stores less precise floating-point numbers

Back

addition operator

Front

+, fifth highest precedence, left to right association

Back

An object is this type of variable

Front

A reference variable

Back

cast operator

Front

(double),(int), third highest precedence, right to left association

Back

The two main kinds of methods:

Front

methods that return a value / void methods

Back

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

Front

True

Back


Front

indicates a newline character

Back

run-time errors

Front

when a computer is asked to do something that is considered illegal

Back

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

Front

setDate(int, int);

Back

keywords

Front

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

Back

\\

Front

escape character for backslash

Back

instantiation operator

Front

new, third highest precedence, right to left association

Back

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

Front

"this."

Back

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

Front

Local variable

Back

byte

Front

1 byte, stores an integer

Back

Objects have both _______ and _______.

Front

Instance Variables && Methods

Back

unary minus operator

Front

-, third highest precedence

Back

What is assumed to be true when a method is called

Front

Precondition

Back

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

Front

equals && toString

Back

subtraction operator

Front

-, fifth highest precedence, left to right association

Back

Section 12

(50 cards)

When you type something wrong and java doesn't compile (LANGUAGE)

Front

Syntax error

Back

blank.

Front

Value

Back

to convert data type

Front

Casting

Back

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

Front

println(x)

Back

Value: true/false

Front

boolean

Back

-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

Front

Casting Rules

Back

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

Front

Main method

Back

When something goes wrong while the program is running. (Also known as exception)

Front

Runtime error

Back

-Must end with a ; (semicolon)

Front

Statements

Back

float input

Front

nextFloat()

Back

-64 bits Range: -big to big No rules

Front

long

Back

-All programs start with a ? -Must have { and } -Identifier (name) begins with a CAPITAL letter EX: public class Westlake

Front

Class

Back

What are the TWO types of data contained by classes?

Front

Characteristics and Behavior

Back

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

Front

Identifiers (name) Rules

Back

-8 bits Range: -128 to 127 No rules

Front

byte

Back

Naming standard for mutator method?

Front

setXYZ();

Back

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

Front

Identity

Back

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

Front

short

Back

-Begins with a \ -Always comes in pairs

Front

Escape sequences

Back

New line

Front


Back

Prints x on the same line

Front

print(x)

Back

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

Front

Methods

Back

-64 bits Range: -big to big

Front

double

Back

"

Front

\"

Back

Backspace

Front

\b

Back

Naming standard for accessor method?

Front

getABC();

Back

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

Front

Mixing Data Types Rules

Back

Integer value: 48

Front

'0'

Back

Stores a specific type of value

Front

Primitive data types

Back

\

Front

\\

Back

'

Front

\'

Back

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

Front

char

Back

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

Front

Overflow error

Back

Tab

Front

\t

Back

byte input

Front

nextByte()

Back

Stores (points to) the memory address of an object

Front

Reference variable

Back

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

Front

String

Back

Integer value: 97

Front

'a'

Back

double input

Front

nextDouble()

Back

// marks the single line ? / block ? /

Front

Comments

Back

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

Front

Mixing Data Types Rules

Back

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

Front

float

Back

What kind of value and how much will be stored?

Front

Data Type

Back

short input

Front

nextShort()

Back

int input

Front

nextInt()

Back

-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

Front

Mixing Data Types Rules

Back

Integer value: 65

Front

'A'

Back

=

Front

Assignment Operator

Back

;

Front

Semicolon

Back

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

Front

int

Back

Section 13

(50 cards)

Loop count to 10

Front

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

Back

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

Front

variableName = methodName();

Back

//

Front

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

Back

Defining Parameters

Front

...

Back

Print statement

Front

System.out.println("");

Back

out

Front

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

Back

( )

Front

opening/closing parentheses; used in a method header

Back

println

Front

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

Back

String declaration

Front

String name = "";

Back

String comparing a to b

Front

a.compareTo("b");

Back

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

Front

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

Back

" "

Front

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

Back

print

Front

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

Back

Conditional operator

Front

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

Back

New tab character

Front

\t

Back

public static void main(String [ ] args)

Front

method header;

Back

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

Front

methodName(); public static void methodName():

Back

Instance variables

Front

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

Back

{ }

Front

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

Back

/t

Front

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

Back

public class _____

Front

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

Back

method

Front

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

Back

\\

Front

backslash; causes a backslash to be printed

Back

Build a void method

Front

public void main

Back

Instantiating an object

Front

class name object name = classname();

Back

New line character

Front


Back

System.out.print( _____ );

Front

prints the content in the parentheses ( _____) and remains on the same line

Back

Logical Operators

Front

&& ||

Back

Keyboard integer input

Front

keyboard.nextInt();

Back

Print format statement to get 3.14 of pi

Front

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

Back

System.out.println( _____ );

Front

prints the content in the parentheses ( _____ ) and moves to the next line

Back

System

Front

a class that holds objects/methods to perform system-level operations, like output

Back

String input

Front

next() nextLine()

Back

static

Front

One copy and everyone can see it

Back

nextLine()

Front

String of words

Back

/b

Front

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

Back

/** */

Front

opening comments

Back

Switch statement

Front

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

Back

/r

Front

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

Back

;

Front

semicolon; marks the end of a complete programming statement

Back

Emergency exit

Front

Sytem.exit(value);

Back

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

Front

...

Back

Constants declaration

Front

public static final NAME = value;

Back

Comparison operators: Equal to, Not equal to, greater than, greater than or equal to, less than, less than or equal to

Front

== != > >= < <=

Back

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

Front

Ans: D Section Ref: Section 7.1 Arrays

Back

Initialize scanner

Front

Scanner keyboard= new Scanner (System.in);

Back

next()

Front

One word String

Back

/n

Front

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

Back

Length method

Front

name.length()

Back

Build a return method

Front

public return

Back

Section 14

(50 cards)

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.

Front

Ans: B Section Ref: Quality Tip 8.3

Back

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.

Front

Ans: A Section Ref: Section 7.6 Common Array Algorithms

Back

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.

Front

Ans:B Section Ref: 8.1

Back

When you use a timer, you need to define a class that implements the ____ interface. A) TimerListener B) TimerActionListener C) ActionListener D) StartTimerListener

Front

Ans: C Section Ref: 9.10

Back

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

Front

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

Back

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.

Front

Ans: D Section Ref: 9.8

Back

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.

Front

Ans: C Section Ref: Section 7.6 Common Array Algorithms

Back

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.

Front

Ans: C Section Ref: 10.1

Back

Which of the following is an event source? A) A JButton object. B) An event listener. C) An inner class. D) An event adapter.

Front

Ans: A Section Ref: 9.7

Back

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();

Front

Ans: D

Back

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");

Front

Ans: D Section Ref: Section 7.2 Array Lists

Back

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

Front

Ans: D Section Ref: 8.9

Back

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.

Front

Ans: D Section Ref: 8.8

Back

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.

Front

Ans: A Section Ref: 8.5

Back

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.

Front

Ans: A Section Ref: 8.4

Back

A method that has no implementation is called a/an ____ method. A) interface B) implementation C) overloaded D) abstract

Front

Ans: D Section Ref: 9.1

Back

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").

Front

Ans: D Section Ref: 9.9

Back

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.

Front

Ans: B Section Ref: 10.3

Back

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

Front

Ans: D Section Ref: 10.2

Back

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.

Front

Ans: A Section Ref: 9.1

Back

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.

Front

Ans: A Section Ref: Section 7.6 Common Array Algorithms

Back

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

Front

Ans: D Section Ref: Section 7.2 Array Lists

Back

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()

Front

Ans: B Section Ref: Section 7.1 Arrays

Back

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.

Front

Ans: C Section Ref: 8.8

Back

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.

Front

Ans: C Section Ref: 10.2

Back

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.

Front

Ans: A Section Ref: 8.7

Back

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.

Front

Ans: A Section Ref: 8.4

Back

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

Front

Ans: D Section Ref: 9.3

Back

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

Front

Ans: B Section Ref: 8.2

Back

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.

Front

Ans: B Section Ref: 10.1

Back

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

Front

Ans: B Section Ref: 10.1

Back

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.

Front

Ans: C Section Ref: 9.9

Back

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); }

Front

Ans: C Section Ref: 9.7

Back

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.

Front

Ans: C Section Ref: 8.3

Back

____ are generated when the user presses a key, clicks a button, or selects a menu item. A) Listeners B) Interfaces. C) Events. D) Errors.

Front

Ans: C Section Ref: 9.7

Back

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.

Front

Ans: A Section Ref: Section 7.6 Common Array Algorithms

Back

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]

Front

Ans: C Section Ref: Section 7.2 Array Lists

Back

What is the type of a variable that references an array of integers? A) int[] B) integer() C) integer[] D) int()

Front

Ans: A Section Ref: Section 7.1 Arrays

Back

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.

Front

Ans: B Section Ref: 8.6

Back

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.

Front

Ans: C Section Ref: 8.5

Back

You access array list elements with an integer index, using the __________. A) () operator B) [] operator C) get method D) element method

Front

Ans: C Section Ref: Section 7.2 Array Lists

Back

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.

Front

Ans: A Section Ref: Section 7.1 Arrays

Back

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.

Front

Ans: C Section Ref: 9.11

Back

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

Front

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

Back

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.

Front

Ans: B Section Ref: 9.1

Back

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?

Front

Ans: C Section Ref: 8.1

Back

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.

Front

Ans: B Section Ref: Common Error 9.6

Back

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.

Front

Ans: A Section Ref: Special Topic 9.1

Back

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.

Front

Ans: B Section Ref: 8.2

Back

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)

Front

Ans: A Section Ref: Section 7.4 The Enhanced for Loop

Back

Section 15

(50 cards)

Exception

Front

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

Back

print (return)

Front

System.out.println();

Back

java.util.*;

Front

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

Back

double

Front

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

Back

int

Front

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

Back

java.awt.*;

Front

To paint basic graphics and images.

Back

==

Front

Used to equal a value

Back

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.

Front

Ans: A Section Ref: 10.7.1

Back

Literal

Front

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

Back

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

Front

Ans: B Section Ref: 10.7

Back

/ /

Front

Used to comment out a paragraph or longer

Back

b

Front

b

Back

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.

Front

Ans: A Section Ref: Special Topic 10.1

Back

declare a as an int

Front

int a;

Back

&&

Front

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

Back

b

Front

b

Back

Scope

Front

Block of code in which a variable is in existence and may be used.

Back

J2SE

Front

Acronym for Java 2 Platform, Standard Edition.

Back

java.lang.*;

Front

To utilize the core java classes and interfaces.

Back

declare a boolean variable, isAscending

Front

boolean isAscending;

Back

Relative Path

Front

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

Back

b

Front

b

Back

||

Front

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

Back

javax.swing.*;

Front

To create lightwieght components for a GUI.

Back

b

Front

b

Back

b

Front

b

Back

J2ME

Front

Acronym for Java 2 Platform, Micro Edition.

Back

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

Front

Ans: A Section Ref: Special Topic 10.1

Back

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.

Front

Ans: C Section Ref: Special Topic 10.1

Back

classpath

Front

An enviroment variable that includes an argument set telling the Java virtual machine where to look for user defined classes/packages.

Back

b

Front

b

Back

RuntimeException

Front

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

Back

JDK

Front

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

Back

Error

Front

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

Back

//

Front

Used to comment out a line.

Back

main loop

Front

public static void main (String[] args)

Back

J2EE

Front

Acronym for Java 2 Platform, Enterprise Edition.

Back

declare and define command line integer argument, a

Front

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

Back

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

Front

Ans: D Section Ref: 10.3

Back

java.net.*;

Front

To develop a networking application.

Back

final

Front

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

Back

java.io.*;

Front

To utilize data streams.

Back

JRE

Front

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

Back

print (return) a command line input

Front

System.out.println (args[0]);

Back

b

Front

bb

Back

byte

Front

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

Back

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.

Front

Ans: D Section Ref: 10.4

Back

String

Front

Can use +, ., and +=

Back

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.

Front

Ans: C Section Ref: 10.7.2

Back

The ____ reserved word in a method definition ensures that subclasses cannot override this method. A) abstract B) anonymous C) final D) static

Front

Ans: C Section Ref: Special Topic 10.2

Back

Section 16

(50 cards)

Declare and define integer a from double, b.

Front

int a = (int) b;

Back

not equal

Front

!=

Back

pen size to 0.05

Front

StdDraw.setPenRadius(0.05);

Back

set pen color

Front

StdDraw.setPenColor();

Back

sin x

Front

Math.sin(x);

Back

draw circle at (x, y) radius = r

Front

StdDraw.circle(x, y, r);

Back

cos x

Front

Math.cos(x);

Back

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

Front

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

Back

arc sin x

Front

Math.asin(x);

Back

square root of a

Front

Math.sqrt (a);

Back

to swap values of integers you need a...

Front

place holder

Back

declare and initial double array, points, with length N

Front

double[] points = new double [N];

Back

play 2001.mid

Front

StdAudio.play("2001.mid");

Back

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

Front

StdDraw.filledCircle(x, y, r);

Back

declare and initial string array, names, with length N

Front

String[] names = new String [N];

Back

read double

Front

StdIn.readDouble();

Back

if / else

Front

if (true) { } else { }

Back

degrees to radians

Front

Math.toRadians();

Back

x^y

Front

Math.pow (x, y);

Back

draw point at (x, y)

Front

StdDraw.point(x, y);

Back

for loop (use i and N)

Front

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

Back

short hand a = a * n

Front

a *= n;

Back

short hand a = a + 1;

Front

a++;

Back

std print

Front

StdOut.println();

Back

and

Front

&&

Back

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

Front

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

Back

first line of program, HelloWorld

Front

public class HelloWorld

Back

π

Front

Math.PI;

Back

declare and initial int array, number, with length N

Front

int[] number = new int [N];

Back

while

Front

while (true) { }

Back

random number between 1 and n

Front

1 + Math.random() * n;

Back

find the max

Front

Math.max (x, y);

Back

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

Front

double b = (double) a / b;

Back

arc cos x

Front

Math.acos(x);

Back

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

Front

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

Back

random number between 0 and 1

Front

Math.random();

Back

declare and define a double, a, from command line argument

Front

double a = Double.parseDouble(args[0]);

Back

remainder

Front

%

Back

read an integer

Front

StdIn.readInt();

Back

radians to degrees

Front

Math.toDegrees();

Back

short hand a = a + n;

Front

a += n;

Back

find the min

Front

Math.min (x, y);

Back

short hand a = a - 1;

Front

a--;

Back

set x and y window scale to -R , R

Front

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

Back

short hand a = a - n;

Front

a -= n;

Back

random number between 0 and n

Front

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

Back

absolute value of x - y

Front

Math.abs(x - y);

Back

draw "text" at (x, y)

Front

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

Back

boolean for empty

Front

StdIn.isEmpty()

Back

if statement (many commands)

Front

if (true) { }

Back

Section 17

(50 cards)

Modulus

Front

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

Back

'if' statement

Front

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.

Back

Primitive Variables

Front

Can store data values.

Back

Arithmetic Expression Type

Front

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.

Back

Java Type Categories

Front

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.

Back

Conditional Processing

Front

Whereby a program can respond to changes due to the data on which it operates.

Back

Caching truth or falsity

Front

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(); }'

Back

Selection Statements

Front

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

Back

Increment and Decrement Unary Operators

Front

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.

Back

Arithmetic Operators

Front

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

Back

Precedence and Parentheses

Front

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.

Back

Operator Precedence

Front

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.

Back

Casting Float Types to Integral Types

Front

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

Back

Promotion

Front

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).

Back

Initialization

Front

When you first store something in a variables memory location.

Back

String method length()

Front

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

Back

Logical Operators

Front

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

Back

Strings and escape sequences

Front

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.

Back

Floating Point Literals

Front

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++.

Back

if...else if... statement

Front

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.

Back

Data Type Sizes

Front

Fixed in Java, to ensure portability across implementations.

Back

Statement

Front

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

Back

Operator Overloading

Front

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.

Back

Prefix Operator

Front

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;'

Back

Reference Variables

Front

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

Back

String Literal

Front

Enclosed in double quotation marks. E.g. "Jonathan withey". This actually creates a String object to be referenced, for example 'String aString = "Character Sequence";'.

Back

Relational Operators and Floating Points

Front

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).

Back

Code Block

Front

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

Back

Reference Variable

Front

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.

Back

Demarcation and indentation

Front

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.

Back

Logical Expression

Front

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

Back

Declaration

Front

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

Back

Logical Type

Front

boolean, with literals 'true' and 'false'. A logical variable can hold the result of a logical expression.

Back

Strongly Typed

Front

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.

Back

Empty String

Front

A special string literal, denoted by "".

Back

flow control structures

Front

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

Back

Escape Sequence

Front

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 '
'.

Back

Integral Types

Front

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.

Back

String operator '+'

Front

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'.

Back

if...else statement

Front

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(); }'.

Back

Nesting Conditional Constructs

Front

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.

Back

Casting

Front

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.

Back

Literals

Front

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.

Back

Data Type 'String'

Front

Sequence of characters, a reference data type.

Back

Operators

Front

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.

Back

curly brackets and ;

Front

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

Back

Local Variables

Front

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 !.

Back

Relational Operators

Front

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.

Back

Char Type

Front

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

Back

Floating Point Types

Front

Those that contain fractional parts using significand digits and an exponent which represents its magnitude. Includes floats and doubles (32 and 64 bits respectively).

Back

Section 18

(50 cards)

This method is the engine of a threaded class.

Front

run()

Back

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.

Front

Errors

Back

What are the two subclasses of the throwable class?

Front

Error & Exception

Back

A thread can be created in two ways:

Front

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

Back

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

Front

Error & RuntimeExceptions

Back

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

Front

MalformedURLException

Back

when writting multiple catch clauses you should always start with ______

Front

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.

Back

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

Front

Threads

Back

__________ method cannot throw more exceptions (either exceptions of different types or more general exception classes) than its superclass method.

Front

Subclass

Back

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

Front

.getMessage() method

Back

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

Front

commas

Back

!

Front

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.

Back

switch example

Front

'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.

Back

switch....case use-age

Front

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.

Back

In Java, the strange events that might cause a program to fail are called

Front

exceptions

Back

exceptions that usually occur because of code that isn't very robust.

Front

Runtime Exceptions

Back

In Java, the strange events that might cause a program to fail are called

Front

exceptions

Back

What are the two subclasses of the throwable class?

Front

Error & Exception

Back

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

Front

printStackTrace()

Back

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

Front

catch clause

Back

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

Front

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

Back

switch default case

Front

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.

Back

&&

Front

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

Back

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

Front

NullPointerException

Back

switch...case form

Front

'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.

Back

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

Front

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

Back

Calling a thread's _____ method causes its _____ method to be called

Front

start() & run()

Back

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

Front

run()

Back

^

Front

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;'.

Back

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

Front

ArrayIndexOutofBounds

Back

What class should be the superclass of any exceptions you create in Java?

Front

Exception

Back

switch break

Front

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.

Back

What keyword is used to jump out of a try block and into a finally block?

Front

return

Back

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

Front

True

Back

switch fall-through

Front

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.

Back

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

Front

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.

Back

switch argument

Front

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

Back

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

Front

thows

Back

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

Front

"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."

Back

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

Front

might

Back

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

Front

Unchecked exceptions

Back

To run a thread what method must be callled?

Front

start() method

Back

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

Front

assertions

Back

Truncation

Front

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.

Back

to "catch" a exception you must surround it with a ____ & _______

Front

try & catch

Back

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

Front

EOFException

Back

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

Front

finally{ }

Back

||

Front

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

Back

switch selector value

Front

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 '=='.

Back

The assert keyword must be followed by one of three things:

Front

an expression that is true or false, a boolean variable, or a method that returns a boolean.

Back

Section 19

(50 cards)

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

Front

Error & RuntimeExceptions

Back

What keyword is used to jump out of a try block and into a finally block?

Front

return

Back

__________ method cannot throw more exceptions (either exceptions of different types or more general exception classes) than its superclass method.

Front

Subclass

Back

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

Front

MalformedURLException

Back

to "catch" a exception you must surround it with a ____ & _______

Front

try & catch

Back

when writting multiple catch clauses you should always start with ______

Front

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.

Back

Basic definition of class for Book (library program)

Front

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; } }

Back

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

Front

catch clause

Back

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

Front

assertions

Back

The assert keyword must be followed by one of three things:

Front

an expression that is true or false, a boolean variable, or a method that returns a boolean.

Back

This method is the engine of a threaded class.

Front

run()

Back

The Java Software Development Kit (JDK)

Front

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.

Back

Java bytecode

Front

A platform independent instruction set that's produced when Java source code is compiled.

Back

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

Front

commas

Back

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

Front

EOFException

Back

What is the syntax of a looping control flow example?

Front

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

Back

Declare the data type of a variable.

Front

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;

Back

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.

Front

Errors

Back

Calling a thread's _____ method causes its _____ method to be called

Front

start() & run()

Back

The Java Runtime Environment (JRE)

Front

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

Back

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

Front

finally{ }

Back

Are primitive data types considered objects in Java?

Front

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

Back

What is the syntax of a decision control flow example?

Front

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

Back

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

Front

run()

Back

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

Front

"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."

Back

JSE JEE JME Java Card

Front

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).

Back

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

Front

thows

Back

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

Front

True

Back

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

Front

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

Back

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

Front

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

Back

UML Diagrams - list the structure diagrams

Front

Structure Diagrams - CCCODPP Composite Structure Class Component Object Deployment Profile Package

Back

What class should be the superclass of any exceptions you create in Java?

Front

Exception

Back

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

Front

Threads

Back

8 primitive data types

Front

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 -)

Back

What is the syntax of a sequence control flow example?

Front

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

Back

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

Front

printStackTrace()

Back

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

Front

might

Back

Definition of class

Front

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.

Back

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

Front

.getMessage() method

Back

Syntax to define a class

Front

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.

Back

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

Front

ArrayIndexOutofBounds

Back

Java Virtual Machine (JVM)

Front

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

Back

To run a thread what method must be callled?

Front

start() method

Back

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

Front

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

Back

exceptions that usually occur because of code that isn't very robust.

Front

Runtime Exceptions

Back

How do you declare a CONSTANT in Java?

Front

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

Back

A thread can be created in two ways:

Front

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

Back

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

Front

Unchecked exceptions

Back

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

Front

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.

Back

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

Front

NullPointerException

Back

Section 20

(50 cards)

Application defined classes

Front

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.

Back

JSE JEE JME Java Card

Front

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).

Back

Queue Interface

Front

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.

Back

Keyword: new

Front

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.

Back

Keyword: this

Front

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).

Back

Defining Exceptions

Front

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.

Back

List Interface

Front

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.

Back

Java Collection Framework

Front

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.

Back

Objects example illustrated

Front

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

Back

polymorphism

Front

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.

Back

Java Virtual Machine (JVM)

Front

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

Back

Package

Front

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)

Back

The Java Software Development Kit (JDK)

Front

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.

Back

Class Constructors

Front

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

Back

Importing packages

Front

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()

Back

Method overloading

Front

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.

Back

Set Interface

Front

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.

Back

The comparing method: equals(Object)

Front

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);

Back

Associations

Front

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.

Back

Arrays

Front

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.

Back

Declaring a class to a package

Front

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.

Back

Constructor syntax

Front

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".

Back

Access Modifiers

Front

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

Back

Throwing & Catching Exceptions

Front

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.

Back

Inheritance

Front

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

Back

Objects...

Front

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

Back

Declaring Exceptions

Front

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.

Back

Iterable Interface

Front

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.

Back

Predefined Java classes

Front

Example of 2: Object class & String class

Back

Method Overriding

Front

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() { ... } }

Back

String class

Front

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();

Back

static fields and methods

Front

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).

Back

method toString()

Front

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().

Back

Syntax to create a String

Front

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

Back

The Java Runtime Environment (JRE)

Front

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

Back

Default (no modifier)

Front

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() { } }

Back

Constructors are special methods defined in a class that are used to initialize ___ ___.

Front

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.

Back

Object class

Front

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 {...}

Back

Java bytecode

Front

A platform independent instruction set that's produced when Java source code is compiled.

Back

Collection Interface

Front

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.

Back

Private

Front

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 } }

Back

Public modifier

Front

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() { } }

Back

Maps

Front

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};

Back

Inner & Anonymous Classes

Front

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.

Back

UML Class diagram w/ general syntax

Front

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).

Back

Exception Handling

Front

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.

Back

Protected modifier

Front

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(); } }

Back

Abstract Classes & Interfaces

Front

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.

Back

UML Diagrams - list the behavior diagrams

Front

Behavior Diagrams - STIACUS Sequence Timing Interactive Activity Communication Use Case State

Back

Software Layers and responsibilities

Front

* 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

Back

Section 21

(50 cards)

Arrays

Front

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.

Back

Syntax to define a class

Front

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.

Back

UML Class diagram w/ general syntax

Front

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).

Back

Predefined Java classes

Front

Example of 2: Object class & String class

Back

Declaring a class to a package

Front

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.

Back

Private

Front

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 } }

Back

UML Diagrams - list the structure diagrams

Front

Structure Diagrams - CCCODPP Composite Structure Class Component Object Deployment Profile Package

Back

8 primitive data types

Front

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 -)

Back

Basic definition of class for Book (library program)

Front

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; } }

Back

What is the syntax of a decision control flow example?

Front

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

Back

Object class

Front

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 {...}

Back

Public modifier

Front

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() { } }

Back

Are primitive data types considered objects in Java?

Front

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

Back

Abstract Classes & Interfaces

Front

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.

Back

Software Layers and responsibilities

Front

* 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

Back

method toString()

Front

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().

Back

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

Front

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

Back

Declare the data type of a variable.

Front

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;

Back

Java Collection Framework

Front

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.

Back

Package

Front

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)

Back

How do you declare a CONSTANT in Java?

Front

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

Back

Iterable Interface

Front

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.

Back

Constructor syntax

Front

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".

Back

Access Modifiers

Front

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

Back

Definition of class

Front

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.

Back

Class Constructors

Front

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

Back

polymorphism

Front

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.

Back

Collection Interface

Front

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.

Back

Protected modifier

Front

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(); } }

Back

Default (no modifier)

Front

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() { } }

Back

Method overloading

Front

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.

Back

static fields and methods

Front

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).

Back

The comparing method: equals(Object)

Front

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);

Back

Inheritance

Front

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

Back

Method Overriding

Front

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() { ... } }

Back

Keyword: new

Front

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.

Back

Associations

Front

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.

Back

Keyword: this

Front

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).

Back

Inner & Anonymous Classes

Front

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.

Back

Objects example illustrated

Front

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

Back

What is the syntax of a sequence control flow example?

Front

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

Back

Maps

Front

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};

Back

Syntax to create a String

Front

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

Back

Constructors are special methods defined in a class that are used to initialize ___ ___.

Front

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.

Back

What is the syntax of a looping control flow example?

Front

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

Back

UML Diagrams - list the behavior diagrams

Front

Behavior Diagrams - STIACUS Sequence Timing Interactive Activity Communication Use Case State

Back

Objects...

Front

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

Back

String class

Front

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();

Back

Application defined classes

Front

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.

Back

Importing packages

Front

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()

Back

Section 22

(50 cards)

Method overriding

Front

Subclass method can override methods from abstract or concrete classes. Within a subclass an override method in the super can still be called with super.method().

Back

Dynamic binding

Front

the subclass' behaviour will occur even though the client does not know it is using the subclass object.

Back

Overriding*

Front

Overriding and overloading support polymorphism. - Abstract class (or concrete class) implement method - subclass with same signature override superclass method. - JVM begins at bottom of type hierarchy and searches up until match found to determine which method to run. - within subclass can call superclass method with super.method()

Back

Local variables (field)

Front

Defined inside methods, constructors or blocks. Initialized within method and destroyed when method complete.

Back

Java portability

Front

Java source code (.java) > Java compiler > Java bytecode program (.class or .jar) > OS Just In Time (JIT) compiler > OS machine code

Back

Applying Encapsulation*

Front

- Make fields private - make accessors (getters) and mutators (setters) public - make helper (utility) methods private

Back

this.method()

Front

calls an instance method in the current class.

Back

Encapsulation*

Front

- data hiding - make fields in class private, accessible via public methods - protective barrier against outside code - access is controlled by interface - Alter code without affecting those that use it

Back

Throwing & Catching Exceptions

Front

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.

Back

List Interface

Front

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.

Back

char

Front

16 bit unicode character

Back

Inheritance*

Front

Process where one object acquires the properties of another.

Back

short

Front

16 bit, useful if memory an issue

Back

byte

Front

8 bit, useful if memory an issue

Back

extends

Front

Back

Long

Front

unsigned long

Back

System.out.println("Hello")

Front

Prints Hello to console on a new line.

Back

JSE API

Front

Java Standard Edition Application Programming Interface Libraries

Back

int

Front

32 bit

Back

Java

Front

- object oriented - architecture neutral - portable - fast -secure -network aware - syntax based on C and C++

Back

this

Front

Denotes current object. Resolves ambiguity problems. this.tree = tree;

Back

Queue Interface

Front

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.

Back

Java Runtime Environment (JRE)

Front

Interpreter for compiled Java byte code programs. = Java Virtual Machine (JVM)

Back

Scanner keyboard = new Scanner(System.in); x = keyboard.nextInt(); y = keyboard.nextLine();

Front

Use scanner for keyboard input. nextInt() scans in next token as an integer nextLine() scans in current line

Back

Defining Exceptions

Front

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.

Back

Abstract Data Types

Front

Model of a data structure e.g. Stack(). Describes the behaviour of the data type.

Back

Boolean

Front

true or false

Back

BufferedReader stdin = new BufferedReader(new InputStreamReader(system.in)) input = stdin.readLine();

Front

Create BufferedReader instance containing a InputStreamReader instance with byte stream as input.

Back

Abstraction (extend)

Front

- Segregation of implementation from interface. - cannot be instantiated - Partial implementation - Class can only extend one abstract class

Back

Interfaces (implement)

Front

- Abstract methods. All methods are public. - Cannot be instantiated. - Class that 'implements' an interface inherits its abstract methods.

Back

Exception Handling

Front

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.

Back

Java Development Kit (JDK)

Front

Java compiler and interpreter. includes JRE and JSE API

Back

Program

Front

set of classes, one with a 'main' method (.java)

Back

this()

Front

invokes the constructor.

Back

Protected

Front

Accessible if in same package.

Back

Class variables

Front

Declared with 'static' keyword. In class but not in methods. One per class - if it is set to 5 and an object changes it to 6 it will then be changed to 6 for all instances of the class.

Back

Package

Front

set of classes with a shared scope, typically providing a single coherent 'service' e.g. FilmFinder package

Back

Set Interface

Front

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.

Back

this.field

Front

accesses an instance variable in the current class

Back

Polymorphism*

Front

Able to perform operations without knowing the subclass of the object (just superclass). Apply the same operation on values of different types as long as they have common ancestor. * parent class reference is used to refer to a child class object - program decides which to run at run time

Back

static

Front

means only one copy exists of the field or method and it belongs to the class not an instance. Its shared between all instances of the class.

Back

Declaring Exceptions

Front

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.

Back

Does Java have multiple inheritance?*

Front

No. Instead deal with interfaces.

Back

Integer

Front

unsigned int, 0 -> 2^31 -1

Back

long

Front

64 bit

Back

Public

Front

Accessible by all.

Back

Benefits of Encapsulation*

Front

Maintainability, Flexibility and Extensibility.

Back

Instance variables

Front

- variables inside class but not in methods - instantiated when class loaded - accessed by any method in class

Back

Private

Front

only accessible if in same class.

Back

OO definitions

Front

Programming paradigm that views programs as cooperating objects, rather than sequences of procedures Focuses on design of abstract data types, which define possible states and operations on variables of that type

Back

Section 23

(50 cards)

Benefits of Refactoring

Front

- Reduces maintenance problems - Reduces probability of errors - Reduces duplicated code.

Back

Methods rule (subtypes)

Front

Calls to the subtype methods must behave like calls to the corresponding supertype method.

Back

Maps

Front

- maps keys to values - can have duplicate keys - each key maps to one value

Back

Interface rules

Front

1. Exceptions should be declared by interface method. 2. Signature and return type should be the same for interface and implemented class. 3. A class can implement multiple interfaces. 4. An interface can extend another interface.

Back

final

Front

- prevents class from being extended or overridden - prevents variables from being altered = constant

Back

HashSet

Front

data is stored in a table with an associated hash code. Has code is used as an index. Contain NO duplicates, elements kept in order.

Back

Bounded generic types

Front

restrict the actual type parameter allowed and can be specified by saying which class the allowed types extend. - effect = permits subtypes of the class. can have: - object of subtype B where object of its supertype A is expected.

Back

Software Patterns

Front

- Reusable solution to common problem. - Description/Template

Back

Glass box

Front

Testing code (can see code)

Back

TDD Mantra

Front

1. Create new tests that fail (RED) 2. Write code to pass the test (GREEN) 3. Refactor

Back

Dummies

Front

tests objects that are never used but exist only to satisfy syntactic requirements.

Back

Refactor - replace error code with exception

Front

A method returns a special code to indicate an error - throw an exception instead.

Back

iterator()

Front

Iterator<String> iter = names.iterator(); while(iter.hasNext()){ System.out.println(iter.next()); }

Back

Glass box steps

Front

Ensure 1. Statement coverage (every statement is executed at least once. 2. Branch coverage (each condition is evaluated at least once). 3. Path coverage (all control flow paths are executed at least once).

Back

Types of Lists

Front

ArrayList: resizable array LinkedList: FIFO Stack: LIFO Vector: deprecated

Back

Types of sets

Front

HashSet<E>: unordered TreeSet<E>: ordered based on value LinkedHashSet<E> : insertion ordered

Back

Basic Enum class

Front

public enum Level { HIGH, MEDIUM, LOW } //Assign it Level level = Level.HIGH;

Back

Lists

Front

- ordered sequence of elements - indexable by individual elements or range - elements can be insereted at or removed from any position - can have duplicates

Back

Pass by value

Front

- Primitive types - makes a copy so does not affect original

Back

Observable

Front

Use instead of Subject interface for Observer pattern, Observable aware of its status and it's Observers unlike Subject.

Back

Sets

Front

- No Duplicates - Usually unordered

Back

Test Driven Development (TDD)

Front

1. Tests developed before code is written. 2. Once code passes, new tests added 3. Code extended to pass new tests and refactored if necessary. Create tests you know will fail because you know implementation not in place.

Back

Collections

Front

- Compound data type that groups multiple elements of the same type together. - Encapsulates the data structure needed to store the elements and the algorithms needed to manipulate them. - Group of elements of the same type

Back

Type parameter

Front

<X> ...of type X. <String> is of type String. <Tree> is a Tree object

Back

Refactoring Techniques

Front

1. Extract Method 2. Extract Class 3. Rename 4. Move class 5. Replace conditional with Polymorphism 6. Decompose conditional 7. Encapsulate collection 8. Replace error code with exception 9. Split Loop

Back

Enum

Front

enumerated type of class. - list of constants. - use when need predefined list of values that do not represent values of textual data

Back

Properties rule (subtypes)

Front

Subtypes must preserve all of the provable properties of the supertype. Anything provable about A is provable about B.

Back

Black box

Front

Testing to specifications (code unseen)

Back

Types of Queues

Front

ArrayDeque: double ended ArrayBlockingQueue: fixed capacity, FIFO PriorityQueue: ordered based on value

Back

Hamcrest

Front

framework to help write JUnit test cases. assertThat("HelloClass", is(equalTo(Greeter.greeting())))

Back

Assertion code

Front

assert boolean_expression; assert boolean_expression : displayable_expression;

Back

Refactor - split loop

Front

You have a loop doing two things - duplicate the loop. for(Tree tree : trees) // do x // do y Will be separated into two loops, one doing x and the other doing y.

Back

Observer Pattern

Front

- Synchronises state and/or responses across a collection of objects in response to an event. - Have Observer and Subject - Observer queries Subject to determine what was the change of state and responds appropriately based on Subjects new state. - Subject adds observers, sets state and gets state.

Back

Subtype rules

Front

1. Signature rule 2. Methods rule 3. Properties rule

Back

Types of Maps

Front

HashMap: unordered, use for max speed TreeMap: ordered by key LinkedHashMap: inseretion ordered.

Back

Arrays

Front

are NOT collections. Do NOT: 1. support iterators 2. grow in size at runtime 3. are not threadsafe Primitive types of a fixed size.

Back

3 different groups of patterns

Front

1. Creational: managing the creation of objects 2. Structural: provide a more workable interface for client code. 3. Behavioural: managing common interactions

Back

Fakes

Front

test objects with working methods but have limited functionality.

Back

Stubs

Front

test objects whose methods return fixed values and support specific test cases only.

Back

Signature rule (subtypes)

Front

Subtypes must have signature-compatible methods for all of the supertypes methods. ArrayList<String> is a subtype of List<String>

Back

Generics

Front

- accept another type as a parameter - collections <E> <X>

Back

Assertions

Front

Assert that particular state must be true for program to proceed. Used for defensive programming and can be basis of formal programming proofs.

Back

Refactor - extract method

Front

You have a code fragment that can be grouped together: turn the fragment into a method with a self-explanatory name.

Back

Mocking

Front

Mocks objects that exist outside the program. Use for TDD.

Back

Refactor - decompose conditional

Front

Complicated if-then-else: extract methods from the condition, then part, then else parts. if (date.before(SUMMER_START)) charge = quantity * winterRate + winterService Charge; else charge quantity * summerRate BECOMES if(notSummer(date)) charge = winterCharge(quantity) else charge = summerCharge(quantity)

Back

Queues

Front

- ordered sequence of elements - access via endpoints - structures for LIFO and FIFO

Back

Refactor - encapsulate collection

Front

A method returns a collection - make it return a read-only view and provide add/remove methods. (get, set, add, remove..)

Back

Pass by reference

Front

- Objects and arrays - Changes affect original as it is given access to the address not just a copy.

Back

Black box Steps

Front

1. Considered input and output values 2. Partition inputs and outputs into ranges 3. For each equivalence class produce a) set of typical test that cover normal cases b) set of boundary value tests at or around the extreme limits of the equivalence class

Back

Refactoring

Front

Cleans code whilst preserving behaviour.

Back

Section 24

(50 cards)

The Lock (version control)

Front

- Lock-modify-unlock - When Harry accesses file he LOCKS it, reads/edits then releases lock. Sally then LOCKS it and does the same. - Only 1 person can access file at time!

Back

Local Repository

Front

- Stored on local computer. - Individual checks out version from Version database.

Back

GIT

Front

- Distributed version control. - Snapshot based = takes snapshot of each version. - Uses checksums to identify changes to files.

Back

Version control principles

Front

1. The Lock 2. The Merge

Back

BoxLayout

Front

Components placed in box. Can be aligned left, centre, right, top, middle, bottom etc.

Back

Working directory

Front

Checkout of the latest version of a project. May contain modified files that are not staged or committed. (Local)

Back

BorderLayout

Front

Splits area into 5 predefined spaces: South, north, west, east and center

Back

Events

Front

Every action creates an event on Event Dispatch Thread. Actions = button click, mouse over etc.

Back

FlowLayout

Front

Place components in the window from left to right, top to bottom.

Back

Thread Life Cycle

Front

new process > WAITING > RUNNING > BLOCKED - waiting starts and runs or times out - runs unless blocked until unblocked or until complete

Back

Example of Event Listener and Event Handler

Front

public class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println(e); } } // Listens for button action, if action occurs then will print the action.

Back

GridBagLayout

Front

Components placed in a grid. - given distinct sizes (# rows and # columns assigned to component. Most common for sophisticated GUIs.

Back

JInternalFrame

Front

Use for Multiple Document Interface (MDI)

Back

Central Repository

Front

- Version database stored on server. - Team checks out version from database. - Checkout = make local copy.

Back

Threads

Front

- Multiple processes within a single program. - Executed in slices or parallel. - Based on a priority system : this thread before that thread - Separate units of a parent process that share the resources of the parent process

Back

Hashcode (GIT)

Front

Uniquely identify each commit.

Back

Checkout

Front

- Make a local copy of code/file. - Checkout from Version Database.

Back

Abstract Windowing Toolkit (AWT)

Front

Java GUI programming toolkit - native widgets - heavyweight components - small range of widgets - look and feel can not be changed. - Dependent on platform. OLD.

Back

Event loop

Front

1. Action (button click, mouse movement...) registered generating event that can be tracked 2. Event passed to affected component, 3. Listen for Event 4. Respond to Event.

Back

git commit

Front

Commits staged files to Repo.

Back

JDesktopPane

Front

Use to create a virtual desktop or multiple-document interface. Use as main frame when you want to have internal frame.

Back

git add

Front

Tells git to track files. Tells git to stage tracked files that have been modified. Recursive.

Back

The Merge (version control)

Front

- Copy-modify-merge - Harry and Sally access at same time, both edit, Sally publishes first and Harry receives 'out-of-date' error. - Version control system performs diff operation and identifies conflicts. - Manual intervention required if conflicts. - Harry has to compare latest version with his own, creates merge and publishes merge.

Back

Disadvantages of the the Lock (version control)

Front

- Unnecessary serialisation of development steps - Programmers forget to release the lock - Doesn't consider dependencies between classes that may be out to different people at the same time.

Back

Event Adapters

Front

- Adapter = Design Pattern - Each Listener has a corresponding Adapter abstract class

Back

Distributed version control

Front

Stored local, everyone has a copy of the entire repository and its history. - very low latency for file inspection, copy and comparisons.

Back

Top Swing Level

Front

- Can appear anywhere on desktop. - Serve as root of containment hierarchy, all others must be contained in top lvl container - have content pane - can have menu bar added JFrame, JDialog, JApplet

Back

Intermediate Swing Level

Front

Components used for laying out the UI (User Interface). JPanel, JInternalFrame, JScrollPane, JSplitPane, JTabbedPane (e.g. chrome browser has tabs at top)

Back

GridLayout

Front

all components are placed in a table like structure and are the same size.

Back

4 heavyweight Swing components

Front

1. JFrame 2. JWindow 3. JDialog 4. JApplet

Back

Event Listeners (Observer?)

Front

Listen for events in components. Instances of Listener classes. Provided in interfaces.

Back

Event Handlers

Front

Methods that host the response code (tells what to do if event occurs).

Back

Disadvantages of TDD

Front

- difficult for programs with complex interactions with their environment e.g. GUI - Bad tests = bad code - if programmer write own code = blind spots - scalability debated.

Back

git init

Front

Initialise an empty repository

Back

Danger of using GIT

Front

Only one repository.

Back

JPanel

Front

- Contain parts of UI - Can contain other JPanels - Contain multiple different types of components.

Back

JTextArea

Front

Display textual data or accept large amounts of text input.

Back

Atomic Swing Components

Front

- Basic Controls JButton, JComboBox, JList, JMenu, JSlider, JSpinner, JTextField - Uneditable Displays JLabel, JProgressBar - Interactive Displays JColorChooser, JFileChooser, JTable, JTextArea, JTree

Back

Swing

Front

Java GUI programming toolkit - Native code windows - 4 heavyweight components - lightweight - look and feel can be changed (can be set or depend on platform) - wide range of widgets

Back

JTextField

Front

Hold any text. Can be editable. Use for small amounts of input.

Back

Head pointer (GIT)

Front

Points to the current branch.

Back

Commit

Front

Publishes file to GIT directory (Repository). Making it accessible by team. Use 'git commit -m "Message"'.

Back

git push

Front

Publishes committed local files to remote repo.

Back

GUI

Front

Graphical User Interface

Back

Staging area

Front

File indicating the modified files in the working directory to be included in the next commit. (Local). Use 'git add'.

Back

Close Window (GUI)

Front

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Back

JComboBox

Front

Combine text field and drop down list. Text field can be editable.

Back

Mocks

Front

test objects that know how they are meant to be used.

Back

Dangers of threads

Front

Introduce ASYNCHRONOUS BEHAVIOUR - multiple threads access same variable/storage location can become unpredictable. - only one should alter data at a time.

Back

Disadvantages of Centralised Servers

Front

- Central point of failure - Latency if remote - Inaccessibility if off-line

Back

Section 25

(50 cards)

Target (ANT)

Front

- can depend on other targets - 'depends' specifies order targets should be executed.

Back

Mismanaged threads result in

Front

1. Race Conditions 2. Deadlock 3. Starvation 4. Livelock

Back

executeUpdate (SQL command)

Front

Returns number of rows affected. Use for INSERT, UPDATE or DELETE. rows = st.executeUpdate("UPDATE names SET age = 21 WHERE name = 'John Howard'");

Back

java.lang.Runnable

Front

- implemented by classes that run on threads - implement instead of extending Thread Need a Thread wrapper - Thread one = new Thread(new HelloRunnable());

Back

Continuous Integration (CI)

Front

Build generated whenever: - change to a defined repository - fixed intervals e.g. CruiseControl, Jenkins (previously Hudson) - configured using config.xml file - effectiveness depends on quality of system integration tests. limited by GUI's etc. Use mocks etc to overcome issues. http://www.thoughtworks.com/continuous-integration

Back

Task (ANT)

Front

Piece of code that can be executed - can have multiple attributes (arguments) name: name of task <name attribute1="value1" attribute2="value2"...>

Back

Depend (ANT)

Front

determines which classfiles are out of date with respect to their source.

Back

CallableStatement (JDBC)

Front

Relies on a stored procedure. Can contain ? placeholders. public static final String INSERT_SQL = "call addName(?, ?)"; insert = connection.prepareCall(INSERT_SQL); ResultSet rs = select.executeQuery(); insert.setString(1, "Zaphod Beeblebrox"); insert.setInt(2, 26); insert.executeUpdate();

Back

Connection interface (JDBC)

Front

Connection to DB through connection object Uses Singleton pattern = only one instance of connection. connection = DBConnection.getInstance(); try { Statement st = connection.createStatement();

Back

Checked exception

Front

- if can throw 'checked' exception must: 1. include exception handling code to catch exception or 2. Declare to its caller that it potentially throws exception

Back

Object lock (synchronization)

Front

- must be final, otherwise could change and dif threads synchronize on dif objects private final static Object sharedLock = new Object(); public static void displayMessage(JumbledMessage jm) throws InterruptedException { synchronized(sharedLock) { for (int i = 0; i < jm.message.length(); i++) { System.out.print(jm.message.charAt(i)); Thread.currentThread().sleep(50); } System.out.println();}}

Back

PreparedStatement (JDBC)

Front

Precompiled SQL statements at object creation time rather than execution time. - Use ? to indicate parameters for the statement and fill in later. public static final String SELECT_SQL = "SELECT * FROM names ORDER BY age"; select = connection.prepareStatement(SELECT_SQL); ResultSet rs = select.executeQuery(); insert.setString(1, "Zaphod Beeblebrox"); insert.setInt(2, 26); insert.executeUpdate(); // So 1 is names and 2 is age.

Back

Race Conditions

Front

- Concurrent access problem - outcome depends on which thread gets to a value first - Results in asynchronous changes = can't predict variables affected by threads - Shared variables need 'volatile' keyword

Back

Levels of synchronization

Front

1. None 2. Class methods only (ensure class variables thread safe) 3. Class and Instance methods - protect integrity of all fields - allow different threads share objects - all fields protected from simultaneous access and modification

Back

Static Variables and Threads

Front

Static Variables are NOT thread safe. - Use ThreadLocal or InheritableThreadLocal type declaration

Back

Service Threads

Front

or daemon threads - Contain never ending loop - Receive and handle service requests - Terminates only when program terminates. So detects when all non-daemons finished then kills daemons and programs terminate.

Back

Deadlock

Front

- Blocked waiting for a resource held by another blocked thread - all philosophers pick up the left fork at the same time before any can pick up the right fork - No progress possible.

Back

notify() (Thread Communication)

Front

sends wake up call to a single blocked thread. Cannot specify which thread to wake.

Back

JDBC (Java Database Connectivity)

Front

Used to interface DBMS and Java code. - Gives database vendor independence. - Java gives platform dependence Allows: 1. Making connection to database 2. Creating SQL or MySQL statements 3. Executing SQL or MySQL queries to database 4. Viewing and modifying the resulting records.

Back

Thread safety

Front

- for GUIs use EventDispatch thread and SwingUtilities.invokeLater(new threadClass()) public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); SwingUtilities.invokeLater(new HelloWorldSwing());

Back

CruiseControl

Front

Build scheduler - <listeners> listen to the status of the build - <bootstrappers> actions to do before build

Back

Attributes (ANT)

Front

Can contain references to a property. References resolved before task executed

Back

Statement (JDBC)

Front

Defines methods that enable send SQL commands and receive data from DB. Statement st = connection.createStatement(); connection.execute(); etc.

Back

Client/server programming (Daemon thread)

Front

1. Server listens using daemon thread for each port 2. Request comes, daemon thread responds 3. Creates/calls another thread to do work 4. Worker thread terminates naturally 5. Daemon thread continues monitoring port

Back

Exceptions

Front

undesireable events outside the 'normal' behaviour of a program. - recoverable (not always) - handled in method where occur or propagated to calling program

Back

Livelock

Front

- Thread acts in response to another thread, makes no progress but is not blocked - Thread states can and do change but no progress can be made - think of corridor dance example Philosophers pass fork back and forth but no one gets to eat.

Back

join (Threads)

Front

Makes other thread/next thread wait until the first thread terminated. one.start(); two.start(); one.join(); three.start(); // Three has to wait on one

Back

In the Swing GUI framework use event handlers to respond to GUI based actions. Case of component responding to button click, models works by requiring:

Front

That the component implement the actionListener interface, that the JButton add the component as an active listener in its collection and that the component provide suitable responses to be called from within the actionPerformed method once the event is triggered.

Back

ResultSet (JDBC)

Front

Used to store the result of an SQL query. // get all current entries ResultSet rs = select.executeQuery(); // use metadata to get the number of columns int columnCount = rs.getMetaData().getColumnCount(); // output each row while (rs.next()) { for (int i = 0; i < columnCount; i++) { System.out.println(rs.getString(i + 1)); }

Back

notifyAll() (Thread Communication)

Front

sends wake up call to all blocked threads - if called when thread does not have lock = Illegal MonitorStateExpectation

Back

execute (SQL command)

Front

Returns boolean use for RENAME, DROP TABLE etc. st.execute("DROP TABLE names");

Back

Starvation

Front

- Some threads allowed to be greedy and others starved of resources, making no progress So some of the philosophers eat everything others get nothing.

Back

Thread communication

Front

Multiple threads notify each other when conditions change, when to wait or stop waiting. - void wait(), wait(long time), wait(long time, int nano) - void notify() - void notifyAll()

Back

Class lock (synchronization)

Front

public static synchronized void displayMessage(JumbledMessage jm) throws InterruptedException { for (int i = 0; i < jm.message.length(); i++) { System.out.print(jm.message.charAt(i)); Thread.currentThread().sleep(50); } System.out.println();}

Back

Synchronization

Front

- Only allows one thread access at a time. - Sets a lock on the method or object - When synchronized method terminated, lock released - Places an overhead on execution time (Don't over use it)

Back

Thread safe variables

Front

Variables that belong to only one thread. - Local variables are thread safe! - Instance and static variables are not thread safe

Back

wait() (Thread Communication)

Front

Puts current thread into blocked state. - can only call from method that has a lock (is synchronized) - Releases lock - Either waits specified time or until notified by another thread. - Best to put in while loop. - useful when all threads

Back

Unchecked exception

Front

- errors and run time exceptions - result of programming errors AssertionError, VirtualMachineError, ArithmeticException, NullPointerException, IndexOutOfBoundsException

Back

Safely stop thread

Front

- control loop with stopFlag - make sure stopFlag independent of other threads - check value frequently - use end() private volatile boolean stopflag; stopflag = false; //in run() try block: while (!stopflag) { d = Math.log(i++); sleep(1);} public void end() { stopflag = true;}

Back

Batch processing (JDBC)

Front

Reduce overhead by executing a large number at once.

Back

volatile

Front

- thread goes straight to source and doesn't locally ache - ensuring working with up to date data "Go back and check" - reduce concurrent thread access issues. private volatile boolean pleaseStop; while (!pleaseStop) { // do some stuff... }

Back

run()

Front

main method for an individual thread

Back

ANT

Front

- specifies how to build something. - require configuration file build.xml - A depends on B means that B needs to occur before A. - if B compiled then A will compile immediately.

Back

Transaction processing (JDBC)

Front

e.g. Funds transfer commit() rollback() savepoint..

Back

Advantages of exceptions

Front

- error handling is separated from normal code - allows different kind of errors to be distinguished

Back

Benefits of Continuous Integration

Front

- allow team detect problems early - reduce integration problems - increase visibility

Back

executeQuery (SQL command)

Front

Returns ResultSet. Use for SELECT. ResultSet rs = st.executeQuery("SELECT * FROM names")

Back

Maven

Front

Back

java.lang.Thread

Front

provides infrastructure for multithreaded programs. can extend thread but issue with multiple class inheritance so extend runnable instead.

Back

Timer

Front

- implements Runnable - runs a TimerTask object on JVM background thread - so use to Schedule Tasks (threads) // set Timer as a daemon thread Timer timer = new Timer(true); timer.schedule(hello1, 1000); // will run after 1000 milisec timer.schedule(hello2, 2000);

Back

Section 26

(50 cards)

Assuming a=3, the values of a and b after the assignment b=a-- are _____.

Front

2, 3

Back

Assuming c=5, the value of variable d after the assignment d=c * ++c is _____.

Front

30

Back

String Concatenation Operator

Front

The name for a plus (+) operator that combines its two operands (Strings) into a single String.

Back

The _ component allows users to add and view multiline text.

Front

JTextArea

Back

Throwable

Front

Used to define own exceptions.

Back

setEditable

Front

Sets the editable property of the JTextArea component to specify whether or not the user can edit the text in the JTextArea.

Back

Users cannot edit the text in a JTextArea if its _ property is set to false.

Front

Editable

Back

The UML decision/merge symbols can be distinguished by _.

Front

The number of flowlines entering or exiting the symbol and whether or not they have guard conditions. (Both of the above)

Back

BLOB

Front

Binary Large OBject - converted to byte arrays before being stored - important in cloud services - data that doesn't fit in standard data types e.g. pictures, media files, archives - alternative to serialization

Back

JTextArea

Front

Control that allows the user to view multiline text.

Back

Postincrement

Front

counter++

Back

A _ is a variable that helps control the number of times that a set of statements will execute.

Front

Counter

Back

Try catch exception block

Front

try {... normal code} catch(exception-class object) {... exception-handling code}

Back

How many JCheckBoxes in a GUI can be selected at once?

Front

Any number

Back

-- (unary decrement operator)

Front

Subtracts one from an integer variable.

Back

CLOB

Front

Character Large OBject

Back

JTextArea method _ adds text to a JTextArea.

Front

Append

Back

Preincrement

Front

++counter

Back

++ (unary increment operator)

Front

Adds one to an integer variable.

Back

Counter

Front

A variable often used to determine the number of times a block of statements in a loop will execute.

Back

Escape Character

Front

This character (\) allows you to form escape sequences.

Back

Diamond (in the UML)

Front

The UML symbol that represents the decision symbol or the merge symbol, depending on how it is used.

Back

The UML represents both the merge symbol and the decision symbol as _____.

Front

Diamonds

Back

Infinite Loop

Front

A logical error in which a repetition statement never terminates.

Back

A(n) _ loop occurs when a condition in a while statement never becomes false.

Front

Infinite

Back

Counter-controlled repetition is also called _.

Front

Definite repetition

Back

Decrementing

Front

The process of subtracting 1 from an integer.

Back

Append

Front

A method that adds text to a JTextArea component.

Back

Counter-Controlled Repetition (Definite Repetition)

Front

A technique that uses a counter to limit the number of times that a block of statements will execute.

Back

Header

Front

A line of text at the top of a JTextArea that clarifies the information being displayed.

Back

Merge Symbol

Front

A symbol in the UML that joins two flows of activity into one flow of activity.

Back

Suite of tests

Front

Run multiple test classes as a single test @RunWith(Suite.class) @Suite.SuiteClasses({class_name, ...})

Back

While Statement

Front

A specific control statement that executes a set of body statements while a loop continuation condition is true.

Back

The body of a while statement executes _____.

Front

If it's condition is true

Back

The text that appears alongside a JCheckBox is referred to as the ____.

Front

JCheckBox Text

Back

Predecrement

Front

--counter

Back

JTextArea method _, when called with an empty string, can be used to delete all the text in a JTextArea.

Front

setText

Back

Loop-Continuation Condition

Front

A condition used in a repetition statement (such as while) that repeats only while the statement is true.

Back

Counter-controlled repetition is also called _____ because because the number of repetitions is known before the loop begins executing.

Front

Definite repetition

Back

Loop

Front

Another general name for a repetition statement.

Back

Postdecrement

Front

counter--

Back

The _ statement executes until its loop-continuation condition becomes false.

Front

While

Back

The line of text that is added to a JTextArea to clarify the information that will be displayed in tabular format is called a _____.

Front

Header

Back

@Test(timeout = T)

Front

Test fails if runs longer than T milliseconds.

Back

@Test(expected = X.class)

Front

Test is expected to throw exception X.

Back

Escape Sequence

Front

The combination of a backslash and a character that can represent a special character, such as a newline or a tab.

Back

Incrementing

Front

The process of adding 1 to an integer.

Back

In a UML activity diagram, a(n) _ symbol joins 2 flows of activity into 1 flow of activity.

Front

Merge

Back

setText

Front

Sets the text property of the JTextArea component.

Back

Repetition Statement

Front

A general name for a statement that allows the programmer to specify that an action or actions should be repeated, depending on a condition.

Back

Section 27

(50 cards)

2

Front

If the variable x contains the value 5, what value will x contain after the expression x -= 3 is executed?

Back

block

Front

A set of statements that is enclosed in curly braces ({ and }).

Back

The condition expression1 && expression2 evaluates to true when __.

Front

Both expressions are true.

Back

True and False

Front

A variable of type boolean can be assigned the values _____.

Back

Executable

Front

Pseudocode usually only describes ____ lines of code.

Back

Print

Front

A variable or an expression can be examined by the _____ debugger command.

Back

Decimal, Text

Front

Class DecimalFormat is used to control how ____ numbers are formatted as ____.

Back

algorithm

Front

A procedure for solving a problem, specifying the actions to be executed and the order in which these actions are to be executed.

Back

String.equals

Front

A method that evaluates whether a String contains specific text specified.

Back

A JCheckBox is selected when the isSelected method returns __.

Front

True

Back

==, <= and <

Front

The ______ operators return false if the left operand is greater than the right operand.

Back

{}

Front

The body of an if statement that contains multiple statements is placed in _____.

Back

Double

Front

If... else is a ____-selection statement.

Back

The JOptionPane dialog icon typically used to caution the user against potential problems is the ____.

Front

Exclamation point

Back

OR operator (||)

Front

A logical operator used to ensure that either or both of two conditions are true. Performs short-circuit evaluation.

Back

Decimal points

Front

The double type can be used to store numbers with ____ ____.

Back

JOptionPane.ERROR_MESSAGE

Front

Icon containing a stop sign, alerts the user of errors or critical situations.

Back

Sequential

Front

The process of application statements executing one after another in the order in which they are written is called ____ execution.

Back

Transfer of control

Front

A ______ occurs when an executed statement does not directly follow the previously executed statement in the written application.

Back

logical operators

Front

Operators (&&, ||, &, |, ^ and !) that can be used to form complex conditions by combining simple ones.

Back

Three

Front

All Java applications can be written in terms of ____ types of program control.

Back

JCheckBox text

Front

The text that appears alongside a JCheckBox.

Back

state button

Front

A button that can be in the on/off (true/false) state, such as a CheckBox.

Back

Operator && __.

Front

Performs short-circuit evaluation

Back

An action

Front

In an activity diagram, a rectangle with curved sides represents _____.

Back

isSelected

Front

Specifies whether the JCheckBox is selected (true) or deselected (false): JCheckBox._____. (method)

Back

Multiplies

Front

The *= operator ____ the value of its left operand by the value of the right one and store it in the left one.

Back

NOT (!) operator

Front

A logical operator that enables a programmer to reverse the meaning of a condition, true is false, false is true if evaluated.

Back

set

Front

You can modify the value of a variable by using the debugger's ____ command.

Back

Sequence, selection and repetition

Front

The three types of program control are _____.

Back

showMessageDialog

Front

Used to display a message dialog: JOptionPane.____.

Back

Program control

Front

____ refer(s) to the task of executing an application's statements in the correct order.

Back

The 2nd argument passed to method JOptionPane.showMessageDialog is ____.

Front

The message displayed by the dialog

Back

print

Front

You can examine the value of an expression by using the debugger's ____ command.

Back

The condition Exp1 ^ exp2 evaluates to true when ____.

Front

Either exp1 is false and exp2 is true or exp1 is true and exp2 is false.

Back

Nesting

Front

Placing an if...else statement inside another one is an example of ____ if-else statements.

Back

XOR operator (^)

Front

A logical operator that evaluates to true if and only if one operand is true.

Back

JOptionPane.WARNING_MESSAGE

Front

Icon containing an exclamation point, cautions the user of potential problems.

Back

The ___ constant can be used to display an error message in a message dialog.

Front

JOptionPane.ERROR_MESSAGE

Back

format

Front

Method ____ of DecimalFormat can display double values in a special format, such as with two digits to the right of the decimal point.

Back

JOptionPane

Front

A class that provides a method for displaying message dialogs and constants for displaying icons in those dialogs.

Back

Pseudocode

Front

____ is an artificial and informal language that helps programmers develop algorithms.

Back

Constant

Front

A variable whose value cannot be changed after its initial declaration is called a _____.

Back

+=

Front

The _____ operator assigns to the left operand the result of adding the left and right operands.

Back

AND operator (&&)

Front

A logical operator used to ensure that two conditions are both true before choosing a path of execution. Performs short-circuit evaluation.

Back

The condition exp1 || exp2 evaluates to false when ___.

Front

Both are false.

Back

selected

Front

Defines if a component has been selected. (property)

Back

message dialog

Front

The general name for a dialog that displays messages to users.

Back

Algorithm

Front

A(n) ___ is a procedure for solving a problem in terms of the actions to be executed and the order in which these actions are to be executed.

Back

Final

Front

Constants are declared with keyword ____.

Back

Section 28

(50 cards)

arithmetic operators

Front

These operators are used for performing calculations.

Back

double

Front

A datatype that can represent numbers with decimal points.

Back

print

Front

A debugger command that is used to examine the values of variables and expressions.

Back

integer

Front

A whole number, such as 919, -11 or 0 (not a decimal or fraction)

Back

empty string ("")

Front

A string that does not contain any characters.

Back

double

Front

Variable type that is used to store floating-point numbers.

Back

if statement

Front

This single-selection statement performs action(s) based on a condition.

Back

final

Front

Keyword that precedes the data type in a declaration of a constant.

Back

logic error

Front

An error that does not prevent the application from compiling successfully, but does cause the application to produce erroneous results when it runs.

Back

Double.parseDouble

Front

A method that converts a String containing a floating-point number into a double value.

Back

workflow

Front

The activity of a portion of a software system.

Back

nondestructive

Front

The process of reading from a memory location, which does not modify the value in that location.

Back

program control

Front

The task of executing an application's statements in the correct order.

Back

keyPressed event

Front

The event that occurs when any key is pressed in a JTextField.

Back

int value

Front

The variable type that stores integer values.

Back

clear

Front

Debugger command that displays a list of all the breakpoints in an application.

Back

-g compiler option

Front

This flag or option causes the compiler to generate debugging information that is used by the debugger to help you debug your applications.

Back

jdb

Front

Starts the Java debugger when typed at the Command Prompt.

Back

DecimalFormat

Front

The class used to format floating-point numbers (that is, numbers with decimal points).

Back

relational operators

Front

Operators < (less than), > (greater than), <= (less than or equal to) and >= (greater than or equal to) that compare two values.

Back

% (remainder operator)

Front

This operator yields the remainder after division.

Back

destructive

Front

The process of assigning data (or writing) to a memory location, in which the previous value is overwritten or lost.

Back

single-selection statement

Front

A statement, such as the if statement, that selects or ignores a single action or sequence of actions.

Back

declaring

Front

When you specify the type and name of a variable to be used in an application, you are ____ a variable.

Back

floating-point number

Front

A number with a decimal point, such as 2.3456, 0.0 and -845.4680

Back

format

Front

DecimalFormat method that takes a double, returns a String containing a formatted number.

Back

declaration

Front

Code that specifies the name and type of a variable.

Back

primitive type

Front

A variable type already defined in Java. (Examples: boolean, byte, char, short, int, long, float and double)

Back

formatting

Front

Modifying the appearance of text for display purposes.

Back

breakpoint

Front

A marker that can be set in the debugger at any executable line of source code, causing the application to pause when it reaches the specified line of code.

Back

control

Front

A program statement (such as if, if...else, switch, while, do...while or for) that specifies the flow of ____.

Back

decision

Front

The diamond-shaped symbol in a UML activity diagram that indicates a ____ is to be made.

Back

pseudocode

Front

An informal language that helps programmers develop algorithms.

Back

if...else statement

Front

This double-selection statement performs action(s) if a condition is true and performs different action(s) if the condition is false.

Back

nested statement

Front

A statement that is placed inside another control statement.

Back

set

Front

Debugger command that is used to change the value of a variable.

Back

bug

Front

A flaw in an application that prevents the application from executing correctly.

Back

name

Front

The ____ of a variable is used in an application to access or modify a variable's value.

Back

asterisk (*)

Front

An arithmetic operator that performs multiplication.

Back

initialization value

Front

The beginning value of a variable.

Back

forward slash (/)

Front

An arithmetic operator that indicates division.

Back

assignment operator

Front

This operator, =, copies the value of the expression on the right side into the variable.

Back

double-selection statement

Front

A statement, such as if...else, that selects between two different actions or sequences of actions.

Back

equality operators

Front

Operators == (is equal to) and != (is not equal to) that compare two values.

Back

break mode

Front

Debugger mode the application is in when execution stops at a breakpoint.

Back

cont

Front

Debugger command that resumes program execution after a breakpoint is reached while debugging.

Back

Breakpoint

Front

One reason to set a _____ is to be able to examine the values of variables at that point in the application's execution.

Back

constant

Front

A variable whose value cannot be changed after its initial declaration.

Back

debugger

Front

Software that allows you to monitor the execution of your applications to locate and remove logic errors.

Back

cont

Front

Debugger command that resumes program execution after a breakpoint is reached while debugging.

Back

Section 29

(50 cards)

Parentheses

Front

4. In Java, use ________ to force the order of evaluation of operators.

Back

body

Front

A set of statements that is enclosed in curly braces ({ and }). This is also called a block. Another name for this is a ____.

Back

event

Front

An action that can trigger an event handler.

Back

run

Front

Debugger command to begin executing an application with the Java debugger.

Back

extending a class

Front

Creating a new class based on an existing class (also called inheritance). This action is called ____.

Back

class name

Front

The identifier used as the name of a class.

Back

Empty String

Front

3. The ____ is represented by "" in Java.

Back

Nondestructive

Front

6. Reading a value from a variable is a ________ process.

Back

Replaces

Front

5. When a value is placed into a memory location, the value ____ the previous value in that location.

Back

full-line comment

Front

A comment that appears on a line by itself in source code.

Back

comment

Front

A ____ begins with two forward slashes (//).

Back

setText()

Front

4. Use the ____ method to clear any text displayed in a JTextField.

Back

stop

Front

Debugger command that sets a breakpoint at the specified line of executable code.

Back

Comment

Front

9. A breakpoint cannot be set at a(n) ____.

Back

operator precedence

Front

Rules of ____ ____ determine the precise order in which operators are applied in an expression.

Back

straight-line form

Front

The manner in which arithmetic expressions must be written so they can be typed in Java code.

Back

size

Front

The ____ of a variable holds the number of bytes required to store a value of the variable's type. For example, an int is stored in four bytes of memory and a double is stored in eight bytes.

Back

Redundant

Front

1. Parentheses that are added to an expression simply to make it easier to read are known as ________ parentheses.

Back

Name and type

Front

3. Every variable has a ________.

Back

Valid Identifier

Front

1. The name of a variable must be a ____.

Back

int

Front

9. Variables used to store integer values should be declared with keyword ________.

Back

/

Front

2. The ________ operator performs division.

Back

actionPerformed

Front

The kind of event that occurs when a JButton is clicked.

Back

Primitive

Front

2. Types already defined in Java, such as int, are known as ____ types.

Back

unary operator

Front

An operator with only one operand (such as + or -).

Back

Left to right

Front

5. If an expression contains several multiplication, division and remainder operations, they are performed from ________.

Back

case sensitive

Front

Identifiers with identical spelling are treated differently if the capitalization of the identifiers differs. This kind of capitalization is called _____.

Back

Before

Front

8. The expression to the right of the assignment operator (=) is always evaluated ____ the assignment occurs.

Back

block

Front

A group of code statements that are enclosed in curly braces ({ and }).

Back

argument

Front

Values inside of the parentheses that follow the method name in a method call are called ____(s).

Back

extends keyword

Front

The keyword the specifies that a class inherits data and functionality from an existing class.

Back

At

Front

10. When application execution suspends at a breakpoint, the next statement to be executed is the statement ____ the breakpoint.

Back

print

Front

Debugger command that displays the value of a variable when an application is stopped at a breakpoint during execution in the debugger.

Back

dot separator

Front

Allows programmers to call methods of a particular class or object.

Back

end-of-line comment

Front

A comment that appears at the end of a code line.

Back

KeyPressed

Front

7. Pressing a key in JTextField raises the ________ event.

Back

comment (//)

Front

Explanatory text that is inserted to improve an application's readability.

Back

value of a variable

Front

The piece of data that is stored in a variable's location in memory.

Back

redundant parentheses

Front

Extra parentheses used in calculations to clarify the order in which calculations are performed. Such parentheses can be removed without affecting the results of the calculations.

Back

class keyword

Front

The keyword used to begin a class declaration.

Back

Stop

Front

8. The debugger command ________ sets a breakpoint at an executable line of source code in an application.

Back

binary operator

Front

An operator that requires two operands.

Back

In straight-line form

Front

7. Arithmetic expressions in Java must be written ____ to facilitate entering expressions into the computer.

Back

Not changed

Front

6. When a value is read from memory, that value is ____.

Back

event handler

Front

Code that executes when a certain event occurs.

Back

variable

Front

A location in the computer's memory where a value can be stored for use by an application.

Back

type

Front

The ____ of a variable specifies the kind of data that can be stored in a variable and the range of values that can be stored, such as an integer holding 1, and a double holding 1.01.

Back

class declaration

Front

The code that defines a class, beginning with the class keyword.

Back

truncating

Front

When you are ____ in integer division, any fractional part of an integer division result is discarded.

Back

Print

Front

10. The debugger command ________ allows you to "peek into the computer" and look at the value of a variable.

Back

Section 30

(50 cards)

String.valueOf

Front

A method that converts a numeric value (such as an integer) into text.

Back

debugging

Front

The process of locating and removing errors in an application.

Back

left brace ({)

Front

Denotes the beginning of a block of code.

Back

setText

Front

Use _____ to set the text on the face of a JButton.

Back

input JTextField

Front

A JTextField used to get user input.

Back

keyword

Front

A word that is reserved by Java. These words cannot be used as identifiers. Also called reserved word.

Back

compiling

Front

The process that converts a source code file (.java) into a .class file.

Back

case sensitive

Front

Distinguishes between uppercase and lowercase letters in code.

Back

newline

Front

A character that is inserted in code when you press Enter.

Back

getText

Front

A method that accesses (or gets) the text property of a component such as a JLabel, JTextField or a JButton.

Back

JLabel component

Front

A component used to describe another component. This helps users understand a component's purpose.

Back

setBounds

Front

The location and size of a JLabel can be specified with _____.

Back

statement

Front

A unit of code that performs an action and ends with a semicolon.

Back

functionality

Front

The tasks or actions an application can execute.

Back

JTextField.RIGHT

Front

Used with setHorizontalAlignment to right align the text in a JTextField.

Back

multiline statement

Front

A statement that is spread over multiple lines of code for readability.

Back

.class file

Front

The type of file that is executed by the Java Runtime Environment (JRE). A ____ file is created by compiling the application's .java file.

Back

JTextField.LEFT

Front

Used with setHorizontalAlignment to left align the text in a JTextField.

Back

JTextField.CENTER

Front

Used with setHorizontalAlignment to center align the text in a JTextField.

Back

setText

Front

A method that sets the text property of a component, such as a JLabel, JTextField or JButton.

Back

left operand

Front

An expression that appears on the left side of a binary operator.

Back

identifier

Front

A series of characters consisting of letters, digits and underscores used to name classes and GUI components.

Back

setText

Front

The text on a JLabel is specified with _____.

Back

white space

Front

A tab, space or newline is called a(n) _____.

Back

background property

Front

Property that specifies the background color of a content pane component.

Back

reserved word

Front

A word that is reserved for use by Java and cannot be used to create your own identifiers. Also called keyword.

Back

editable property

Front

The property that specifies the appearance and behavior of a JTextField (whether the user can enter text.)

Back

semicolon (;)

Front

Character used to terminate each statement in an application.

Back

return

Front

Some methods, when called, __ a value to the statement in the application that called the method. The returned value can then be used in that statement.

Back

JButton component

Front

A component that, when clicked, commands the application to perform an action.

Back

font property

Front

Property specifying font name (Times New Roman), style (Bold) and size (12) of any text.

Back

horizontalAlignment property

Front

The property that specifies the text alignment in a JTextField (JTextField.LEFT, JTextField.CENTER, or JTextField.RIGHT).

Back

book-title capitalization

Front

A style that capitalizes the first letter of each significant word in the text (for example, Calculate the Total).

Back

horizontalAlignment property

Front

The property that specifies how text is aligned within a JLabel is called:

Back

sentence-style capitalization

Front

A style that capitalizes the first letter of the first word In the text (for example, Cartons per shipment): other letters in the text are lowercase, unless they are the first letters of proper nouns.

Back

operand

Front

An expression that is combined with an operator (and possibly other expressions) to perform a task (such as multiplication).

Back

content pane

Front

The portion of a JFrame that contains the GUI components.

Back

Integer.parseInt

Front

Returns the integer equivalent of a String.

Back

dir command

Front

Command typed in a Command Prompt window to list the directory contents.

Back

output JTextField

Front

a JTextField used to display calculation results. The editable property of an output JTextField is set to false with setEditable.

Back

bounds property

Front

The property that specifies both the location and size of a component.

Back

method

Front

An application segment containing statements that perform a task.

Back

right operand

Front

An expression that appears on the right side of a binary operator.

Back

JLabel

Front

Component that displays a text or an image that the user cannot modify

Back

uneditable JTextField

Front

JTextField in which the user cannot type values or edit existing text. Such JTextFields are often used to display the results of calculations.

Back

right brace (})

Front

Denotes the end of a block of code.

Back

Book-Title

Front

You should use _____ capitalization for a JButton's name.

Back

multiplication operator

Front

This operator is an asterisk (*), used to ____ its two numeric operands.

Back

JTextField component

Front

A component that can accept user input from the keyboard or display output to the user.

Back

inheritance

Front

Creating a new class based on an existing class (also called extending a class). This action is called ____.

Back

Section 31

(50 cards)

syntax error

Front

An error that occurs when code violates the grammatical rules of a programming language.

Back

Clock -hr: int -min: int -sec: int +Clock() +Clock(int, int, int) +setTime(int, int, int): void +getHours(): int +getMinutes(): int +getSeconds(): int +printTime(): void +incrementSeconds(): int +incrementMinutes(): int +incrementHours(): boolean +equals(Clock): boolean +makeCopy(Clock): void +getCopy(): Clock According to the UML class diagram above, which method is public and doesn't return anything? 1. getCopy() 2. setTime(int, int, int) 3. incrementHours() 4. equals(Clock)

Front

setTime(int, int, int)

Back

.java

Front

5. Java source code files have the extension ____.

Back

Javac

Front

2. To compile an application, type the command ____ followed by the name of the file.

Back

Accessor instance method names typically begin with the word "____" or the word "____" depending on the return type of the method. 1. set, is 2. get, can 3. set, get 0% 4. get, is

Front

get, is

Back

Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements adds the object to the end of the collection 1. a[3] = element; 2. a.add(element, 4); 3. a[4] = element; 4. a.add(element);

Front

4. a.add(element);

Back

setTitle

Front

3. Use ____ to set the text that appears on a JFrame's title bar.

Back

statement

Front

Code that instructs the computer to perform a task. Every statement ends with a semicolon ( ; ) character. Most applications consist of many statements.

Back

logic error

Front

An error that does not prevent your application from compiling successfully but does cause your application to produce erroneous results.

Back

Compiler

Front

4. Syntax errors are found by the ____.

Back

Clock -hr: int -min: int -sec: int +Clock() +Clock(int, int, int) +setTime(int, int, int): void +getHours(): int +getMinutes(): int +getSeconds(): int +printTime(): void +incrementSeconds(): int +incrementMinutes(): int +incrementHours(): boolean +equals(Clock): boolean +makeCopy(Clock): void +getCopy(): Clock Which of the following would be a default constructor for the class Clock shown in the figure above? 1. public Clock(0, 0, 0) { setTime(); } 2. private Clock(10){ setTime(); } 3. public Clock(0) { setTime(0); } 4. public Clock(){ setTime(0, 0, 0); }

Front

public Clock(){ setTime(0, 0, 0); }

Back

Size, style, and name

Front

3. The font property controls the ____ of the font displayed by the Jlabel.

Back

setIcon

Front

4. Use ____ to specify the image to display on a JLabel.

Back

Picture elements

Front

10. Pixels are ____.

Back

Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 length + 2 width; } } Which of the following statements correctly instantiate the Rectangle object myRectangle? (i) myRectangle Rectangle = new Rectangle(10, 12); (ii) class Rectangle myRectangle = new Rectangle(10, 12); (iii) Rectangle myRectangle = new Rectangle(10, 12); 1. Only (ii) 2. Only (iii) 3. Only (i) 4. Both (ii) and (iii)

Front

Only (iii)

Back

Components of a color

Front

9. RGB values specify the ____.

Back

How many constructors can a class have? 1. Any number 2. 0 3. 1 4. 2

Front

Any number

Back

the line number of the error; a brief description of the error.

Front

5. Upon finding a syntax error in an application, the compiler will notify the user of an error by giving the user ____.

Back

Title bar

Front

The area at the top of a JFrame where its title appears.

Back

size property

Front

Property that specifies the width and height, in pixels, of a component.

Back

JLabel

Front

The component that displays text or an image that the user cannot modify.

Back

Size and location of component

Front

6. The bounds property controls the ____.

Back

String literal

Front

A sequence of characters within double quotes.

Back

word is spelled incorrectly; parentheses is omitted.

Front

6. Syntax errors occur for many reasons, such as when a(n) ____.

Back

Person -name: String +setName(String name): void +getName(): String ^ Student -studentID: long +Student(String sname, long sid) +setID(): long Which of these fields or methods are inherited (and accessible) by the Student class? 1. getName(), setName(), name 2. name, getName(), setName(), getID() 3. studentID, name, getName(), setName(), getID() 4. getName(), setName(), toString() 5. None of them 6. getName(), setName(), studentID, getID()

Front

4. getName(), setName(), toString()

Back

.java

Front

1. A source code file has the ____ extension.

Back

Clock ---------------------------------------- -hr: int -min: int -sec: int --------------------------------------- +Clock() +Clock(int, int, int) +setTime(int, int, int) : void +getHours() : int +getMinutes() : int +getSeconds() : int +printTime() : void +incrementSeconds() : int +incrementMinutes() : int +incrementHours() : int +equals(Clock) : boolean +makeCopy(Clock) : void +getCopy() : Clock ---------------------------------------- According to the UML class diagram above, which of the following is a data member? 1. printTime() 2. min 3. Clock() 4. Clock

Front

2. min

Back

Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 length + 2 width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following sets of statements are valid (both syntactically and semantically) in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); 1. Both (i) and (ii) 2. Only (ii) 3. Only (i) 4. None of these

Front

Only (i)

Back

pixel

Front

A point on your computer screen. ____ is short for "picture element".

Back

Compiler

Front

2. The __________ converts a .java file to a .class file.

Back

RGB value

Front

The amount of red. green and blue needed to create a color.

Back

Person -name: String +setName(String name): void +getName(): String ^ Student -studentID: long +Student(String sname, long sid) +setID(): long To access the name instance variable from inside a method defined in the Student class, name must use the _____________ modifier. (We'll ignore the default package-private access if no modifier is used.) 1. Any of them 2. public 3. protected or public 4. protected 5. private 6. private or protected

Front

3. protected

Back

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the data type of the array above? 1. num 2. int 3. char 4. list

Front

int

Back

setBackground

Front

1. Use ___ to specify the content pane's background color.

Back

To print the last element in the array named ar, you can write : A. System.out.println(ar[length-1]); B. System.out.println(ar[length()-1]); C. System.out.println(ar[ar.length-1]); D. System.out.println(ar[ar.length]);

Front

System.out.println(ar[ar.length-1]);

Back

To print the last element in the array named ar, you can write : A. System.out.println(ar.length); B. System.out.println(ar[length]); C. System.out.println(ar[ar.length]); D. None of these

Front

None of these

Back

icon property

Front

The property that specifies the file name of the image displayed in a JLabel.

Back

double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is the value of vals.length in the array above? 1. 16 2. 4 3. 0 4. 3

Front

4

Back

setHorizontalAlignment

Front

8. Use ____ to align the text displayed inside a Jlabel.

Back

When you override a method defined in a superclass, you must do all of these except: 1. Use exactly the same number and type of parameters as the original method 2. Use an access specifier that is at least as permissive as the superclass method 3. Change either the number, type, or order of parameters in the subclass. 4. Return exactly the same type as the original method.

Front

3. Change either the number, type, or order of parameters in the subclass.

Back

String

Front

A sequence of characters that represents text information.

Back

A method that has the signature void m(int[] ar) : A. can change the values in the array ar B. cannot change the values in the array ar C. can only change copies of each of the elements in the array ar D. None of these

Front

can change the values in the array ar

Back

javac command

Front

The command that compiles a source code file (.java) into a . class file.

Back

location property

Front

The property that specifies where a component's upper-left corner appears on the JFrame.

Back

semicolon ( ; )

Front

The character used to indicate the end of a Java statement.

Back

text property

Front

The property that specifies the text displayed by a JLabel.

Back

.java file

Front

The type of file in which programmers write the Java code for an application.

Back

Constructors have the same name as the ____. 1. data members 2. package 3. class 4. member methods

Front

class

Back

setText

Front

7. A Jlabel component displays the text specified by ____.

Back

source code file

Front

A file with a .java extension. These files are editable by the programmer, but are not executable.

Back

Section 32

(50 cards)

char[][] array1 = new char[15][10]; What is the value of array1.length? 1. 15 2. 0 3. 2 4. 10

Front

15

Back

Which of the following class definitions is correct in Java? (i) public class Student { private String name; private double gpa; private int id; public void Student() { name = ""; gpa = 0; id = 0; } public void Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } (ii) public class Student { private String name; private double gpa; private int id; public Student() { name = ""; gpa = 0; id = 0; } public Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } 1. Both (i) and (ii) 2. None of these 3. Only (ii) 4. Only (i)

Front

3. Only ii

Back

Suppose that sales is a two-dimensional array of 10 rows and 7 columns wherein each component is of the type int , and sum and j are int variables. Which of the following correctly finds the sum of the elements of the fifth row of sales? 1. sum = 0; for(j = 0; j < 10; j++) sum = sum + sales[5][j]; 2. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[4][j]; 3. sum = 0; for(j = 0; j < 10; j++) sum = sum + sales[4][j]; 4. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[5][j];

Front

2. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[4][j];

Back

Assume that you have an ArrayList variable named a containing many elements. You can rearrange the elements in random order by writing:

Front

Collections.shuffle(a);

Back

What does the following loop do? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; a[pos] = a[size - 1]; size--;

Front

Removes the 1 from the array, replacing it with the 7. Array now unordered.

Back

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the value at index 10 of the array above?

Front

10

Back

What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] < value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 1, 3, 5, 0, 0, 0 } 2. { 5, 1, 3, 7, 0, 0 } 3. { 1, 3, 5, 7, 0, 0 } 4. { 1, 3, 7, 5, 0, 0 }

Front

2. { 5, 1, 3, 7, 0, 0 }

Back

Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (size < capacity && value > 0) { a[size] = value; } 1. Reads up to 3 values and places them in the array in the unused space. 2. Reads one value and places it in the remaining first unused space endlessly. 3. Reads up to 3 values and inserts them in the array in the correct position. 4. Crashes at runtime because it tries to write beyond the array.

Front

Reads one value and places it in the remaining first unused space endlessly.

Back

A classification hierarchy represents an organization based on _____________ and _____________.

Front

generalization and specialization

Back

What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 5; for (j = 1; j < 5; j++) { if (j % 2 == 0) alpha[j] = alpha[j - 1] + 2; else alpha[j] = alpha[j - 1] + 3; } 1. None of these 2. 13 3. 15 4. 10

Front

13

Back

What does the following loop print? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = a[0]; for (int i = 1; i < len; i++) if (a[i] < x) x = a[i]; System.out.println(x); 1. 36 2. 12 3. 1 4. 6

Front

1

Back

The arguments in a method call are often referred to as ____. 1. concept parameters 2. constants 3. actual parameters 4. argument lists

Front

3. Actual parameters

Back

When you write an explicit ____ for a class, you no longer receive the automatically written version.

Front

constructor

Back

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x++; System.out.println(x); 1. Sums the even elements in a. 2. Finds the largest value in a. 3. Counts the even elements in a. 4. Finds the smallest value in a.

Front

Counts the even elements in a.

Back

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x++; System.out.println(x); 1. Sums the even elements in a. 2. Counts the even elements in a. 3. Finds the smallest value in a. 4. Finds the largest value in a.

Front

Counts the even elements in a.

Back

Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements replaces the last object in the collection with element?

Front

a.set(3, element);

Back

Mutator methods typically begin with the word "____".

Front

set

Back

When you override a method defined in a superclass, you must do all of these except:

Front

Change either the number, type, or order of parameters in the subclass.

Back

What does the following loop print? int[] a = {6, 1, 9, 5, 12, 7}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x++; System.out.println(x); 1. 4 2. 22 3. 18 4. 2

Front

2

Back

To determine the number of valid elements in an ArrayList, use:

Front

the size() method

Back

A ____________ relationship exists between two classes when one class contains fields that are instances of the other class.

Front

has-A

Back

Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long 1. toString() 2. None of them 3. getName(), setName(), name 4. name, getName(), setName(), getID() 5. getName(), setName(), studentID, getID() 6. studentID, name, getName(), setName(), getID()

Front

toString()

Back

Consider the following statements. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println("Length = " + length + "; Width = " + width + "
" + + " Area = " + area() + "; Perimeter = " + perimeter()); } public double area() { return length * width; } public void perimeter() { return 2 length + 2 width; } } What is the output of the following statements?

Front

3. Length = 14.0; Width = 10.0 Area = 140.0; Perimeter = 48.0

Back

You cannot declare the same ____ name more than once within a block, even if a block contains other blocks.

Front

variable

Back

Which of the following lines of code implicitly calls the toString() method, assuming that pete is an initialized Student object variable?

Front

String s = "President: " + pete;

Back

Which of the following creates an array of 25 components of the type int? (i) int[] alpha = new[25]; (ii) int[] alpha = new int[25]; 1. Only (ii) 2. None of these 3. Only (i) 4. Both (i) and (ii)

Front

Only (ii)

Back

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the value of num.length in the array above? 1. 0 2. 100 3. 99 4. 101

Front

100

Back

Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Assume that pete is a Person object variable that refers to a Person object. Which method is used to print this output: pete is Person@addbf1 1. getClass() 2. getAddress() 3. getName(), getID() 4. getID() 5. getName() 6. None of them 7. toString()

Front

toString()

Back

Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements assigns the first object in the collection to the variable element?

Front

element = a.get(0);

Back

When you overload a method defined in a superclass, you must do which one of these? 1. Change either the number, type, or order of parameters in the subclass. 2. Use an access specifier that is at least as permissive as the superclass method 3. Return exactly the same type as the original method. 4. Use exactly the same number and type of parameters as the original method.

Front

Change either the number, type, or order of parameters in the subclass.

Back

public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } What does the default constructor do in the class definition above? 1. Sets the value of x to 0 2. There is no default constructor. 3. Sets the value of x to 1 4. Sets the value of x to a

Front

3. Sets the value of x to 1.

Back

Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (value > 0) { a[size] = value; size++; value = cin.nextInt(); } 1. May crashe at runtime because it can input more elements than the array can hold 2. Reads up to 3 values and inserts them in the array in the correct position. 3. Reads one value and places it in the remaining first unused space endlessly. 4. Reads up to 3 values and places them in the array in the unused space.

Front

1. May crashe at runtime because it can input more elements than the array can hold

Back

Inheritance gives your programs the ability to express _______________ between classes. 1. encapsulation 2. relationships 3. composition 4. dependencies

Front

relationships

Back

What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 1; if (j > 2) alpha[j - 1] = alpha[j] + 2; } 1. alpha = {1, 2, 3, 4, 5} 2. alpha = {4, 5, 6, 7, 9} 3. alpha = {1, 5, 6, 7, 5} 4. None of these

Front

None of these

Back

Which of the following is used to allocate memory for the instance variables of an object of a class? 1. the reserved word public 2. the operator new 3. the operator + 4. the reserved word static

Front

2. The operator new

Back

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] > a[x]) x = i; System.out.println(x); 1. Finds the position of the largest value in a. 2. Sums the elements in a. 3. Finds the position of the smallest value in a. 4. Counts the elements in a.

Front

Finds the position of the largest value in a.

Back

If a class's only constructor requires an argument, you must provide an argument for every ____ of the class that you create. 1. object 2. type 3. parameter 4. method

Front

1. Object

Back

You are ____ required to write a constructor method for a class.

Front

never

Back

What does the following loop print? int[] a = {6, 1, 9, 5, 12, 7}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 1) x++; System.out.println(x); 1. 18 2. 2 3. 22 4. 4

Front

4

Back

When you define a subclass, like Student, and don't supply a constructor, then its superclass must: 1. have no constructors defined 2. have no constructors defined or have an explicit default (no-arg) constructor defined. 3. have an explicit copy constructor defined 4. have an explicit default (no-arg) constructor defined 5. have an explicit working constructor defined

Front

have no constructors defined or have an explicit default (no-arg) constructor defined.

Back

An object is a(n) ____ of a class. 1. instance 2. method 3. field 4. constant

Front

1. Instance

Back

double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is in vals[2][1]? 1. 1.3 2. 3.3 3. 3.5 4. 5.3

Front

5.3

Back

The ____________ relationship occurs when members of one class form a subset of another class, like the Animal, Mammal, Rodent example we discussed in the online lessons. 1. encapsulation 2. composition 3. is-A 4. has-A

Front

is-A

Back

What does a contain after the following loop? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; for (int i = pos; i < size - 1; i++) a[i + 1] = a[i]; size--;

Front

{1, 1, 1, 0, 0, 0}

Back

To prevent subclasses from overriding an inherited method, the superclass can mark the method as:

Front

final

Back

The reference to an object that is passed to any object's nonstatic class method is called the ____. 1. this reference 2. magic number 3. literal constant 4. reference

Front

1. This

Back

What does a contain after the following loop? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; for (int i = pos; i < size - 1; i++) a[i] = a[i + 1]; size--;

Front

{3, 7, 7, 0, 0, 0}

Back

Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long If you define a subclass of Person, like Student, and add a single constructor with this signature Student(String name, long id), that contains no code whatsoever, your program will only compile if the superclass (Person) contains: 1. an explicit constructor of whatever type 2. a setName() method to initialize the name field 3. an implicit constructor along with a working constructor 4. a default or no-arg constructor

Front

a default or no-arg constructor

Back

To use an ArrayList in your program, you must import: 1. the java.collections package 2. the java.awt package 3. Nothing; the class is automatically available, just like regular arrays. 4. the java.util package 5. the java.lang package

Front

the java.util package

Back

Methods that require you to use an object to call them are called ____ methods. 1. accessor 2. instance 3. internal 4. static

Front

2. Instance

Back

Section 33

(50 cards)

What does the following loop print? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = a[0]; for (int i = 1; i < len; i++) if (a[i] < x) x = a[i]; System.out.println(x); 1. 1 2. 12 3. 6 4. 36

Front

1. 1

Back

double[] as = new double[7]; double[] bs; bs = as; How many objects are present after the code fragment above is executed? 1. 2 2. 14 3. 1 4. 7

Front

1

Back

What does a contain after the following loop? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; for (int i = size; i > pos; i--) a[i - 1] = a[i]; size--; 1. {3, 7, 0, 0, 0, 0} 2. {0, 0, 0, 0, 0, 0} 3. {3, 7, 7, 0, 0, 0} 4. {1, 1, 1, 0, 0, 0}

Front

{0, 0, 0, 0, 0, 0}

Back

Suppose you have the following declaration. int[] beta = new int[50]; Which of the following is a valid element of beta. (i) beta[0] (ii) beta[50]

Front

Only (i)

Back

Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (size < capacity && value > 0) { a[size] = value; size++; value = cin.nextInt(); } 1. Reads one value and places it in the remaining first unused space endlessly. 2. Crashes at runtime because it tries to write beyond the array. 3. Reads up to 3 values and places them in the array in the unused space. 4. Reads up to 3 values and inserts them in the array in the correct position.

Front

Reads up to 3 values and places them in the array in the unused space.

Back

Consider the following declaration. int[] alpha = new int[3]; Which of the following input statements correctly input values into alpha? (i) alpha = cin.nextInt(); alpha = cin.nextInt(); alpha = cin.nextInt(); (ii) alpha[0] = cin.nextInt(); alpha[1] = cin.nextInt(); alpha[2] = cin.nextInt(); 1. Only (i) 2. Only (ii) 3. None of these 4. Both (i) and (ii)

Front

Only (ii)

Back

Here is a loop that should average the contents of the array named ar : double sum = 0.0; int n = 0; for (int i=0; i < ar.length; i++, n++) sum = sum + ar[i]; if ( ?????? ) System.out.println("Average = " + ( sum / n ); What goes where the ???? appears : A. sum > 0 B. n == 0 C. n > 0 D. None of these

Front

C. n > 0

Back

What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 5; if (j % 2 == 1) alpha[j - 1] = alpha[j] + 2; }

Front

alpha = {8, 6, 10, 8, 9}

Back

What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 1; if (j > 2) alpha[j - 1] = alpha[j] + 2; }

Front

None of these

Back

Consider the following method which takes any number of parameters. Which statement would return the first of the numbers passed when calling the method? int first = firstNum(7, 9, 15); public int firstNum(int..nums) { // what goes here? } 1. return nums[0] 2. return nums; 3. return nums...0 4. return nums.first;

Front

3. return nums..0

Back

char[][] array1 = new char[15][10]; What is the value of array1.length? 1. 0 2. 10 3. 2 4. 15

Front

4. 15

Back

int[] hit = new hit[5]; hit[0] = 3; hit[1] = 5; hit[2] = 2; hit[3] = 6; hit[4] = 1; System.out.println(hit[1 + 3]); What is the output of the code fragment above? 1. 1 2. 5 3. 6 4. 3

Front

1

Back

If you pass the first element of the array ar to the method x() like this, x(ar[0]); the element ar[0] :

Front

cannot be changed by the method x()

Back

Which of the following statements creates alpha, an array of 5 components of the type int, and initializes each component to 10? (i) int[] alpha = {10, 10, 10, 10, 10}; (ii) int[5] alpha = {10, 10, 10, 10, 10}

Front

Only (i)

Back

Suppose you have the following declaration. char[] nameList = new char[100]; Which of the following range is valid for the index of the array nameList. (i) 1 through 100 (ii) 0 through 100 1. Both are invalid 2. Only (i) 3. None of these 4. Only (ii)

Front

1. Both are invalid

Back

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] > a[x]) x = i; System.out.println(x); 1. Finds the position of the smallest value in a. 2. Sums the elements in a. 3. Counts the elements in a. 4. Finds the position of the largest value in a.

Front

4. Finds the position of the largest value in a.

Back

char[][] array1 = new char[15][10]; What is the value of array1[3].length? 1. 15 2. 10 3. 2 4. 0

Front

2. 10

Back

What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 1; if (j > 2) alpha[j - 1] = alpha[j] + 2; } 1. None of these 2. alpha = {1, 2, 3, 4, 5} 3. alpha = {1, 5, 6, 7, 5} 4. alpha = {4, 5, 6, 7, 9}

Front

1. None of these

Back

What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; for (j = 4; j >= 0; j--) { alpha[j] = j + 5; if (j <= 2) alpha[j + 1] = alpha[j] + 3; } 1. 9 2. 5 3. 8 4. 10

Front

4. 10

Back

What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = 2 * j; if (j % 2 == 1) alpha[j - 1] = alpha[j] + j; } 1. alpha = {0, 2, 4, 6, 8} 2. alpha = {0, 2, 9, 6, 8} 3. alpha = {3, 2, 9, 6, 8} 4. alpha = {0, 3, 4, 7, 8}

Front

alpha = {3, 2, 9, 6, 8}

Back

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int x = 0; for (int e : a) x++; 1. Sums all the elements in a. 2. Will not compile (syntax error) 3. Counts each element in a. 4. Finds the largest value in e.

Front

3. Counts each element in a.

Back

The first element in the array created by the statement int[] ar = { 1, 2, 3 }; is :

Front

ar[0]

Back

double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is the value of vals[4][1] in the array above? 1. 7.1 2. There is no such value. 3. 7.3 4. 1.1

Front

There is no such value.

Back

To create the array variable named ar, you would use : A. int ar; B. int() ar; C. int[] ar; D. None of these

Front

C. int[] ar;

Back

Consider the following declaration. double[] sales = new double[50]; int j; Which of the following correctly initializes all the components of the array sales to 10. (i) for (j = 0; j < 49; j++) sales[j] = 10; (ii) for (j = 1; j <= 50; j++) sales[j] = 10;

Front

None of these

Back

Assume that two arrays are parallel. Assume the first array contains a person's id number and the second contains his or her age. In which index of the second array would you find the age of the person in the third index of the first array? 1. 2 2. 3 3. 1 4. It cannot be determined from the information given.

Front

2. 3

Back

The last element in the array created by the statement int[] ar = { 1, 2, 3 }; is :

Front

ar[2]

Back

What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; for (j = 4; j >= 0; j--) { alpha[j] = j + 5; if (j <= 2) alpha[j + 1] = alpha[j] + 3; } 1. 8 2. 10 3. 9 4. 5

Front

2. 10

Back

What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] > value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 1, 3, 5, 7, 0, 0 } 2. { 1, 3, 5, 0, 0, 0 } 3. { 1, 3, 7, 5, 0, 0 } 4. { 5, 1, 3, 7, 0, 0 }

Front

{ 1, 3, 5, 7, 0, 0 }

Back

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the index number of the last component in the array above? 1. 99 2. 100 3. 0 4. 101

Front

1. 99

Back

If you pass the array ar to the method m() like this, m(ar); the element ar[0] : A. will be changed by the method m() B. cannot be changed by the method m() C. may be changed by the method m(), but not necessarily D. None of these

Front

C. may be changed by the method m(), but not necessarily

Back

What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = 2 * j; if (j % 2 == 1) alpha[j - 1] = alpha[j] + j; } 1. alpha = {0, 2, 4, 6, 8} 2. alpha = {0, 3, 4, 7, 8} 3. alpha = {0, 2, 9, 6, 8} 4. alpha = {3, 2, 9, 6, 8}

Front

4. alpha = {3, 2, 9, 6, 8}

Back

You can create an array of three integers by writing :

Front

int ar[] = new int[3];

Back

Which of the following about Java arrays is true? (i) Array components must be of the type double. (ii) The array index must evaluate to an integer.

Front

Only (ii)

Back

Which of the following about Java arrays is true? (i) All components must be of the same type. (ii) The array index and array element must be of the same type.

Front

Only (i)

Back

Which of the following statements creates alpha, a two-dimensional array of 10 rows and 5 columns, wherein each component is of the type int? 1. Both (i) and (ii) 2. Only (ii) 3. None of these 4. Only (i)

Front

Only (ii)

Back

What is the output of the following Java code? int[] alpha = {2, 4, 6, 8, 10}; int j; for (j = 4; j >= 0; j--) System.out.print(alpha[j] + " "); System.out.println();

Front

10 8 6 4 2

Back

What does the following loop print? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = a[0]; for (int i = 1; i < len; i++) if (a[i] > x) x = a[i]; System.out.println(x); 1. 36 2. 6 3. 12 4. 1

Front

3. 12

Back

Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (size < capacity && value > 0) { a[size] = value; size++; 1. Reads one value and places it in the remaining three unused spaces in a. 2. Reads up to 3 values and places them in the array in the unused space. 3. Reads up to 3 values and inserts them in the array in the correct position. 4. Crashes at runtime because it tries to write beyond the array.

Front

1. Reads one value and places it in the remaining three unused spaces in a.

Back

To print the number of elements in the array named ar, you can write : A.System.out.println(length); B.System.out.println(ar.length()); C.System.out.println(ar.length); D.System.out.println(ar.length-1);

Front

C. System.out.println(ar.length);

Back

Suppose we want to store a tic-tac-toe board in a program; it's a three-by-three array. It will store "O", "X" or a space at each location (that is, every location is used), and you use a two-dimensional array called board to store the individual tiles. Suppose you pass board to a method that accepts a two-dimensional array as a parameter. If the method was designed to process two-dimensional arrays of various sizes. What information about the size of the array would have to be passed to the method so it could properly process the array? A. the number of columns in the array B. the number of rows in the array C. the number of cells in the array D. Both A and B E. No additional information is needed, as the array carries its size information with it.

Front

E. No additional information is needed, as the array carries its size information with it.

Back

Given the method heading public void strange(int a, int b) and the declaration int[] alpha = new int[10]; int[] beta = new int[10];

Front

strange(alpha[0], alpha[1]);

Back

What is the output of the following Java code? int[] list = {0, 5, 10, 15, 20}; int j; for (j = 1; j <= 5; j++) System.out.print(list[j] + " "); System.out.println(); 1. 5 10 15 20 0 2. 5 10 15 20 20 3. 0 5 10 15 20 4. Code contains index out-of-bound

Front

Code contains index out-of-bound

Back

Consider the following declaration. Scanner cin = new Scanner(System.in); int[] beta = new int[3]; int j; Which of the following input statements correctly input values into beta? (i) beta[0] = cin.nextInt(); beta[1] = cin.nextInt(); beta[2] = cin.nextInt(); (ii) for (j = 0; j < 3; j++) beta[j] = cin.nextInt();

Front

Both (i) and (ii)

Back

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is visible in method one? 1. x (block three's local variable) 2. local variables of method two 3. rate (before main) 4. one (method two's formal parameter)

Front

rate (before main)

Back

Which of the following creates an array of 25 components of the type int? (i) int[] alpha = new[25]; (ii) int[] alpha = new int[25];

Front

Only (ii)

Back

Local variables A. Lose the values stored in them between calls to the method in which the variable is declared B. May have the same name as local variables in other methods C. Are hidden from other methods D. All of the above

Front

All of the above

Back

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is visible on the line marked // main block? 1. All identifiers are visible in main. 2. local variables of method two 3. w (before method two) 4. z (before main)

Front

w (before method two)

Back

To print the last element in the array named ar, you can write : A. System.out.println(ar.length); B. System.out.println(ar[length]); C. System.out.println(ar[ar.length]); D. None of these

Front

D

Back

What is the value of alpha[4] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 2; for (j = 1; j < 5; j++) alpha[j] = alpha[j - 1] + 3; 1. 11 2. 14 3. 5 4. 8

Front

2. 14

Back

Section 34

(50 cards)

The header of a value-returning method must specify this. A. The method's local variable name B. The data type of the return value C. The name of the variable in the calling program that will receive the returned value D. All of the above

Front

The data type of the return value

Back

Which of the following would be a valid method call for the following method? public static void showProduct (int num1, double num2) { int product; product = num1 * (int)num2; System.out.println("The product is " + product); } A. showProduct(10.0, 4); B. showProduct(33.0, 55.0); C. showProduct(5.5, 4.0); D. showProduct(10, 4.5);

Front

D. showProduct(10, 4.5);

Back

When a method tests an argument and returns a true or false value, it should return

Front

A boolean value

Back

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following is an example of a local identifier in the example above? 1. w (line 20) 2. t (line 5) 3. a (line 25) 4. rate (line 3)

Front

3. a (line 25)

Back

Which of the following is not a benefit derived from using methods in programming? A. Code reuse B. Problems are more easily solved C. Simplifies programs D. All of the above are benefits

Front

D. All of the above are benefits

Back

In a @return tag statement the description A. Describes the return value B. Must be longer than one line C. Cannot be longer than one line D. Describes the parameter values

Front

Describes the return value

Back

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Where is identifier x (block three's local variable) visible? 1. In two and block three 2. In block three and main 3. In block three only 4. In one and block three

Front

In block three only

Back

methods are commonly used to

Front

Break a problem down into small manageable pieces.

Back

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } What is the name of the method above?

Front

minimum

Back

What will be returned from the following method? public static double methodA() { double a = 8.5 + 9.5; return a; }

Front

18.0

Back

When an object, such as a String, is passed as an argument, it is

Front

Actually a reference to the object that is passed

Back

Which of the following is not part of a method call? A. Return type B. Parentheses C. Method name D. All of the above are part of a method call

Front

Return type

Back

All @param tags in a method's documentation comment must

Front

Appear after the general description of the method

Back

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Based on the above code, what would be the output of the statement int s = minimum(5, minimum(3, 7));

Front

3

Back

When an argument is passed to a method,

Front

Its value is copied into the method's parameter variable

Back

What is wrong with the following method call? displayValue (double x);

Front

The data type of the argument x should not be included in the method call

Back

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is visible in block three? x (one's formal parameter) t (before main) z (before main) local variables of main

Front

t (before main)

Back

What will be returned from the following method? public static double methodA() { double a = 8.5 + 9.5; return a; }

Front

18.0

Back

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is NOT visible in block three? 1. t (before main) 2. z (before main) 3. local variables of method two 4. main

Front

z (before main)

Back

public static String exampleMethod(int n, char ch) Which of the following statements about the method heading above is NOT true? 1. The method has two parameters. 2. exampleMethod is an identifier giving a name to this specific method. 3. The method cannot be used outside the class. 4. It is a value-returning method of type String.

Front

3. The method cannot be used outside the class.

Back

Which of the following is NOT true about return statements? 1. A method can have more than one return statement. 2. return statements can be used in void methods to return values. 3. Whenever a return statement executes in a method, the remaining statements are skipped and the method exits. 4. A value-returning method returns its value via the return statement.

Front

2. return statements can be used in void methods to return values.

Back

public static String exampleMethod(int n, char ch) Based on the method heading above, what is the return type of the value returned? 1. char 2. String 3. int 4. Nothing will be returned

Front

String

Back

What is wrong with the following method call? displayValue (double x);

Front

The data type of the argument x should not be included in the method call

Back

Methods are commonly used to

Front

Break a problem down into small manageable pieces

Back

This part of a method is a collection of statements that are performed when the method is executed.

Front

Method body

Back

Which modifier is used to specify that a method cannot be used outside a class?

Front

private

Back

Formal parameters of primitive data types provide ____ between actual parameters and formal parameters.

Front

a one-way link

Back

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Based on the above code, what would be the output of the statement int s = minimum(5, minimum(3, 7)); 1. 5 2. There would be no output; this is not a valid statement. 3. 7 4. 3

Front

3

Back

When an object, such as a String, is passed as an argument, it is A. Passed by value like any other parameter value B. Actually a reference to the object that is passed C. Encrypted D. Necessary to know exactly how long the string is when writing the program

Front

Actually a reference to the object that is passed

Back

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } What is the return type of the method above?

Front

int

Back

Given the following method header, which of the method calls would cause an error? public void displayValues(int x, int y)

Front

displayValue(a,b); // where a is a short and b is a long

Back

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is a valid call to the method above? 1. minimum(int x, int y); 2. minimum(int 5, int 4); 3. minimum(5, 4); 4. public static int minimum(5, 4);

Front

minimum(5, 4);

Back

In a @return tag statement the description

Front

Describes the return value

Back

This type of method method performs a task and sends a value back to the code that called it. A. Local B. Void C. Complex D. Value-returning

Front

Value-returning

Back

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is a valid call to the method above?

Front

minimum(5, 4);

Back

Which of the following is NOT a modifier?

Front

return

Back

Which of the following is NOT an actual parameter? 1. Expressions used in a method call 2. Constant values used in a method call 3. Variables used in a method call 4. Variables defined in a method heading

Front

Variables defined in a method heading

Back

Functional decomposition is

Front

The process of breaking a problem down into smaller pieces.

Back

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is a valid call to the method above?

Front

minimum(5, 4);

Back

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is NOT visible in method two?

Front

x (variable in block three)

Back

Which of the following statements is NOT true?

Front

The operator new must always be used to allocate space of a specific type, regardless of the type.

Back

Which of the following statements is NOT true? 1. Reference variables contain the address of the memory space where the data is stored. 2. The operator new must always be used to allocate space of a specific type, regardless of the type. 3. Reference variables do not directly contain the data. 4. A String variable is actually a reference variable of the type String.

Front

2. The operator new must always be used to allocate space of a specific type, regardless of the type.

Back

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is NOT part of the heading of the method above? 1. static 2. int smaller; 3. minimum(int x, int y) 4. public

Front

2. int smaller;

Back

In the following code, System.out.println(num), is an example of ________. double num = 5.4; System.out.println(num); num = 0.0;

Front

A void method

Back

What is an actual parameter?

Front

The value passed into a method by a method call

Back

If method A calls Method B, and method B calls method C, and method C calls method D, when method D finishes, what happens?

Front

Control is returned to method C

Back

The header of a value-returning method must specify this.

Front

The data type of the return value

Back

The lifetime of a method's local variable is

Front

Only while the method is executing

Back

In the following code, System.out.println(num), is an example of ________. double num = 5.4; System.out.println(num); num = 0.0;

Front

A void method

Back

This type of method method performs a task and sends a value back to the code that called it.

Front

Value-returning

Back

Section 35

(50 cards)

Consider the following method definition. public int strange(int[] list, int item) { int count; for (int j = 0; j < list.length; j++) if (list[j] == item) count++; return count; } Which of the following statements best describe the behavior of this method? 1. This method returns the sum of all the values of list. 2. None of these 3. This method returns the number of times item is stored in list. 4. This method returns the number of values stored in list.

Front

3. This method returns the number of times item is stored in list.

Back

If you pass the first element of the array ar to the method x() like this, x(ar[0]); the element ar[0] : A. will be changed by the method x() B. cannot be changed by the method x() C. may be changed by the method x(), but not necessarily D. None of these

Front

B. cannot be changed by the method x()

Back

The last element in the array created by the statement int[] ar = { 1, 2, 3 }; is : A. ar[3] B. ar[2] C. ar(3) D. ar(2)

Front

B. ar[2]

Back

double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} How many rows are in the array above? 1. 4 2. 0 3. 2 4. 3

Front

1. 4

Back

Consider the following statements. public class PersonalInfo { private String name; private int age; private double height; private double weight; public void set(String s, int a, double h, double w) { name = s; age = a; height = h; weight = w; } public String getName() { return name; } public int getAge() { return age; } public double getHeight() { return height; } public double getWeight() { return weight; } } Assume you have the following code fragment inside a method in a different class: PersonalInfo person1 = new PersonalInfo(); PersonalInfo person2 = new PersonalInfo(); String n; int a; double h, w; Which of the following statements are valid (both syntactically and semantically) in Java? (i) person2 = person1; (ii) n = person1.getName(); a = person1.getAge(); h = person1.getHeight(); w = person1.getWeight(); person2.set(n, a, h, w); 1. None of these 2. Only (ii) 3. Only (i) 4. Both (i) and (ii)

Front

4. Both (i) and (ii)

Back

Assigning ____ to a field means that no other classes can access the field's values. 1. key access 2. user rights 3. private access 4. protected access

Front

3. private access

Back

The keyword ____ indicates that a field value is non-changable. 1. const 2. readonly 3. final 4. static

Front

3. final

Back

Suppose you have the following declaration. double[] salesData = new double[1000]; Which of the following range is valid for the index of the array salesData. (i) 0 through 999 (ii) 1 through 1000 1. Only (i) 2. None of these 3. Both are invalid 4. Only (ii)

Front

1. Only (i)

Back

char[][] array1 = new char[15][10]; How many dimensions are in the array above? 1. 3 2. 2 3. 1 4. 0

Front

2. 2

Back

Here is a loop that is supposed to sum each of the values in the array named ar : double sum = 0.0; for (int i=0; i < ar.length; i++) // ??? System.out.println(sum); What goes on the line containing ???? : A. i = sum + ar[i]; B. sum + ar[i]; C. sum = sum + i; D. sum += ar[i];

Front

D. sum += ar[i];

Back

Which of the following is the array subscripting operator in Java? 1. . 2. {} 3. [] 4. new

Front

3. []

Back

What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 5; for (j = 1; j < 5; j++) { if (j % 2 == 0) alpha[j] = alpha[j - 1] + 2; else alpha[j] = alpha[j - 1] + 3; } 1. 13 2. 15 3. None of these 4. 10

Front

1. 13

Back

To print the last element in the array named ar, you can write : A. System.out.println(ar.length); B. System.out.println(ar[length]); C. System.out.println(ar[ar.length]); D. None of these

Front

D. None of these

Back

int[] hits = {10, 15, 20, 25, 30}; copy(hits); What is being passed into copy in the method call above? 1. 10 2. A reference to the array object hits 3. The value of the elements of hits 4. A copy of the array hits

Front

2. A reference to the array object hits

Back

The value of the last element in the array created by the statement int[] ar = new int[3]; is : A. 0 B. 1 C. 2 D. 3

Front

A. 0

Back

What does a contain after the following loop? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; for (int i = size; i > pos; i--) a[i - 1] = a[i]; size--; 1. {3, 7, 7, 0, 0, 0} 2. {1, 1, 1, 0, 0, 0} 3. {3, 7, 0, 0, 0, 0} 4. {0, 0, 0, 0, 0, 0}

Front

4. {0, 0, 0, 0, 0, 0}

Back

What does the following loop print? int[] a = {6, 9, 1, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] < a[x]) x = i; System.out.println(x); 1. 6 2. 1 3. 2 4. 4

Front

3. 2

Back

Suppose we define a class called NameInfo. It has several private fields, including String hospName; and several public methods, including one that accesses hospName: String getName(); Now, we define an array like this: NameInfo[] listOfHospitals = new NameInfo[100]; Which expression below correctly accesses the name of the hospital that's stored in position 5 (that is, the 6th element) of the listOfHospitals? A. listOfHospitals.getName(5) B. listOfHospitals.hospName[5] C. listOfHospitals[5].hospName D. listOfHospitals[getName(5)] E. listOfHospitals[5].getName()

Front

E. listOfHospitals[5].getName()

Back

How can a method send a primitive value back to the caller?

Front

By using the return statement

Back

Which of the following class definitions is correct in Java? (i) public class Student { private String name; private double gpa; private int id; public void Student() { name = ""; gpa = 0; id = 0; } public void Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } (ii) public class Student { private String name; private double gpa; private int id; public Student() { name = ""; gpa = 0; id = 0; } public Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } 1. Only (i) 2. Both (i) and (ii) 3. None of these 4. Only (ii)

Front

4. Only (ii)

Back

You can create an array of three doubles by writing : A. double ar[] = 3; B. double ar[3]; C. double ar[] = { 1.1, 2.2, 3.3 }; D. double[] ar = double(3);

Front

C. double ar[] = { 1.1, 2.2, 3.3 };

Back

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 7}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 1) x += a[i]; System.out.println(x); 1. Finds the largest value in a. 2. Finds the smallest value in a. 3. Counts the odd elements in a. 4. Sums the odd elements in a.

Front

4. Sums the odd elements in a.

Back

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is a valid call to the method above?

Front

minimum(5, 4);

Back

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] < a[x]) x = i; System.out.println(x); 1. Finds the position of the smallest value in a. 2. Sums the elements in a. 3. Finds the position of the largest value in a. 4. Counts the elements in a.

Front

1. Finds the position of the smallest value in a.

Back

double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is in vals[2][1]? 1. 3.3 2. 3.5 3. 1.3 4. 5.3

Front

4. 5.3

Back

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; for (int e : a) e = 0; 1. Changes each element in a to 0. 2. Compiles, but crashes when run. 3. Changes each element e to 0 but has no effect on the corresponding element in a. 4. Will not compile (syntax error)

Front

3. Changes each element e to 0 but has no effect on the corresponding element in a.

Back

Which of the following methods returns an array ? A. int acpy(int n) { ... } B. int acpy(int[] n) { ... } C. int[] acpy(int n) { ... } D. None of these

Front

C. int[] acpy(int n) { ... }

Back

What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] < value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 1, 3, 7, 5, 0, 0 } 2. { 1, 3, 5, 0, 0, 0 } 3. { 1, 3, 5, 7, 0, 0 } 4. { 5, 1, 3, 7, 0, 0 }

Front

4. { 5, 1, 3, 7, 0, 0 }

Back

What is the value of alpha[4] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 2; for (j = 1; j < 5; j++) alpha[j] = alpha[j - 1] + 3; 1. 5 2. 11 3. 8 4. 14

Front

4. 14

Back

What is the value of alpha[2] after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) alpha[j] = 2 * j + 1; 1. 1 2. 4 3. 5 4. 6

Front

3. 5

Back

Which of the following statements about strings is NOT true? 1. The class String contains many methods that allow you to change an existing string. 2. A String variable is actually a reference variable. 3. When a string is assigned to a String variable, the string cannot be changed. 4. When you use the assignment operator to assign a string to a String variable, the computer allocates memory space large enough to store the string.

Front

The class String contains many methods that allow you to change an existing string.

Back

int[] x = new int[10]; x[0] = 34; x[1] = 88; println(x[0] + " " + x[1] + " " + x[10]); What is the output of the code fragment above? 1. 34 88 88 2. This program throws an exception. 3. 34 88 0 4. 0 34 88

Front

2. This program throws an exception.

Back

Which of the following statements is NOT true? 1. Reference variables contain the address of the memory space where the data is stored. 2. The operator new must always be used to allocate space of a specific type, regardless of the type. 3. Reference variables do not directly contain the data. 4. A String variable is actually a reference variable of the type String.

Front

2. The operator new must always be used to allocate space of a specific type, regardless of the type.

Back

A(n) ____ method is a method that creates and initializes objects. 1. constructor 2. non-static 3. instance 4. accessor

Front

1. constructor

Back

What is the value of alpha[2] after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) alpha[j] = 2 * j + 1; 1. 4 2. 6 3. 1 4. 5

Front

4. 5

Back

What does the following loop do? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] > value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. Removes (deletes) value from a so that the array remains ordered. 2. Places value in the last element of a 3. Inserts value into a so that the array remains ordered. 4. Places value in the first unused space in a (where the first 0 appears)

Front

3. Inserts value into a so that the array remains ordered.

Back

Consider the following statements. public class Circle { private double radius; public Circle() { radius = 0.0; } public Circle(double r) { radius = r; } public void set(double r) { radius = r; } public void print() { System.out.println(radius + " " + area + " " + circumference()); } public double area() { return 3.14 radius radius; } public double circumference() { return 2 3.14 radius; } } Assume, also that you have the following two statements appearing inside a method in another class: Circle myCircle = new Circle(); double r; Which of the following statements are valid (both syntactically and semantically) in Java? (Assume that cin is Scanner object initialized to the standard input device.) (i) r = cin.nextDouble(); myCircle.area = 3.14 r r; System.out.println(myCircle.area); (ii) r = cin.nextDouble(); myCircle.set(r); System.out.println(myCircle.area()); 1. Only (ii) 2. Both (i) and (ii) 3. Only (i) 4. None of these

Front

1. Only (ii)

Back

Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 length + 2 width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following statements are valid in Java? (Assume that cin is Scanner object initialized to the standard input device.) (i) bigRect.length = cin.nextDouble(); bigRect.width = cin.nextDouble(); (ii) double l; double w; l = cin.nextDouble(); w = cin.nextDouble(); bigRect.set(l, w); 1. Only (i) 2. Only (ii) 3. Both (i) and (ii) 4. None of these

Front

2. Only (ii)

Back

int[] array1 = {1, 3, 5, 7}; for (int i = 0; i < array1.length; i++) if (array1[i] > 5) System.out.println(i + " " + array1[i]); What is the output of the code fragment above? 1. 0 3 2. 7 3 3. 5 1 4. 3 7

Front

4. 3 7

Back

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x += a[i]; System.out.println(x); 1. Sums the even elements in a. 2. Finds the largest value in a. 3. Finds the smallest value in a. 4. Counts the even elements in a.

Front

1. Sums the even elements in a.

Back

You can use ____ arguments to initialize field values, but you can also use arguments for any other purpose. 1. constructor 2. field 3. data 4. object

Front

1. constructor

Back

What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 5; if (j % 2 == 1) alpha[j - 1] = alpha[j] + 2; } 1. alpha = {5, 6, 10, 8, 9} 2. alpha = {8, 6, 7, 8, 9} 3. alpha = {5, 6, 7, 8, 9} 4. alpha = {8, 6, 10, 8, 9}

Front

4. alpha = {8, 6, 10, 8, 9}

Back

A(n) ____ constructor is one that requires no arguments. Student Response Value Correct Answer Feedback 1. write 2. default 3. class 4. explicit

Front

2. default

Back

Which of the following words indicates an object's reference to itself? 1. public 2. that 3. this 4. protected

Front

3. this

Back

When an object, such as a String, is passed as an argument, it is

Front

Actually a reference to the object that is passed

Back

Methods are commonly used to

Front

Break a problem down into small manageable pieces

Back

A(n) ____ variable is known only within the boundaries of the method. 1. instance 2. double 3. local 4. method

Front

3. local

Back

Consider the following declaration. int[] list = new int[10]; int j; int sum; Which of the following correctly finds the sum of the elements of list? (i) sum = 0; for (j = 0; j < 10; j++) sum = sum + list[j]; (ii) sum = list[0]; for (j = 1; j < 10; j++) sum = sum + list[j]; 1. Only (ii) 2. Only (i) 3. Both (i) and (ii) 4. None of these

Front

3. Both (i) and (ii)

Back

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; How many components are in the array above? 1. 100 2. 0 3. 50 4. 99

Front

1. 100

Back

public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } How many constructors are present in the class definition above? 1. 3 2. 2 3. 1 4. 0

Front

2. 2

Back

Section 36

(50 cards)

How many constructors can a class have? 1. 2 2. Any number 3. 1 4. 0

Front

2. Any number

Back

Methods that retrieve values are called ____ methods. 1. static 2. mutator 3. accessor 4. class

Front

3. accessor

Back

Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Which of these fields or methods are inherited by the Person class? 1. getName(), setName(), studentID, getID() 2. getName(), setName(), name 3. None of them 4. studentID, name, getName(), setName(), getID() 5. name, getName(), setName(), getID()

Front

None of them

Back

Which of these are superclass members are not inherited by a subclass? 1. a protected method 2. a protected instance variable 3. a public instance variable 4. a public constructor 5. a public method

Front

4. a public constructor

Back

When you define a subclass, like Student, and add a single constructor with this signature Student(String name, long id), an implicit first line is added to your constructor. That line is: 1. No implicit lines are added to your constructor 2. this(); 3. super(name, id); 4. base(); 5. super();

Front

5. super();

Back

How many constructors can a class have? 1. Any number 2. 2 3. 1 4. 0

Front

1. Any number

Back

Mutator methods typically have a return type of ______________. 1. boolean 2. String 3. void 4. int

Front

3. void

Back

A locally declared variable always ____ another variable with the same name elsewhere in the class. 1. uses 2. creates 3. deletes 4. masks

Front

4. masks

Back

Mutator methods typically begin with the word "____". 1. read 2. get 3. call 4. set

Front

4. set.

Back

Which of the following lines of code explicitly calls the toString() method, assuming that pete is an initialized Student object variable? 1. println(pete.toString()); 2. println("" + pete); 3. println(super.toString()); 4. println(pete)

Front

1. println(pete.toString());

Back

Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public void perimeter() { return 2 length + 2 width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(); Which of the following sets of statements are valid in Java? (i) bigRect.set(10, 5); (ii) bigRect.length = 10; bigRect.width = 5; 1. Only (ii) 2. None of these 3. Only (i) 4. Both (i) and (ii)

Front

3. Only (i)

Back

Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 length + 2 width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following sets of statements are valid (both syntactically and semantically) in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); 1. Both (i) and (ii) 2. Only (ii) 3. None of these 4. Only (i)

Front

4. Only (i)

Back

If a method in the superclass is declared protected, you may replace it in the subclass as long as the subclass method that you define: 1. has a different number, type, or order of parameters 2. has a different return type 3. is defined as protected or private 4. is defined as public or protected 5. is defined only as public

Front

4. is defined as public or protected

Back

A variable comes into existence, or ____, when you declare it. 1. is referenced 2. comes into scope 3. overrides scope 4. goes out of scope

Front

2. comes into scope

Back

Suppose we have these two array definitions in main(): String[] hospName = new String[100]; int[] hospCode = new int[100]; hospCode[I] stores the code for a specific hospital. hospName[J] stores the name of the hospital that has code J. Suppose the code 24 is stored at position 13 of hospCode. Which expression below references 24's corresponding name? A. hospName[13] B. hospCode[24] C. hospCode[hospName[13]] D. hospName[hospCode[13]] E. hospName[hospCode[24]]

Front

D. hospName[hospCode[13]] General Feedback: What we want is the name for hospital with code 24. We could get that with hospName[24], but that's not one of the options. However, we know that hospCode[13] contains the value 24, so we can use that instead.

Back

In the type-safe version of the ArrayList class, you specify the type of each element by: 1. None of these; an ArrayList can hold any object type 2. specifying a generic type parameter when defining the ArrayList variable 3. using the special type-safe version of the subscript operator 4. passing a Class parameter as the first argument to the constructor 5. using the setType() method once the ArrayList is constructed

Front

specifying a generic type parameter when defining the ArrayList variable

Back

To access the name instance variable from inside a method defined in the Student class, name must use the _____________ modifier. (We'll ignore the default package-private access if no modifier is used.) 1. public 2. protected or public 3. private or protected 4. private 5. protected 6. Any of them

Front

2. protected or public

Back

When you define a subclass, like Student, and don't supply a constructor, then its superclass must: 1. have an explicit working constructor defined 2. have no constructors defined 3. have an explicit default (no-arg) constructor defined 4. have an explicit copy constructor defined 5. have no constructors defined or have an explicit default (no-arg) constructor defined.

Front

5. have no constructors defined or have an explicit default (no-arg) constructor defined.

Back

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

Front

Java: double varX= input.nextDouble();

Back

Assume you have a Student object and a Student variable named bill that refers to your Student object. Which of these statements would be legal? bill.name = "Bill Gates"; // I bill.setName("Bill Gates"); // II println(bill.getName()); // III bill.studentID = 123L; // IV println(bill.getID()); // V 1. II, III, IV, VI 2. IV, V 3. All of them 4. II, III, V 1 5. None of them

Front

4. II, III, V

Back

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x += a[i]; System.out.println(x); 1. Counts the even elements in a. 2. Sums the even elements in a. 3. Finds the largest value in a. 4. Finds the smallest value in a.

Front

2. Sums the even elements in a.

Back

The inside block, which is contained entirely within an outside block, is referred to as ____. 1. nested 2. out of scope 3. ambiguous 4. a reference

Front

1. nested

Back

Prompt the user

Front

Java: System.out.println

Back

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

Front

Java: Int varx= input.nextint();

Back

Create a Method called methodX

Front

Java: public static void methodX(){

Back

What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] > value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 5, 1, 3, 7, 0, 0 } 2. { 1, 3, 7, 5, 0, 0 } 3. { 1, 3, 5, 7, 0, 0 } 4. { 1, 3, 5, 0, 0, 0 }

Front

3. { 1, 3, 5, 7, 0, 0 }

Back

Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Which of these fields or methods are inherited by the Person class? 1. toString() 2. getName(), setName(), studentID, getID() 3. studentID, name, getName(), setName(), getID() 4. name, getName(), setName(), getID() 5. getName(), setName(), name 6. None of them

Front

toString()

Back

Which of the following lines of code explicitly calls the toString() method, assuming that pete is an initialized Student object variable? 1. println(super.toString()); 2. println("" + pete); 3. println(pete); 4. println(pete.toString());

Front

4. println(pete.toString());

Back

Create a Scanner object that reads from System.in

Front

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

Back

When you create a new class using inheritance, you use the extends keyword to specify the __________________ when you define the ________________. 1. derived class, subclass 2. derived class, base class 3. superclass, base class 4. subclass, base class 5. superclass, subclass 6. subclass, superclass

Front

5. superclass, subclass

Back

Methods that retrieve values are called ____ methods. 1. accessor 2. class 3. mutator 4. static

Front

1. accessor

Back

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int z = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Where is identifier z (block three's local variable) visible? 1. In block three and main 2. In block three only 3. In two and block three 4. In one and block three

Front

2. In block three only

Back

Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements adds the object to the end of the collection? 1. a[3] = element; 2. a[4] = element; 3. a.add(element); 4. a.add(element, 4);

Front

3. a.add(element);

Back

Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 length + 2 width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following sets of statements are valid (both syntactically and semantically) in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); 1. Only (ii) 2. None of these 3. Only (i) 4. Both (i) and (ii)

Front

Only (i)

Back

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] > a[x]) x = i; System.out.println(x); 1. Sums the elements in a. 2. Finds the position of the smallest value in a. 3. Finds the position of the largest value in a. 4. Counts the elements in a.

Front

3. Finds the position of the largest value in a.

Back

Programmers frequently use the same name for a(n) ____ and an argument to a method simply because it is the "best name" to use. 1. block 2. instance field 3. variable 4. constant

Front

2. instance field

Back

Import the Scanner Class

Front

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

Back

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int z = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is NOT visible in method two? 1. x (variable in main block) 2. w (before method two) 3. rate (before main) 4. one (method name)

Front

x (variable in main block)

Back

Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements replaces the first object in the collection with element? 1. a.set(0, element); 2. a.set(element, 0); 3. a.add(0, element); 4. a[0] = element;

Front

1. a.set(0, element);

Back

Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements adds the object to the beginning of the collection? 1. a[4] = element; 2. a.add(0, element); 3. a.insert(element); 4. a.add(element, 0); 5. a[0] = element;

Front

2. a.add(0, element);

Back

_______________—the specification of attributes and behavior as a single entity—allows us to build on our understanding of the natural world as we create software.

Front

encapsulation

Back

Constructors have the same name as the ____. 1. data members 2. member methods 3. class 4. package

Front

3. class

Back

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the data type of the array above? 1. list 2. num 3. char 4. int

Front

4. int

Back

When you create your own new, user-defined types, there are really three different strategies you can use. Which of these is not one of those strategies? 1. defining a component from scratch, inheriting only the methods in the Object class 2. extending an existing component by adding new features 3. defining a component from scratch, inheriting no methods whatsoever 4. combining simpler components to create a new component

Front

3. defining a component from scratch, inheriting no methods whatsoever

Back

To call a superclass method from a subclass method, when both methods have the same name and signature, prefix the call to the superclass method with: 1. super 2. the name of the superclass (that is, Person, if that is the name of the superclass) 3. no prefix is necessary. You cannot call an overridden superclass method from the subclass method you've overridden. 4. this 5. base

Front

1. super

Back

public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } Which of the following statements would you use to declare a new reference variable of the type Illustrate and instantiate the object with a value of 9 for the variable x? 1. Illustrate.illObject(9); 2. Illustrate illObject = new Illustrate(9); 3. Illustrate illObject(9); 4. illObject = Illustrate(9);

Front

2. Illustrate illObject = new Illustrate(9);

Back

___________________ is one of the primary mechanisms that we use to understand the natural world around us. Starting as infants we begin to recognize the difference between categories like food, toys, pets, and people. As we mature, we learn to divide these general categories or classes into subcategories like siblings and parents, vegetables and dessert. 1. classification 2. encapsulation 3. specialization 4. generalization

Front

1. classification

Back

The toString() method is automatically inherited from the __________________ class. 1. GObject 2. Object 3. java.lang 4. Root 5. Component

Front

2. Object

Back

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int x = 0; for (int e : a) x += a; 1. Sums all the elements in a. 2. Will not compile (syntax error) 3. Finds the largest value in e. 4. Counts each element in a.

Front

2. Will not compile (syntax error)

Back

Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements assigns the last object in the collection to the variable element? 1. element = a[3]; 2. element = a[4]; 3. element = a.get(3); 4. a.get(3, element); 5. a.get(element, e);

Front

3. element = a.get(3);

Back

Section 37

(50 cards)

Use a remainder assignment operator to make c=3 when c=12

Front

c%=9

Back

Natural logarithm of a number?

Front

Math.log()

Back

What is sentinel controlled repetition?

Front

When a loop is controlled by a sentinel value such as s!=3

Back

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

Front

when they're applied to integral operands

Back

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

Front

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

Back

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

Front

&& 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))

Back

How do you set up a switch method?

Front

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

Back

Cosine?

Front

Math.cos(#)

Back

Prints a formatted string

Front

printf

Back

Make g conditional upon some statement

Front

?:g

Back

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

Front

c-=2

Back

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

Front

subclass Superclass

Back

What is a local variable?

Front

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

Back

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

Front

no

Back

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

Front

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

Back

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

Front

c*=4

Back

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

Front

Math.floor(#)

Back

absolute value?

Front

Math.abs(#)

Back

What is the format for a, for, statement?

Front

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

Back

Pi

Front

Math.PI

Back

Make c not equal to b

Front

c!=b

Back

Prints to the current line(single function)

Front

print

Back

What is the sentinel value?

Front

a value to be typed in to stop a loop

Back

Square Root

Front

Math.sqrt

Back

What is program control?

Front

Specifying the order in which statements(actions) execute in a program.

Back

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

Front

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

Back

What is counter controlled repetition?

Front

When a loop is controlled by a counter such as x>3

Back

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

Front

Math.exp(x)

Back

What is the scope of a variable?

Front

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

Back

What does a UML activity diagram do?

Front

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

Back

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

Front

<Ctrl> z <Ctrl> d

Back

Why is the method "main" Declared static?

Front

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

Back

What is control statement stacking?

Front

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

Back

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

Front

c/=2

Back

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

Front

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

Back

Power or Exponent

Front

Math.pow(x,y)

Back

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

Front

adds 1 to c then prints out result. Prefix increment subtracts 1 from c then prints out result. Prefix decrement

Back

Random Number

Front

Math.random()

Back

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

Front

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

Back

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

Front

last

Back

What are the rules for forming a structured program?

Front

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.

Back

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

Front

c += 3

Back

What are the three types of class variables?

Front

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.

Back

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

Front

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

Back

What is the format for a, while, statement?

Front

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

Back

What does the keyword, Extends, do?

Front

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.

Back

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

Front

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

Back

How do you call a method from a class?

Front

ClassName.methodName(arguments)

Back

What is the definition of an algorithm?

Front

A procedure for solving a problem in terms of: The actions to execute and the order in which these actions execute

Back

Prints to a new line and flushes the buffer.

Front

println

Back

Section 38

(50 cards)

Demo

Front

The filename of the source file must be the same as the class name (###case sensitive###) java MyFirstApp (###not MyFirstApp.class###)

Back

What are the three ways to call a method?

Front

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

Back

Bit Permutations

Front

Each additional bit doubles the number of possible permutations Each permutation can represent a particular item N bits can represent up to 2^N unique items, so to represent 50 states, you would need 6 bits: 1 bit: 2^1 = 2 items 2 bits: 2^2 = 4 items 3 bits: 2^3 = 8 items 4 bits: 2^4 = 16 items 5 bits: 2^5 = 32 items Five bits wouldn't be enough, because 2^5 is 32. Six bits would give us 64 permutations, and some wouldn't be used.

Back

What compilation error should you be aware of when using arguments and parameters?

Front

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

Back

Program Development

Front

The mechanics of developing a program include several activities: -writing the program (source code) in a specific programming language (such as Java) using an editor -translating the program (through a compiler or an interpreter) into a form that the computer can execute -investigating and fixing various types of errors that can occur using a debugger Integrated development environments, such as Eclipse, can be used to help with all parts of this process

Back

Java Reserved Words

Front

You cannot use use reserved words for your own names (Java identifiers)

Back

larger value of x and y?

Front

Math.max(x,y)

Back

Java standard class library (Java API)

Front

a set of predefined classes and methods that other programmers have already written for us System, out, println and String are not Java reseved words, they are part of the API

Back

Computer Processing

Front

Back

Java Program Structure

Front

In the Java programming language: -A program is made up of one or more classes defined in source files (with the .java extension) -A class contains one or more methods -A method contains program statements

Back

What Java Can Do

Front

Science and Technology -Popular machine learning libraries are written in Java: Mahout, Weka -Has been adopted in many distributed environments (Hadoop) Web development -Most web backend are developed using Java Mobile application development -Android development platform Graph user interface (GUI) design: menu, windows, ...

Back

Smaller value of x and y?

Front

Math.min(x,y)

Back

Another Example

Front

Output A quote by Abraham Lincoln: Whatever you are, be a good one.

Back

Sine?

Front

Math.sin(#)

Back

Problem Solving

Front

The purpose of writing a program is to solve a problem The key to designing a solution is breaking it down into manageable pieces An object-oriented approach lends itself to this kind of solution decomposition We will dissect our solutions into pieces called classes (.java files) We design separate parts (classes) and then integrate them

Back

How is the filename of a public class formatted?

Front

Filename.java

Back

Binary Numbers

Front

Information is stored in memory in digital form using the binary number system A single binary digit (0 or 1) is called a bit A single bit can represent two possible states, like a light bulb that is either on (1) or off (0) Permutations of bits are used to store values Devices that store and move information are cheaper and more reliable if they have to represent only two states

Back

What must come after a declared class?

Front

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

Back

Object-Oriented Programming

Front

Classes are the building blocks of a Java program; a blueprint for which individual objects can be created Each class is an abstraction of similar objects in the real world E.g., dogs, songs, houses, etc Once a class is established, multiple objects can be created from the same class. Each object is an instance (a concrete entity) of a corresponding class E.g., a particular dog, a particular song, a particular house, etc

Back

Java Program Structure Continued

Front

Back

What does a scanner do for a program?

Front

Enables the program to read data (ints, dbls, char etc.)

Back

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

Front

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

Back

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

Front

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

Back

When naming variables, what is camel case?

Front

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

Back

Tangent?

Front

Math.tan(x)

Back

How Java Works

Front

The compiled bytecode is not the machine language for traditional CPU and is platform-independent javac and java (two command-line tools) can be found in the directory of bin/ of Java Development Kit (JDK) you will install

Back

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

Front

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

Back

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

Front

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

Back

How to Execute Programs

Front

Each type of CPU executes only a particular machine language A program must be translated into machine language before it can be executed Compiler: translates only once Most high-level languages: C, C++, etc. Interpreter: translates every time you run programs Most scripting languages: python, perl, etc. The Java approach is somewhat different. It combines the use of a compiler and an interpreter.

Back

Class=Blueprint

Front

Just like how one blueprint (class) is used to create several similar, but different houses (objects)

Back

When should camel case be used?

Front

When defining the type of an input: int greatNumber, dbl, char etc. When naming a method or class: class( QuadraticFormula), Method(equationProcessor)

Back

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

Front

Stack frames/activation records

Back

What type of structure are stacks usually known as?

Front

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

Back

Basic Program Execution

Front

If there are errors the compiler will complain and not let us go onto the next step. We must trace back to the source and fix the problem in our code. It's important to understand why you're getting errors. LOOK IT UP debuggers can help you find errors in your code

Back

Language Levels

Front

There are four programming language levels. Each type of CPU has its own specific machine language The other levels were created to make it easier for a human being to read and write programs

Back

What does JVM stand for?

Front

Java Virtual Machine

Back

White Space

Front

Spaces, new lines, and tabs are called white space White space is used to separate words and symbols in a program Extra white space is ignored by the computer A valid Java program can be formatted many ways Programs should be formatted to enhance readability, using consistent indentation

Back

Where must all import declarations appear?

Front

Before the first class declaration

Back

Categorize each of the following situations as a compile-time error, run-time error, or logical error.

Front

A. Multiplying two numbers why you mean to add them. logical error B. Dividing by zero run-time error C. Forgetting a semicolon at the end of a programming statement compile-time error D. Spelling a word incorrectly in the output logical error E. Producing inaccurate results logical error F. Typing { when you should have typed a ( compile-time error

Back

Comments

Front

There are two forms of comments, which should be included to explain the purpose of the program and describe processing steps They do not affect how a program works

Back

Logical or semantic errors (Error Type 3/3)

Front

a program may run, but produce incorrect results, perhaps using an incorrect formula

Back

How to Write

Front

Back

Syntax

Front

The rules of a language that define how we can combine symbols, reserved words, and identifiers to make a valid program -Identifiers cannot begin with a digit -Curly braces are used to begin and end classes and methods

Back

Each class declares Instance Variables and Methods (Unique Values for the Objects in the Class)

Front

Instance variables: descriptive characteristics or states of the object Ex. students are an instance variable of a class Methods: behaviors of the object (the actual doing thing of each instance variable) Ex. doing homework or taking exams are the methods of the instance variable "student"

Back

The Main Method

Front

In Java, everything goes in a class (object-oriented) After you compile the source code (.java) into a bytecode or class file (.class), you can run the class using the Java Virtual Machine (JVM) When the JVM loads the class file, it starts looking for a special method called main, and then keeps running until the code in main is finished

Back

Run-time errors (Error Type 2/3)

Front

a problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally

Back

Semantics

Front

The semantics of a program statement define what that statement means (its purpose or role in a program) A program that is syntactically correct is not necessarily logically (semantically) correct A program will always do what we tell it to do, not what we meant to tell it to do

Back

Who will do the Java compiling?

Front

Javac is the complier, not Eclipse. Eclipse is the software that runs javac. The Java virtual machine (the executable response) is called java For one class... what is the mechanism that allows us to run it? Answer: we are using an existing object

Back

Compile-time or syntax errors (Error Type 1/3)

Front

the compiler will find syntax errors and other basic problems

Back

Java Identifiers

Front

Identifiers are the "words" in a program -Name of a class: Dog, MyFirstApp, and Lincoln -Name of a method: bark and main -Name of a variable: args (later in this course) Rules: A Java identifier can be made up of -letters -digits (cannot begin with a digit) -the underscore character ( _ ), -the dollar sign ($) Java is case sensitive: -Total, total, and TOTAL are different identifiers By convention, programmers use different case styles for different types of identifiers, such as title case for simple class names - Lincoln camel case for compound words - MyFirstApp upper case for constant variables - MAXIMUM

Back

Section 39

(50 cards)

Expressions

Front

Order of operations is applied: Multiplication, division, and remainder are evaluated before addition, subtraction, and string concatenation Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order Assignment operator is last

Back

String Concatenation

Front

The string concatenation operator (the plus symbol) is used to append one string to the end of another. In the case of a long string, you must use concatenation to break it across multiple lines.

Back

Numeric Primitive Types

Front

Back

Data Conversion

Front

Sometimes it is convenient to covert 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 convert a value as part of a computation 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) In Java, data conversions can occur in three ways: -assignment conversion -promotion -casting

Back

Packages

Front

For purposes of accessing them, classes in the Java API are grouped into packages

Back

Casting Conversion

Front

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

Back

Dog Example

Front

Will see the syntax of creating objects (with unique instance variables) and then calling methods from the class later The computer will read this and decide which bark to use Just think of it like you name something (object) and give it variables and then it takes the information and outputs something (method)

Back

New

Front

new is a Java reserved word that triggers all kinds of actions. goes back to the heap (free memory space), reserves a chunk of the memory for the real value (address) Java actually invokes a special method called constructor, provided by programmer, which does the proper initialization new is the only thing that produces a reference type

Back

Constant

Front

A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence As the name implies, it is constant and cannot be changed The compiler will issue an error if you try to change the value of a constant In Java, we use the final modifier to declare a constant final int NUM_SEASONS = 4; whenever you use the reference variable, NUM_SEASONS, it will equal 4 Constants are useful for three important reasons First, they give meaning to otherwise unclear literal values Example: MAX_LOAD means more than the literal 250 Second, they facilitate program maintenance If a constant is used in multiple places, its value need only be set in one place Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers

Back

The + Operator

Front

The + operator is also used for arithmetic addition The function that it performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation If both operands are numeric, then it adds them The + operator is evaluated left to right, but parentheses can be used to force the order If both of its operands are strings, or if one is a string and one is a number, it performs string concatenation. But if both operands are numeric, it performs addition.

Back

The string class

Front

Every character string (enclosed in double quotation characters) is an object in Java defined by the String class Every character string can be used to create a string object Because strings are so common, we don't have to use the new operator to create a String object (special syntax that works only for strings) String name1 = "Steve Jobs"; It is equivalent to String name1 = new String("Steve Jobs");

Back

Java Class Libraries

Front

A class library is a collection of classes to facilitate programmers when developing programs The Java standard class library is part of any Java development environment (available after installing JDK) The Java standard class library is sometimes referred to as the Java API (Application Programming Interface) Its classes are not part of the Java language per se, but we rely heavily on them Various classes we've already used (System, String) are part of the Java API

Back

Creating Objects: Reference Variable

Front

Dog is the data type. That's what reference allows us to do. It makes it user friendly by letting us make our own data types. We tell the computer to set aside a chunk of space for the data type, Dog. The size of the chunk will be big enough to hold an address, because reference is indirect. No actual amount will go in like with primitive datatypes where we know the amount of storage being used. It will just leave space (a placeholder)

Back

More About System.out

Front

The System.out object represents a destination (the monitor screen) to which we can send an output The System.out object provides another service in addition to println The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line

Back

Example of the Dot Operator in Use

Front

System.out.println revisited There is a class called System, which contains an object reference variable out as one of its instance variables The object referenced by out has a method called println

Back

Example of setting a reference to null

Front

Back

Charachter Strings

Front

A string literal is represented by putting double quotes around the text examples: "I Rule!" "The World" "123 Main Street" "X" "" literal is an explicit data (constant) value used in a program Every character string is an object in Java, defined by the String class Every string literal represents a String object A string literal can contain any valid characters, including numeric digits, punctuation, and other special characters.

Back

Example of Declaring a Variable and then changing it with the assignment operator

Front

Back

Scanner Class

Front

It is often useful to design interactive programs that read input data from the user The Scanner class provides convenient methods for reading input values of various types A scanner object can be set up to read input values from various sources including the user typing values on the keyboard The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner(System.in); Once created, the Scanner object can be used to invoke various input methods, such as: String answer = scan.nextLine(); The nextLine method reads all of the input until the end of the line is found, and return it as one String

Back

Creating objects

Front

How to create objects once a class is established? How to "hold" those created objects? For primitive types (such as byte, int, double), we use a variable of that particular type as a cup to store its actual value BUT Objects are different There is actually no such thing as an object variable, because we can't put a number on it. There is only an object reference variable An object reference variable holds something like a pointer or an address that represents a way to get to the object. When you copy a string object, you're really copying it's address.

Back

Garbage Collection

Front

When an object no longer has valid references to it, it can no longer be accessed by the program The object is useless and therefore is called garbage Java performs automatic garbage collection periodically, returning and object's memory to the system for use In other languages the programmer is responsible for performing garbage collection

Back

Three step of object declaration, creation and assignment

Front

Back

Reference Assignment

Front

Once a String object has been created, neither its value nor its length can be changed (it's immutable) However, its reference variables can change

Back

String mutation example to put into Java

Front

Even though we can't change String value or length, several methods of the String class return new String objects that are modified versions of the original

Back

Increment and Decrement

Front

Write four different program statements that increment the value of an integer variable total. Count ++ Count = Count + 1 Count = ++ Count Count += 1

Back

Classes contain methods that determine the behaviors of objects

Front

Two common usages of methods: -change the values of the instance variables, e.g., making deposits to a bank account object should change its current balance -methods can behave differently based on the values of the instance variables, e.g., playing a "Darkstar" song object and a "My Way" song object should be somehow different...

Back

What output is produced by the following?

Front

X: 25 Y: 65 Z: 30050

Back

Some String Methods

Front

String name1 = new String("Steve Jobs"); int numChars = name1.length(); char c = name1.charAt(2); String name2 = name1.replace('e', 'x'); String name3 = name1.substring(1, 7); String name5 = name1.toLowerCase();

Back

Example of three references and two object

Front

d and c are aliases, because they both reference the same book

Back

What are the results of the following expressions?

Front

Back

numChars = name1.length();

Front

// returns the number of characters name1 contains

Back

Charachters

Front

A char variable stores a single character (16 bits) Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '
' Example of declarations with initialization: char topGrade = 'A'; char terminator = ';', separator = ' '; Note the difference between a primitive character variable, which holds only one character (enclosed by single quotes), and a String object, which can hold multiple characters (enclosed by double quotes)

Back

Promotion Conversion

Front

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

Back

Boolean

Front

A boolean value represents a true or false condition (1 bit) The reserved words true and false are the only valid values for a boolean type boolean done = false; A boolean variable are usually used to indicate whether a particular condition is true, such as whether the size of a dog is greater than 60

Back

The Import Statement

Front

Why didn't we import the System or String classes explicitly in earlier programs? All classes of the java.lang package are imported automatically into all programs It's as if all programs contain the following line: import java.lang.*; The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported

Back

The right and left hand sides of an assignment statement can contain the same variable

Front

Back

Example of two references and two objects

Front

Back

Declaration with Initialization

Front

An assignment statement changes the value of a variable The assignment operator is the = sign If you wrote keys = 80; The 88 would be overwritten You should assign a value to a variable that is consistent with the variable's declared type

Back

Inheritance

Front

One class can be used to derive another via inheritance Classes can be organized into hierarchies

Back

Variables

Front

A variable is a name for a location (a chunk) in memory that holds a value (a fixed type of data) Variables come in two flavors: primitive and reference primitive: integer (such as 1, 2,...), floating point number (such as 1.2, 3.5, etc.), boolean (true or false) and char (such as 'A', 'B',...) reference: "address" of an object that resides in memory A variable declaration specifies the variable's name and the type of information that it will hold

Back

Objects and the Heap

Front

The number of objects that a program creates is not known until the program is actually executed Java uses a memory area called the heap to handle this situation, which is a dynamic pool of memory on which objects that are created are stored When an object is created, it is placed in the heap -Two or more references that refer to the same object are called aliases of each other -One object can be accessed using multiple reference variables -Changing an object through one reference changes it for all of its aliases, because there is really only one object

Back

Primitive Types

Front

There are eight Primitive data types in Java Four of them represent integers • byte, short, int, long Two of them represent floating point numbers • float, double One of them represents a single character • char And one of them represents boolean values • boolean

Back

String Indexes

Front

It is occasionally helpful to refer to a particular character within a string This can be done by specifying the character's numeric index The index begins at zero in each string In the string "Hello" H is at the index 0 and o is at the index 4

Back

String mutation example Output

Front

Back

The Dot Operator

Front

The dot operator (.) gives you access to an object's instance variables (states) and methods (behaviors) It says: use the Dog object referenced by the variable myDog to invoke the bark() method Think of a Dog reference variable as a Dog remote control When you use the dot operator on an object reference variable, it is like pressing a button on the remote control for that object

Back

Assignment Conversion

Front

Assignment conversion occurs when a value of one type is assigned to a variable of another Only widening conversions can happen via assignment

Back

Quick Check: Who am I?

Front

Back

Escape Sequence

Front

What if we wanted to print the quote character? The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\) System.out.println ("I said \"Hello\" to you.");

Back

Assignment Operators

Front

Often we perform an operation on a variable, and then store the result back into that variable Java provides assignment operators to simplify that process For example, the statement num += count; is equivalent to num = num + count; Other assignment operators: -=, *=, /=, %=

Back

Division and Remainder

Front

Back

Section 40

(47 cards)

Boolean Expressions

Front

A boolean expression often uses one of Java's equality operators or relational operators, which all return boolean results: Note the difference between the equality operator (==) and the assignment operator (=)

Back

field

Front

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

Back

signature

Front

Combination of identifiers, return value, name and parameters of a method. Example: public int calculateMonth(String name)

Back

Nested Statement Example

Front

Back

Quick Check: The Random Class

Front

Given a Random object reference named gen, what range of values are produced by the following expression?

Back

Guessing Game Example Continued

Front

Back

instance

Front

An object.

Back

Specific Boolean expressions can be evaluated using truth tables

Front

Back

The if Statement

Front

The if statement has the following syntax: if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression (must evaluate to either true or false) If the condition is true, the statement is executed. If it is false, the statement is skipped. An if statement with its boolean condition: if (total == sum) system.out.println("total equals sum"); Another if statement with its boolean condition: if (total != sum) system.out.println("total does NOT equals sum");

Back

Guessing Game Example

Front

Back

declare and initialize string variables

Front

String itemToCheck; itemToCheck = "";

Back

Nested Statement Example Continued

Front

Back

Block Statements

Front

Several statements can be grouped together into a block statement delimited by braces A block statement can be used wherever a statement is called for in the Java syntax rules The if clause, or the else clause, or both, could be governed by block statements

Back

parameter

Front

Variable passed to a method that provides more information for the method.

Back

type

Front

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

Back

The Random Class

Front

The Random class is part of the java.util package It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values nextFloat() generates a random number [0, 1) nextInt() generates a random integer over all possible int values (positive or negative) nextInt(n) generates a random integer [0, n-1]

Back

multiple instances

Front

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

Back

while

Front

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

Back

declare a class

Front

Public Class MemorizeThis {

Back

jump

Front

up and down

Back

Logical NOT

Front

The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then !a is false; if a is false, then !a is true Logical expressions can be shown using a truth table. A truth table shows all possible true-false combinations of the terms.

Back

if else structure

Front

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

Back

method

Front

Specifies the actions of an object.

Back

concatenate and output

Front

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

Back

Quick Check: Nested Statements

Front

What output is produce by the following code fragment given the assumptions below?

Back

Quick Check: Booelan Expressions

Front

Given the following declarations, what is the value of each of the listed boolean conditions?

Back

class

Front

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

Back

Math Class Sample Output

Front

Back

Nested if Statements

Front

We can put an if-else statement as part of another if statement, these are called nested if statements if ( condition1 ) if ( condition2 ) statement1; else statement2; An else clause is always matched to the last unmatched if (no matter what the indentation implies) Braces can be used to specify the if statement to which an else clause belongs Both if statements must be true for statement 1 to be printed

Back

Another way to generate a Random Number

Front

There is another way to generate a random double number [0,1) double newRand = Math.random(); as opposed to import java.util.Random; Random generator = new Random(); float newRand = generator.nextFloat();

Back

Expressions that use logical operators can form complex conditions

Front

Max +5, then less than sign, then the logical not and logical & operators Think of it like true always wins

Back

Logical AND and Logical OR

Front

Since && and || each have two operands, there are four possible combinations of conditions a and b

Back

Conditional Statements

Front

The order of statement execution is called the flow of control A conditional statement lets us choose which statement will be executed next The Java conditional statements are the: -if and if-else statement -switch statement

Back

Logical Operators

Front

They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands)

Back

If Statement Example

Front

Back

The if-else Statement

Front

An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both

Back

The Math Class

Front

The Math class is part of the java.lang package The Math class contains methods that perform various mathematical functions These include: absolute value square root exponentiation trigonometric functions The methods of the Math class are static methods (also called class methods) Static methods never use instance variable values Math class does not have any instance variables Nothing to be gained by making an object of Math class Static methods are invoked through the class name - no object of the Math class is needed value = Math.abs(90) + Math.sqrt(100);

Back

return value

Front

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.

Back

Input Tokens

Front

Unless specified otherwise, white space is used to separate the tokens (elements) of the input White space includes space characters, tabs, new line characters The next method of the Scanner class reads the next input token and returns it as a string Methods such as nextInt and nextDouble read data of particular types (int and double)

Back

set input variables

Front

thisEnter = myScanner.next.Int();

Back

declared scanner class

Front

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

Back

object

Front

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

Back

Summary of the Four Classes we Have Learned so Far

Front

Back

declare and initialize primitive variables

Front

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

Back

state

Front

The values of all of the variables in an object at a given time.

Back

If Statement Example Continued

Front

Back

set up main method

Front

Public static void main (string[], args) {

Back