JAVA FINAL 13

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Name 3 reasons why favor composition over inheritance

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

Method

A program unit that represents a particular action or computation. The next-smallest unit of code in Java, after classes. They represent a single action or calculation to be performed. Several methods can be defined with in a class.

Object

A programming entity that contains data and methods

An object is this type of variable

A reference variable

Import Declaration

A request to access a specific Java package

Declaration

A request to set aside a new variable with a given name and type

Exception

A runtime error that prevents a program from being executed.

Decomposition

A separation into discernible parts, each of which is simpler than the whole.

Expression

A sequence of One or more identifiers and operator that evaluate a value.

Computer program:

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

What is the value for the variable sum? int[][] sampleArray = new int[3][4]; for (int i = 0; i < 3; i++) { sampleArray[i][i+1] = 2; } int sum = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { sum += sampleArray[i][j]; } }

4

int

4 bytes, stores integer values

float

4 bytes, stores less precise floating-point numbers

long

4 bytes, stores long integer values

What is a 'set' in Java?

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

What's a list in Java?

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

True

A left brace in a Java program is always followed by a right brace later in the program

statements

A line of java code.

String

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

Program

A list of instructions to be carried out by a computer

Program

A list of instructions to be carried out by a computer. Also called software.

Variable

A location in memory used to hold a data value.

Infinite Loop

A loop that never terminates

java.io.Serializable is a marker interface, also known as a tag interface. What is the unique attribute of marker interfaces?

A marker interface includes no methods or fields.

Class

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

Named constant:

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

Variable:

A memory location whose content may change during program execution.

Variable

A memory location with a name and a type that stores a value

b()

A method called b

Constructor

A method that has the same name as the class, but it does not have a return value specified. A constructor builds the object or class structure in memory.

Megabyte

A million Bytes. Can store large pictures.

What's a method?

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

Identifier

A name given to an entity in a program (must start with a letter, and can include _ and $)

Identifier

A name given to an entity in a program, such as a class or method. Identifiers must start with a letter, underscore, or $. illegal identifiers two+two, hi there hi-there 2by4

Class Constant

A named value that cannot be changed, and its scope extends to the entire class

Binary Number

A number composed of 0s and 1s, also known as base-2 number.

Relative Path

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

Programming:

A process of planning and creating a program.

applet

A program that appears in a window, often intended to be embedded in a HTML document.

Platform Independent

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

Java Runtime

A program that executes compiled Java bytecodes.

Application

A program that runs locally, on your own computer.

Applet

A program that runs on a web page.

Compiler

A program that translate a computer program written in one language to another language (from high-level to machine language)

Compiler

A program that translates a computer program written in one language into an equivalent program in another language (often, but not always, translating form a high-level language into machine language).

Method

A program unit that represents a particular action

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

Methods

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

Methods && Instance Variables

Punctuation Error Examples

Missing Curly Braces Missing Semi Colons Malformed Comments

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

Mixing Data Types Rules

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

Mixing Data Types Rules

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

Mixing Data Types Rules

%

Modulo(Mod)- Remainder after Integer division.

Can the access specifier for an overriding method allow more or less access than the overridden method?

More. The access specifier for an overriding method can allow more, but not less, access than the overridden method.

switch....case use-age

Multi-coniditional branching. Used instead of the 'if' statement when a large number of outcomes need to be tested. Each case contains code that is executed if the switch argument takes on a particular value.

...

Multi-dimensional arrays can be initialized by placing the values that will populate the array in curly brackets. Each dimension is represented by a nested set of curly brackets. Example: int[ ][ ][ ] threeDArray = {{{1,2}, {3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}

...

Multi-dimensional arrays can declared with the new operator by placing the size of each dimension in square brackets. Example: int[ ][ ][ ] threeDArray = new int[3][2][2]

...

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

...

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

*

Multiplication operator

*=

Multiply and assign operator

identifier

Name of a variable, parameter, constant, user-defined method, or user-defined class.

Identifiers

Names of Variables. They are case sensitive. They can use digits 0-9,$, and underscore. Cannot start with a digit. Cannot contain spaces or other characters. Cannot use JAVA Keywords.

Will this line compile without errors? double[ ][ ][ ] numbers = new double[ ][ ][ ];

No. When the new operator is used, at least one array dimension in a multi-dimensional array must be given a size.

Can a constructor have a synchronized modifier?

No; they can never be synchronized.

Will this line compile without errors? Object [ ] obj = new Object [3]();

Incorrect because the () after the [] is not the correct syntax.

Will this line compile without errors? Object obj [ ] = new Object [3]();

Incorrect because the () after the [] is not the correct syntax.

Will this line compile without errors? Object obj [] = new {new Object(), new Object()};

Incorrect because the first new operator is being used with the {} initialization method.

Will this line compile without errors? Object [3] obj = new Object [3]() ;

Incorrect because the size is in the declaration and the extra () after the [] is not the correct syntax.

Will this line compile without errors? Object [7] obj = new Object [7];

Incorrect because the size is not assigned when it is declared.

Will this line compile without errors? Object [8] obj = new Object [ ];

Incorrect because the size is not assigned when it is declared.

Will this line compile without errors? Object [ ] obj = new Object [ ];

Incorrect because they do not assign a size to the array.

Will this line compile without errors? Object obj [ ] = new Object[ ] ;

Incorrect because they do not assign a size to the array.

Will this line compile without errors? Object [ ] obj = new Object ();

Incorrect because they have () instead of [] after the type.

Will this line compile without errors? Object obj [ ] = new Object() ;

Incorrect because they have () instead of [] after the type.

++

Increment by one

< >

Indicates that something needs to be filled in. For example,public class <name> means that a name for the class needs to be filled in.

Source

Information in it's original form.

Escape Sequence

A sequence used to represent special characters.

Pseudocode

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

Operator

A symbol expressing a way to modify a value or values. Ex (+,=, etc.).

Class

A template of an object. Objects are instantiated from a class.

Kilobyte

A thousand bytes. Can store pages of text.

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

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

appletviewer

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

Event-Driven Programing

An event occurs whenever an event listener detects an event trigger and responds by running a method called an event handler.

Statement

An executable snippet of code that represents a complete command

Statement

An executable snippet of code that represents a complete command. Each statement is terminated by a semicolon.

Mixed expression:

An expression that has operands of different data types.

Constants

An identifier that is initialized to a value that cannot change. Usually declared at top of program using keyword final. final int MAXHT=100;

Reference Variable

An identifier that represents a location in memory which itself has a *reference* to another location in memory where an object resides. Multiple reference variables can reference the same object and so affect its reference count. An object with no references can be garbage collected.

variable

An identifier that represents a location in memory.

Object

An instance of a class.

Statement

An instruction you give a computer.

Element

An item in an Array.

Attributes and Behaviors

An object contains these two things.

Cumulative Algorithm

An operation in which the total is acquired incrementally using a loop

New operator

An operator that constructs new objects

Unary operator:

An operator that has only one operand.

Binary operator:

An operator that has two operands.

Chaining

An undesirable design in which a "chain" of several methods call each other without returning the overall flow of control to main.

Coupling

An undesirable state in which two methods or processes rigidly depend on each other.

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

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

=

Assignment

=

Assignment Operator

Name 9 primitive types

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

Digital

Based on numbers that increase in discrete increments, such as the integers 0, 1, 2, 3, etc.

Byte

Basic Unit of storage. Can store one letter of the alphabet or Keyboard. (1 byte is 8 bits -256 combinations).

Naming Methods?

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

&

Bitwise And operator

~

Bitwise Not operator

|

Bitwise Or operator

Scope

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

main()

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

while(true) { }

Block that can only be exited using break.

==

Boolean equals

Boolean logic

Boolean logic is a form of mathematics in which the only values used are true and false. Boolean logic is the basis of all modern computing. There are three basic operations in Boolean logic - AND, OR, and NOT.

!

Boolean not

!=

Boolean not equal to

&&

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

||

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

Engaging in OOP

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

Does Java support multiple inheritance?

C++ allows an object to inherit from multiple classes. Java does not. However, Java does permit an object to implement multiple interfaces and inherit from a superclass, providing a limited form of multiple inheritance.

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

Calls the default constructor on the Printer class.

Arithmetic Operators

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

Strings and escape sequences

Can be included in a string as if they were another character using the backslash \. E.g. "\"This is a string\"" uses \" to include double quotation marks as characters in the sequence.

switch default case

Can be included to perform some processing if none of the other cases in the switch statement are selected, such as throwing an exception. It isn't a requirement but is good style.

System.out.print();

Can be used to produce output on the same line

Primitive Variables

Can store data values.

String

Can use +, ., and +=

Reference Variables

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

to convert data type

Casting

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

Casting Rules

Autoboxing

Casts a simple variable value to the corresponding class.

Unboxing

Casts an object to the corresponding simple value.

switch break

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

Conversion

Changing one type of primitive data to another.

Work with Java Arrays

Chapter 6 Objective 1

char

Character

What are the TWO types of data contained by classes?

Characteristics and Behavior

Relational Operators

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

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

Class

Class

Class is a type of object

RuntimeException

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

What are the access levels in order of most restrictive to least?

Class, Package, Sub class, and World.

Object Construction

ClassName objectName = new ClassName(parameters);

Static method call

ClassName.methodName(parameters);

final or user-defined constant

Constant, cannot be changed.

Which access modifiers can be applied to constructors?

Constructors can have package-private, private, protected, and public access modifiers applied to them.

Interpretation

Converting a source code into common language (.class file)

Casting

Converting information from one form to another.

Compiler

Converts Source Code into an Object File or Machine Code. Detects Syntax Errors.

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

Define the keyword "public"

Method that returns.

Define the keyword "return"

Does not change. Cannot make an instance of.

Define the keyword "static"

Method that does not return.

Define the keyword "void"

{}

Defines a block of code

Code Block

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

Primitive Data Types

Eight commonly used data types.

matrix.length pixels.length

Example of getting the number of rows

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

Example of setting the value of elements

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

Example: Accessing two elements

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

Example: get the number of columns

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

Examples of 2D array declarations

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

Examples of creation of 2D arrays

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

Exception

Demarcation and indentation

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

Applet

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

Relational Operators and Floating Points

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

Selection Statements

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

What is a main method for?

For letting your program run.

for( insert argument here) { insert code here }

For loop

Three types of Loops

For, While, and Do-While.

Syntax error

Forgetting a semicolon or brace

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

Format flags (printf)

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

Format types (printf)

Dialog Box

GUI object resembling a window on which messages can placed

Windowed Application

GUI with elements such as menus, toolbars, and dialog boxes

name[0].length

Get the number of columns

name.length

Get the number of rows

GUI

Graphical User Interfaces A GUI has icons on the computer screen and a mouse (or other device) to control a pointer that can be used to operate the computer.

>

Greater than

>=

Greater than or equal to

boolean expression

Is a selection control structure that introduces a decision-making ability into a program, TRUE or FALSE

Program

Is a solving tool

Index

Is an integer that describes the location of a value in a complete sequence; starts with (0)

Iteration

Is another name for looping. An iterative method contains a loop.

What is the keyword transient?

It marks a member variable not to be serialized when it is persisted to streams of bytes.

curly brackets and ;

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

What is a primitive type in Java?

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

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

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

Methods

In object-oriented programming, the programs that manipulate the properties of an object are the object's method

What's the purpose of the Finally Block

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

find the min

Math.min (x, y);

x^y

Math.pow (x, y);

random number between 0 and n

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

random number between 0 and 1

Math.random();

sin x

Math.sin(x);

square root of a

Math.sqrt (a);

radians to degrees

Math.toDegrees();

degrees to radians

Math.toRadians();

Debugger

May be able to find Semantic/logic Errors. Used when error is detected.

Abstraction

Meaning we do not need to know the implementation details in order to use them

void

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

public

Method declaration. It means that method can be called from anywhere. Any thing declared as public can be accessed from anywhere.

static

Method declaration. You don't have to create instance of the class if it is in main method

Static methods

Method not associated with any object

Mutator

Method that alters the attributes of an object.

toUpperCase

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

BufferedReader

io class for buffering reads

InputStreamReader

io class for reading input stream

K&R Style

is the indent style in which the opening brace follows the header line

literals

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

Literals

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

-es

java switch to run a program with assertions active

Character strings are represented by the class ___.

java.lang.String

CH13: The ListSelectionListener interface is in this package.

javax.swing.event

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

just invoking 'aMethod()'.

Keyboard integer input

keyboard.nextInt();

Object-Oriented Programs

language involving creating classes, and objects from those classes, and creating applications that use those objects

A thread can be created in two ways:

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

-8 bits Range: -128 to 127 No rules

byte

What are the eight primitive data types supported by the Java programming language?

byte short long float double int char boolean

CH12: This is an internal list of all the methods that are currently executing.

call stack

default modifier

can be accessed only to classes in the same package

Architecturally Neutral

can be used to write a program that runs on any platform

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

cannot be accessed.

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

catch clause

/b

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

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

char

Alphabetic characters that can be stored as a numeric value?

char

CH11: A method in a subclass that has the same signature as a method in the superclass is an example of _______.

Overriding

Logic.Semantic/Run-Time Errors

Program Complies, but Doesn't Produce the Expected Results

Code

Program fragments

Testers

Programmers hand Program to these code breakers.

Objects

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

CH11: These superclass members are accessible to subclasses and classes in the package.

Protected

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

Runtime error

Differences in String

S is Capitalized. Type of Object.

Type of errors

SYNTAX ERRORS - Violations of the programming language rules. LOGIC ERRORS - Also called run-time or execution errors. They are errors in the sequence of the instructions in the program.

Initialize scanner

Scanner keyboard= new Scanner (System.in);

;

Semicolon

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

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

Data Type 'String'

Sequence of characters, a reference data type.

Test Plan

Series of tests (ex. inputs) that have predetermined expected outputs. Program should be tested several times with different inputs, and under all potential conditions.

Java vocabulary

Set of all words and symbols in the language

name [row] [col] = value

Set the value of an element

Instance variables

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

Operators

Sets of which are associated with primitive datatypes, can be either unary or binary, depending on whether they require one variable or two (operands). E.g. addition, multiplication or increment.

long totalMilliseconds = System.currentTimeMillis();

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

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

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

....

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

...

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}

...

Standard Java arrays can be initialized with the new operator and their size in square brackets after the type. Example: int[ ] myArray = new int[4]

How many dimensions can standard Java arrays have?

Standard Java arrays can have one or many dimensions.

What can standard Java arrays store?

Standard Java arrays can store both objects and primitives.

What is missing from the following multi-dimensional array declaration: int[][] array = int[10][10];

The new keyword is needed to establish memory allocation.

What methods would a class that implements the java.lang.CharSequence interface have to implement?

char charAt(int index) Returns the char value at the specified index. int length() Returns the length of this character sequence. CharSequence subSequence(int start, int end) Returns a new CharSequence that is a subsequence of this sequence. String toString() Returns a string containing the characters in this sequence in the same order as this sequence.

\

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

Console Applications

character output to a computer screen in a DOS window

Escape Sequence

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

CH12: All exceptions that do NOT inherit from the Error class or the RuntimeException class are ________.

checked exceptions

in.hasNextDouble()

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

Machine Language

ciruitry-level languag written in a series of off and on switches, The language made up of binary-coded instructions that is used directly by the computer.

A blueprint for a software object is called a...

class

How do you start a program?

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

Naming standard for accessor method?

getABC();

CH12: This is a section of code that gracefully responds to exceptions.

exception handler

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

exceptions

while (s.equals("v")) { }

execute block while string s equals value v

Logic

executing the various statements and procedures in the correct order to produce the desired results

Instance

existing object of a class

break

exit block

Comments

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

Mixed-mode arithmetic

expressions imvolving integers and floating-point values

CH11: This key word indicates that a class inherits from another class.

extends

Where is a software object's state contained?

fields (Java) or variables (C++)

Constant definition

final typeName variableName = expression;

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

finally{ }

CH12: This method can be used to retrieve the error message from an exception object.

getMessage

CH13: This JList method returns -1 if no item in the list is selected.

getSelectedIndex

accessor

gets a property

array.length

gives the length of the array (no parentheses!)

Lexical elements

groups of characters used in program code

public static double cubeVolume (double sideLength)

header for method

/t

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

In the following program, explain why the value "6" is printed twice in a row: class PrePostDemo { public static void main(String[] args){ int i = 3; i++; System.out.println(i); // "4" ++i; System.out.println(i); // "5" System.out.println(++i); // "6" System.out.println(i++); // "6" System.out.println(i); // "7" } }

i++ is a postfix operator. 1 will be added to 1 after it's printed. ++i is a prefix operator. If it had been used, the println would have been "7"

instance variables

identifiers used to descibe the attributes of an object.

if (cond) { } else { }

if "cond" blocks syntax

How do you make if...else statements?

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

The if Statement

if (condition) statement; else statement;

if statement (many commands)

if (true) { }

if / else

if (true) { } else { }

Explain the following code sample: result = someCondition ? value1 : value2;

if someCondition is true then assign value1 to result else if someCondition is false then assign value2 to result

if (condition) { statements1 } else { statements2 }

if statement (else not required in all cases)

The most basic control flow statement supported by the Java programming language is the ___ statement.

if then

String

immutable character holder

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

implement all of its 'abstract' methods.

The first non-abstract (concrete) class to extend an 'abstract' class must ...

implement all the 'abstract' class' 'abstract' methods.

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

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

'abstract' methods must be ...

implemented by a subclass, so they must be inheritable.

Interfaces can be ...

implemented by any class, from any inheritance tree.

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

implemented.

declare and initial int array, number, with length N

int[] number = new int [N];

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

int[] numbers = new int[3];

A collection of methods with no implementation is called an ___.

interface

is interface a slass

interface is not a class

Iterative enhancement

The process of producing a program in stages, adding new functionality at each stage. A key feature of each iterative step is that you can test it to make sure that piece works before moving on.

"protected" modifier

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

Operator Precedence

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

Token:

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

countryName = countryName.trim();

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

Which method of the Stringbuilder class attempts to reduce storage used for the character sequence?

The trimToSize method attempts to reduce storage used for the character sequence.

State

The values stored in an object's properties at any one time form the state of an object.

update statement

The way the index of a loop changes value.

Class Statement

The way you give your computer program a name.

Boolean Literal

The words true and false.

Programmer - defined names

There are words or names that are used to identify storage locations in memory and parts of the program that are created by the programmer.

Is the following interface valid? public interface Marker { }

There is no requirement to contain constants or method signatures. Empty interfaces can be used as types and to mark classes without requiring any particular method implementations. For an example of a useful empty interface, see java.io.Serializable.

Is this valid? short s = 1000s;

There is no s postfix.

The following code creates one array and one string object. How many references to those objects exist after the code executes? Is either object eligible for garbage collection? ... String[] students = new String[10]; String studentName = "Peter Parker"; students[0] = studentName; studentName = null; ...

There is one reference to the students array and that array has one reference to the string Peter Smith. Neither object is eligible for garbage collection.

Operators

These are symbols or words that perform operations on one or more operands.

Syntax

These are the rules that must be followed when writing a program.

Key words

These are words that have a special meaning in the programming language

{}

These characters are used in Java to group together related bits of code. They could be used to group groups within groups just like parenthesis.

/**

These characters mark the beginning of a documentation comment

/*

These characters mark the beginning of a multi - line comment

//

These characters mark the beginning of a single - line comment

Punctuation

These characters serve specific purposes, such as marking the beginning or ending of a statement, or separating items in a list.

Keywords

These have a special meaning in the program and cannot be used in other ways (eg class, if, while)

Syntax errors

They are the equivalent of bad grammar and are caught by the compiler.

What are variables?

Things that store information.

Error

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

Loop

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

Exception

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

primitive data types

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

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

float

How do you write an infinite loop using the for statement?

for ( ; ; ) { //do something }

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

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

The "for each" loop

for (Type variable: collection) statement;

The for Statement

for (initialization; condition; update) statement;

for loop (use i and N)

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

How do you make loops?

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

Loop count to 10

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

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

fun ny

ReadLine()

function to get a line from InputStreamReader object

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

funny

flag

This is a boolean variable that signals when soem conditions exists in the program

Variable

This is a named storage location in the computer's memory.

null statement

This is an empty statement that does nothing

nested if statement

This is an if statement that appears inside another if statement

new

This key word creates an object

Final

This key word is used to declare a named constant

Do While Execution

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

CPU

This part of the computer fetches instructions, carries out the operations commanded by the instructions, and produces some outcome or resultant information.

boolean expression

This type of expression has a value of either true or false

Secondary storage

This type of memory can hold data for long periods of time - even when there is no power to the computer

Cast

This type of operator let's you manually convert a value, even if it means that a narrowing conversion will take place

Applet

This type of program is designed to be transmitted over the internet and run in a web browser

If a variable is cast to an invalid object, what is the effect?

This will cause a runtime exception to be thrown.

If you delete the order and do not bill the customer, but still fail to return the items to the available inventory, your code fails to ensure transaction integrity.

True

s.substring(b,e);

get sub string from s starting at position b ending at position e

Layout managers automate the positioning of the components within containers.

True

Locks are the Java concept for flag maintained by the operating system.

True

SQL should be contained in the persistence layer, shown in the figure.

True

Stopping an active thread asynchronously from the outside, by calling stop or suspend, releases all locks without giving the thread an opportunity to complete potentially critical operations.

True

Swing components separate the manipulation of data associated with a component from the rendering or graphical-representation component and its contents.

True

Swing uses a separable model architecture.

True

Swing-bases applications extents the javax.swing.JFrame class.

True

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

True

The Drag and Drop API provides the ability to move data between programs created with the Java programming language.

True

The JVM is in charge of scheduling processor time according to the priorities assigned to the threads.

True

The PreparedStatement interface extends Statement.

True

The currentThread is the static method of the Thread class

True

The join method of the Thread class waits for the thread object to terminate.

True

The method setDefaultCloseOperation is a member of the JFrame class.

True

The method that issues an INSERT statement returns an integer value that indicates the number of row affected.

True

The paint and update methods provide a Graphic object as an argument of the method.

True

The properties of transactional integrity have been formalized and are known as the ACID properties.

True

The setColor method sets the color used for subsequent drawing and fill coloring.

True

The sleep method of the Thread class makes the thread pause for the specified number of milliseconds.

True

Thread-safe variables belong to one thread alone; different threads have separate copies.

True

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

True

True or False, octal literals must start with a 0.

True

When a Thread object is constructed with a Runnable object as input, the Thread object uses the run method of the Runnable object

True

You create handlers for user-initiated events by defining classes that implement the listener interfaces.

True

Your threds can launch other threads.

True

only the Model layer, shown in the figure, operates on persistent data.

True

reserved words or keywords

Words used by java that have a special meaning. They cannot be used as variable names.

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

Write an endless do loop where i=10

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

Write an endless for loop where i=10

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

Write an endless while loop where i=10

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

Write an if then else statement where i=10

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

Write an if then statement where i=10

varargs construct

You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.

JOptionPane

You can use this class to display dialog boxes

Will this line compile without errors? Object obj [ ] = {new Object(), new Object()};

Yes.

Will this line compile without errors? double[ ][ ] numbers = {{1,2,3},{7,8},{4,5,6,9}};

Yes.

Will this line compile without errors? double[ ][ ][ ] numbers = new double[7][ ][ ];

Yes.

Can a constructor be declared private?

Yes. This can be used to control the creation of the object by other less restrictive methods.

What is a compound assignment operator?

You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.

True

You cannot change the value of a variable whose declaration uses the final key word

"new" operator

You create an object from a class by using the new operator and a constructor. The new operator returns a reference to the object that was created. You can assign the reference to a variable or use it directly.

"

\"

'

\'

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

\\

\

\\

Backspace

\b

What escape sequence makes the backspace character?

\b

New line

\n

New line character

\n

What escape sequence makes the newline character?

\n

New tab character

\t

Tab

\t

What escape sequence makes the tab character?

\t

short hand a = a * n

a *= n;

short hand a = a + n;

a += n;

short hand a = a - n;

a -= n;

An interface is like ...

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

CH13: The setPreferredSize method accepts this as its argument(s).

a Dimension object

Method Definition

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

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

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

Comment Out

act of turning code into a statement so the compiler will not execute its command

CH13: A JComboBox component generates this type of even when the user selects an item.

action event

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

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

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

body of method

True False data type

boolean

Value: true/false

boolean

declare a boolean variable, isAscending

boolean isAscending;

&&, ||, !

boolean operators; and, or, not

Logical Type

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

CH11: Fields in an interface are ________.

both final and static

An open brace is always followed by a close

brace }

Never put a semi-colon before an open

brace{

CH14: This sorting algorithm makes several passes through an array and causes the larger values to gradually move toward the end of the array with each pass.

bubble sort

concatination

but strings together

Reference types

store addressed of objects stored elsewhere in memory

Object references

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

Three

the conditional operator takes this many operands

'this .' always refers to ...

the currently executing object.

Polymorphism

the feature of language that allows the same word to be interpreted correctly in different situations based on context

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

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

Encapsulation

the hiding of data and methods within an object

Allman Style

the indent style in which curly braces are aligned and each occupies its own line

Getter methods

the methods that retrieve a property's value are called getter methods. getSize()

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

the object itself immutable.

Source code

the original problem-solving, logical solution written in a programming language (ex. JAVA, .java file)

Origin

the point (0,0) in a coordinate system

Parsing

the process the compiler uses to divide source code into meaningful portions for analysis

syntax

the rules for combining words into sentences

Syntax

the rules of the language

It is legal to declare a local variable with ...

the same name as an instance variable; this is called shadowing.

true

the scope of a variable is limited to the block in which it is defined

vocabulary

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

Interpreter

the software the executes byte code

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

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

State

the values of the attributes of an object

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

the whole class must be abstract.

the equals method

this determines whether two different String objects contain the same string.

default

this section of a switch statement is branched to if none of the case expressions match the switch expression

Interactive Applications

those which a user communicated with a program by using an input device

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

thows

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

through inheritance.

CH12: You use this statement to throw an exception manually.

throw

CH12: When an exception is generated, it is said to have been ________.

thrown

CH12: This informs the compiler of the exceptions that could get thrown from a method.

throws clause`

Executing

to carry out a statement

string Var = "Hello"

variable Var = Hello (*double quotes!)

char answer = 'y'

variable answer = y (*single quotes!)

final

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

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

variableName = methodName();

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

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

Assignment

variableName = value;

Local Variables

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

Constants

variables whose values cannot change

public static void boxString(String contents)

void methods return no value, but can produce output

Identifiers may contain ...

letters, digits and the underscore character

What could a object be compared to for similarity?

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

statements

lines of code in java

CH13: A JList component generates this type of event when the user selects an item.

list selection event

LinkedList: peek methods

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

API documentation

lists the classes and methods of the Java library

i = a.Length;

load element count of array a into integer i

char[]c=s.toCharArray();

load s into character array c

&&

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

!

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.

||

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

^

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

-64 bits Range: -big to big No rules

long

/* */

long comments

public static void main(String[] args)

main method block syntax

Helper methods should be

marked as private

static

means a method is accessible and usable even though no objects of the class exist

A local variable stores temporary state; it is declared inside a ___.

method - for example a counter in a loop int i=0;

public static void main(String [ ] args)

method header;

length() method

method which counts the number of characters in a String

trim() method

method which removes leading and trailing spaces from a String

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

methodName(); public static void methodName():

Where is a software object's behavior exposed?

methods (Java) or functions (C++)

The 'synchronized' modifier applies only to ...

methods and code blocks.

Instance method

methods that are part of objects and can only b e called through an object

The two main kinds of methods:

methods that return a value / void methods

The 'native' modifier applies only to ...

methods.

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

might

predefined variable

or implicit object

implicit object

or predefined variable

'protected' members can be accessed by ...

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

CH11: Abstract methods must be ________.

overridden

'final' methods cannot be ...

overridden in a subclass.

A namespace that organizes classes and interfaces by functionality is called a ___.

package

'protected' = ...

package + kids (kids meaning subclasses)

A variable declared within the opening and closing parenthesis of a method signature is called a ____.

parameter

Copy Constructor

passes as a parameter values anouther object. All instance variables in the object

Parameter(overloaded) constructor

passes values through the parameter list; these values are used to initialize all instance variables.

to swap values of integers you need a...

place holder

System.out.println("foo");

print foo on a line

Prints x on the same line

print(x)

CH12: This method may be called from any exception object, and it shows the chain of methods that were called when the exception was thrown.

printStackTrace

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

printStackTrace()

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

println(x)

System.out.print

prints statement

System.out.println

prints statement and creates new line

System.out.println( _____ );

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

System.out.print( _____ );

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

CH11: A subclass does not have access to these superclass members.

private

Javac

program used to compile .java files into .class files.

Java

program used to run .class files

Bytecode

programming statements that have been compiled in to binary ofrmat

Source Code

programming statements written in a high-level porgramming language

CH11: When a class implements an interface, it must ________.

provide all of the methods that are listed in the interface, with the exact signatures and return types specified.

str.indexOf(text)

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

str.substring(start, end)

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

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

run()

This method is the engine of a threaded class.

run()

LinkedList: remove methods

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

objects

second category of Java variables such as scanners and strings

Consider the following code snippet. if (aNumber >= 0) if (aNumber == 0) System.out.println("first string"); else System.out.println("second string"); System.out.println("third string"); Exercise: What output do you think the code will produce if aNumber is 3?

second string third string

A class with public access can be ...

seen by all classes from all packages.

A class with default access can be ...

seen only by classes within the same package.

;

semicolon; marks the end of a complete programming statement

Passing

sending arguments to a method

Objects

sent messages

.

separates package names / adds folders

CH14: This search algorithm steps sequentially through an array, comparing each item with the search value.

sequential search

Public Interface

specifies what you can do with its objects

Math.sqrt(x)

square root of x

Application

stand-alone, executable program

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

start() & run()

To run a thread what method must be callled?

start() method

Block Comments

starts with a forward slash and an asterisk (/*) and end with an asterisk forward slash (*/) Can span many lines

javadoc Comments

starts with a forward slash and two asterisks (/**) and end with an asterisk forward slash (*/) Are used to genertate documentation with javadoc

Line Comments

starts with two forward slashes (//) and continue to the end of the current line. Can span only one line

What do real world objects contain?

state and behavior

Character.isDigit(ch)

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

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

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

while (condition) { statements }

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

assertions

statements to find error states by testing assumptions

The term "class variable" is another name for ___.

static field - class variables are fixed and global across all instances of the class

Reasons to use "long"

Numbers greater then ±2 billion

4 Java Data Types?

Numeric, String, Character, Boolean.

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

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

CH11: All classes directly or indirectly inherit from this class.

Object

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

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

A class is a type whose values are ______

Objects

CH11: A method in a subclass having the same name as a method ina superclass but a different signature is an example of _______.

Overloading

Class

The data type of an object

Semicolon

Used to separate sections.

Comma

Used to separate things within a section.

not equal

!=

What will be printed? System.out.println("roberto".replaceAll("o","!").substring(1, 6));

!bert

What will be printed? System.out.println("roberto".replaceAll("o", "!").substring(1, 7));

!bert!

What package is the ArrayList part of?

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

To invert the value of a boolean, which operator would you use?

"!" logical complement operator

String combination identifier

"+"

{ }

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

CH14: This search algorithm will search half the array on average.

...

CH14: This sorting algorithm begins by sorting the initial portion of the array consisting of two elements. At that point, the first three elements are in sorted order. This process continues with the fourth and subsequent elements until the entire array is sorted.

...

CH14: This sorting algorithm recursively divides an array into sublists.

...

Call

...

Defining Parameters

...

Element and index

...

How to use sub-string function?

...

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

...

Work with ArrayList Objects and Their Methods

...

field

...

how do you use collection

...

object

...

variable

...

what are top level clases

...

what is abstract method

...

what is collection

...

what is deadlock

...

what is inheritance

...

what is the difference between class and interface

...

what types of memory do java have

...

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

.getMessage() method

Byte code

.java code is compiled into this

What operator divides two numbers?

/

division operator

/, fourth highest precedence, left to right association

Comments

// Comment in one line. //*Comment until first occurrence of slash */

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

// and /* */

How do you make a comment?

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

random number between 1 and n

1 + Math.random() * n;

byte

1 byte, stores an integer

In the following code segment, how many times will an even number be sent to standard out? for(int x=0 ; x<10 ; x++){ if(x%2 == 0){ System.out.println("x: " + x + " - Even"); continue; } else{ System.out.println("x: " + x + " - Odd"); } x++; }

1 time

There are three access modifiers:

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

What are checked & unchecked exceptions.

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

Member access comes in two forms:

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

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

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

Class visibility revolves around whether code in one class can:

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

Instance variables can ...

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

There are four access levels:

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

Three ways to spot a non-abstract method:

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

Array

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

private

Any thing declared as Private can't be seen outside of its class

protected

Any thing declared as protected can be accessed by a classes in the same package and subclasses in other packages.

Input

Anything typed by the user.

String Literal

Anything within double quotation marks.

logical operator

Applied to boolean expressions to form compound boolean expressions that evaluate to true or false. AND, OR and NOT.

Methods?

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

Parameters

Are values that are passed to another method when it is invoked by an event.

Parameters are filled in with _________________ when invoking a method.

Arguments

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

ArrayIndexOutofBounds

ArrayList<String>: Instantiation

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

The return type of the method that issues an SELECT statement is int.

False (ResultSet)

Changes made to variable by another thread are called synchronous changes.

False (asynchronous)

The getLocation method returns the location for the mouse event.

False (getPoint)

You can call wait only from a method that own a key.

False (lock)

To execute a task repeatedly, specify the period in seconds.

False (milliseconds)

Only type 1 drivers are portable to any JVM.

False (type 4)

True or False - during arithmetic, when the operands or different types, the resulting type is always the widest of the two type.

False, the result of an arithmetic operation on any two primitive operands will be at least an int -- even if the operands are byte and short.

CH12: This is one or more statements that are always executed after the try block has executed and after any catch blocks have executed if an exception was thrown.

Finally block

General Rule to fix Syntax Errors

Fix 1st error and any obvious errors,then recompile.

Data Type Sizes

Fixed in Java, to ensure portability across implementations.

Evaluation

The process of obtaining the value of an Expression

i

What is the standard convention for un-named variables?

Post Condition?

What will be true after a method is called

Widening conversion

When Java converts a lower- ranked value to a higher - ranked type, it us called a -----

Void

When a method does not return a value.

Implicit type coercion:

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

Operator Precedence

When an expression includes one or more operators, this governs in what order the operations are carried out. For example, multiplication has a higher precedence than addition and so is carried out first. Each language has rules of precedence for all of it's operators.

Truncation

When casting a larger type to a smaller type there may be a loss of information due to the truncation of additional bits or the fractional part of the number when casting from a floating point number to an integral number.

&&

When determining whether a number is inside a range, its best to use this operator

round off errors

When double values are translated to binary bits information is lost or created.

Encapsulation

When each object protects its own information.

Binary Number

a number composed of 0s and 1s (base-2 number)

int

a primitive data type, integer

Virus

a program that can enter a computer and perhaps destroy information

Compiler/Interpreter

a program that translates code into machine language

High-Level Programming Language

a programming language that resembles human language to some degree.

A subclass outside the package cannot access ...

a protected member by using a reference to superclass instance.

Method

a self-contained block of programming code, similar to a procedure

A ________ is used to terminate all java

a semi colon ;

'abstract' methods end in ...

a semicolon - no curly braces.

Method

a sequence of instructions that accesses the data of an object

Arithmetic expressions

a sequence of operands and operators that computes a value

Literal String

a series of characters that appear excatly as entered. Any literal string in Java appears between double quotation marks

Computer Porgram

a set of instructions that you write to tell a computer what to do.

Write Once Run Anywhere (WORA)

a slogan developed by Sun Microsytems to describe the ability of one Java program version to work correctly on multiple platforms

algorithm

a step by step description of how to accomplish a task

Computer program

a step by step set of instructions for a computer.

Procedural Programming

a style of programming in which sets of operations are executed one after another in sequence

Object reference

a value that denotes the location of the object in memory

Statements and expression

a way to manipulate/operate on the data

Instance Field Declaration

accessSpecifier class ClassName { accessSpecifer fieldType fieldName; }

Class Definition

accessSpecifier class ClassName { constructors methods fields }

Unicode

an international system of character representation

out

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

Assignment operator

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

White space

and combination of nonprinting characters

numeric data types

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

'synchronized' methods can have ...

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

Static variables are not tied to ...

any particular instance of a class.

Object

anything that can be represented by data in a computer's memory and manipulated by a computer program.

CH11: In a subclass constructor, a call to the superclass constructor must__________

appear on the very first statement

String concatenation

append a string or value to another string

The term API stands for ___?

application programmer interface

What will be printed? System.out.println("roberto".replaceAll("o", "!").substring(2, 7));

bert!

semantics

define the rules for interpreting the meaning of statements

Access Modifier

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

void

describes function that returns no value

private

describes property that can only be accessed locally

static

describes property that never changes

Class Definition

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

Semantic rules:

determine the meaning of instructions in a programming language.

Syntax rules:

determine the validity of instructions in a programming language.

/=

divide and assign operator

The ___ statement is similar to the while statement, but evaluates its expression at the ___ of the loop.

do while end

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

do/while loop

-64 bits Range: -big to big

double

For numeric data types what declaration will always be used?

double

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

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

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

double b = (double) a / b;

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

double numero = 867.5

Insert a comment? On multiple lines?

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

//

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

declare and initial double array, points, with length N

double[] points = new double [N];

Math.exp(x)

e^x

Instance

each copy of an object from a particular class is call an instance of the object.

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

elements separated by commas with brackets

Hiding internal data from the outside world, and accessing it only through publicly exposed methods is known as data...

encapsulation

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

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

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

equals && toString

Compile-Time-Error

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

What will be printed? System.out.println("roberto".substring(3, 7));

erto

\\

escape character for backslash

Declare & Initialize a variable

int n = 5;

Declare a variable

int n;

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

int num = 394;

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

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

Primitive types

int, double, boolean, char

Name the 6 numeric data types

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

Primitive types

int, float, and boolean variables are examples of this

Numeric Data Sub-Types

int, long, float, double

CH13: A list selection listener must have this method.

valueChanged

literals

values that are hard-coded into the program (integers and strings)

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

";"

How do you assign data to a variable?

"=". ex. int number = 100

&&

"And" operator

CPU

"Central Processing Unit" The brain of the computer.

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

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

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

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

||

"Or" operator

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

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

ampersand

"and" operator

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

"members".

vertical line

"or" operator

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

"this."

remainder

%

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

% /number of spaces taken up/ Integer, variable

remainder or modulus operator

%, fourth highest precedence, left to right association

and

&&

Logical Operators

&& ||

logical operators

&&, and ! are

Integer value: 48

'0'

Integer value: 65

'A'

Integer value: 97

'a'

An 'abstract' class can have both ...

'abstract' and non-abstract methods.

switch example

'char control = 'a'; switch (control) { case 'a': invokeA(); break; default: invokeError(); break; }' Note that because 'a' is logically equivalent to the switch argument 'control', that case would be selected and, once the statements executed, break would transfer control to the end of the switch statement, skipping the default: case.

A class cannot be both ...

'final' and 'abstract'.

Classes can also be modified with ...

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

'abstract' methods cannot be ...

'private' or 'final'.

Interface methods are by default ...

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

switch...case form

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

grouping operator

( ), highest precedence

How do you create variables?

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

str.equals("test")

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

cast operator

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

Cast

(typeName) expression

What operator multiplies two numbers?

*

multiplication operator

*, fourth highest precedence, left to right association

addition operator

+, fifth highest precedence, left to right association

unary plus operator

+, third highest precedence

subtraction operator

-, fifth highest precedence, left to right association

unary minus operator

-, third highest precedence

What is the primitive storage range of a byte?

-128 to 127

LinkedList: add item to beginning of list

-addFirst(item);

method selector operator

., second highest precedence, left to right association

CH14: If an array is sorted in this order, the values are stored from highest to lowest.

...

CH14: If an array is sorted in this order, values are stored from lowest to highest.

...

CH14: In this sorting algorthm, the smallest value in the array is located and moved to position 0. Then the next smallest value is located and moved to position 1. This process continues until all of the elements have been placed in their proper order.

...

CH14: This search algorithm repeatedly divides the portion of an array being searched in half.

...

CH14: This search algorithm requires that the array's contents be sorted.

...

Describe 2 classes can have.

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

Create an array called 'colors' and add to it :"red","blue", "Green" 2. 1. Create a foreach loop the writes out the contents of the arra

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

Name to things about strings in Java.

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

Steps in Creating Pseudocode

1. Understand the Problem 2. Decide How to solve the problem 3. Write the Solution Using a logical sequence of statements

Why should I bundle classes and interfaces into a package?

1. You and other programmers can easily determine that these types are related. 2. You and other programmers know where to find types that can provide related functions. 3. The names of your types won't conflict with the type names in other packages because the package creates a new namespace. 4. You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the package.

Reasons to use "double"

1023 digits after the decimal point

Reasons to use "float"

127 digits after the decimal point

short

16 bit integer

short

2 bytes, stores integer values

Braces{}

A group of statements, such as the contents of a class or a method, are enclosed in

The RGB values of Color.RED

255, 0, 0

int

32 bit integer

float

32 bit real number

OOP Program

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

long

64 bit integer

double

64 bit real number

What is the ASCII value of 'A'?

65

byte

8 bit integer

double

8 bytes, stores floating-point numbers

What is the ASCII value of 'a'?

97

reading a file

: Open file, Priming read, Loop until EOF, second read in loop and Close file after loop.

In Java, every program statement ends with what?

; (a semicolon)

Method

A group of programming statements given a name.

What are 6 assignment operators?

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

assignment operator

=, lowest precedence, right to left association

Which operator is used to compare two values, = or == ?

== = is an assignment operator

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

== != > >= < <=

realtional operators

>,<, and == are

Bit

A "1" or "0" representing "on or off"

difference between Static and non Static

A "Static" method DOES NOT require instantiating an object to access it. Examples : Main and MATH methods A "Non Static" method requires instantiating an object to access it.

Identifier:

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

Syntax errors

A Non-proper, not allowable, sequence of character or words given a particular language. Listed at the bottom of screen when compilation is complete

Procedural

A Procedural Language does NOT PERMIT to define OBJECTS. Example: C Language, PASCAL

Gigabyte

A billion bytes. Can store music an video files.

single precision

A binary computing format that occupies 4 bytes in computer memory.

double precision

A binary computing format that occupies 8 bytes in computer memory.

Static Method

A block of Java statements that is given a name. They are units of procedural decomposition.

JDK

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

Bits

A byte is made up of eight

What must a class name always start with?

A capital letter then camel case with no spaces.

who implements an interface

A class implements an interface , thereby inheriting the abstract methods of the interface.

Programs

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

Subclass

A class that inherits from another class.

Superclass

A class that is inherited from.

Package

A collection of Java classes

String

A collection of characters. Surrounded by double quotation marks.

Method Call

A command to execute another method, causes all of the statements inside that method to be executed.

int b1 = 0b_0101_0101_0101_0101; int b2 = 0b_1010_1010_1010_1010; int b3 = b1 & b2; System.out.println("Value:" + b3); What will be the result?

A compilation error will occur because an underscore cannot be used after the b in the literal. The other underscores are allowed.

Given: public void simpleTest () { int i; System.out.println(i); } What will occur?

A compiler error will occur since the value has not been initialized.

Native Compilers

A compiler that translates directly into machine language and creates a program that can be executed directly on the computer. The compile code to the lowest possible level.

true

A conditionaly executed statement should be indented one level from the if clause

Screen coordinate system

A coordinate system used by most programming languages in which the origin is in the upper-left corner of the screen, window, or panel, and the y values increase toward the bottom of the drawing area

When you pass a variable as an argument to a method call, what are you passing?

A copy of the value. You always get a copy of whatever is in the variable - either a primitive or a reference. So for objects, you get a copy of the reference.

boolean

A data type that represents a true or false value.

double

A data type that represents decimals.

int

A data type that represents whole numbers.

Cohesion

A desirable quality in which the responsibilities of a method or process are closely related to each other.

Source file:

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

Method

A group of Attributes and Behaviors.

Programming language:

A set of rules, symbols, and special words.

Data type:

A set of values together with a set of operations.

Expression

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

Java

A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multi-threaded, dynamic language.

char

A single character

Token

A single element of input, java uses whitespaces to separate tokens

Iteration

A single trip through a loop.

Empty String

A special string literal, denoted by "".

Operator

A special symbol that is used to indicate an operation to be performed on one or more values

Console Window

A special text-only window in which Java programs interact with the user.

Constructor?

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

application

A stand-alone Java program stored and executed on the user's local computer.

Assignment Statement

A statement assigning a value to a variable.

Algorithm

A step-by-step description of how to accomplish a task.

Variable

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

binary

A string of bits, Base 2.

String Literals

A string of text surrounded by quotation marks that will send it as output. Must not be more than one line.

Run-time error

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

Class

A unit of code that is the basic building block of Java programs. In Java class names always begin with a capital letter. Java requires that the class name and file name always match. So if class name is "Hello", the file name is "Hello.java". Nothing can exist outside of a class!

Statement

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

Attribute

A value an object stores internally.

Operand

A value being modified by an operator. Example, x, 10.

Literal

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

Local Variable

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

True

A variable must be declared before it can be used

Local variable

A variable that has a scope from the point of declaration to then end of the block in which they are declared

Multi-thread

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

Object

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

Method

A way to accomplish a task in a Java program.

I/O

A way to get data into and out of our program

name [row] [col]

Access an element

Sequential access

Accessing an array by searching the whole array

Direct access

Accessing an array through an arbitrary location

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

Accessor methods && Mutator methods

J2EE

Acronym for Java 2 Platform, Enterprise Edition.

J2ME

Acronym for Java 2 Platform, Micro Edition.

J2SE

Acronym for Java 2 Platform, Standard Edition.

+=

Add and assign operator

Concatenation

Adding one string to another.

Scanner input = new Scanner(System.in);

Adds scanner to program

.java

All Java file names have to have this extension.

;

All Java statements must end with it.

Capital Letter

All java file names must have this at the beginning.

true

All lines in a conditionally executed block should be indented one level

What access control applies to interfaces?

All methods declared in an interface are implicitly public, so the public modifier can be omitted. An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted.

unchecked exception

An error that will not be resolved in the program.

flow control structures

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

What are bounded types in Java?

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

Hard Drive

Also called a hard disk. The place that a computer stores data permanently.

Logic errors

Also called bugs. When you write code that doesn't perform the task it is intended to perform.

Casting Float Types to Integral Types

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

Argument Storage

An Array.

...

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

...

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

Where can an anonymous inner class be defined?

An anonymous class is an expression. So anywhere an expression is used.

the closest previous if clause that doesnt already have its own else clause

An else clause always goes with

"enum" type

An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

classpath

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

JRE

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

declaration

An equation (has an =) that identifies a variable.

exception

An error condition that occurs during the execution of a Java program.

checked exception

An error that is resolved in a program usually with a try..catch block.

Consider the following code snippet: Vehicle aVehicle = new Auto(4,"gasoline"); String s = aVehicle.toString(); Assume that the Auto class inherits from the Vehicle class, and neither class has an implementation of the toString() method. Which of the following statements is correct? A) The toString() method of the Object class will be used when this code is executed. B) The toString() method of the String class will be used when this code is executed. C) This code will not compile because there is no toString() method in the Vehicle class. D) This code will not compile because there is no toString() method in the Auto class.

Ans: A Section Ref: 10.7.1

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

Ans: A Section Ref: 8.4

Which of the following types of side effects potentially violates the rule of minimizing the coupling of classes? A) Standard output. B) Modification of implicit parameters. C) Modification of explicit parameters. D) Modification of both implicit and explicit parameters.

Ans: A Section Ref: 8.4

Which of the following statements describes an assertion? A) A logical condition in a program that you believe to be true. B) A guarantee that the object is in a certain state after the method call is completed. C) A requirement that the caller of a method must meet. D) A set of criteria defined by the caller of a method.

Ans: A Section Ref: 8.5

Why is a static variable also referred to as a class variable? A) There is a single copy available to all objects of the class. B) It is encapsulated within the class. C) Each class has one and only one static variable. D) It is stored in the separate class area of each object.

Ans: A Section Ref: 8.7

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

Ans: A Section Ref: 9.1

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

Ans: A Section Ref: 9.7

What is the error in this array code fragment? double[] data; data[0] = 15.25; A) The array referenced by data has not been initialized. B) A two-dimensional array is required. C) An out-of-bounds error occurs. D) A cast is required.

Ans: A Section Ref: Section 7.1 Arrays

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

Ans: A Section Ref: Section 7.1 Arrays

Wrapper objects can be used anywhere that objects are required instead of ____. A) primitive data types B) clone methods C) array lists D) generic classes

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

Rewrite the following traditional for loop header as an enhanced for loop, assuming that ArrayList<String> names has been initialized. for (int i = 0; i < names.size(); i++) { // process name } A) for (String s : names) B) for (int i = 0; i < names.size(); i++) C) for (s : names) D) for (names : String s)

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

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

Ans: A Section Ref: Section 7.6 Common Array Algorithms

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

Ans: A Section Ref: Section 7.6 Common Array Algorithms

What is the purpose of this algorithm? int m = 0; for (BankAccount a : accounts) { if (a.getBalance() >= atLeast) m++; } A) Counting matches. B) Finding a value. C) Computing the sum. D) Locating an element.

Ans: A Section Ref: Section 7.6 Common Array Algorithms

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

Ans: A Section Ref: Special Topic 10.1

Which of the following statements about a superclass is true? A) An abstract method may be used in a superclass when there is no good default method for the superclass that will suit all subclasses' needs. B) An abstract method may be used in a superclass to ensure that the subclasses cannot change how the method executes. C) An abstract method may be used in a superclass when the method must have identical implementations in the subclasses. D) An abstract method may not be used in a superclass.

Ans: A Section Ref: Special Topic 10.1

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

Ans: A Section Ref: Special Topic 9.1

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

Ans: B Section Ref: 10.1

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

Ans: B Section Ref: 10.1

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

Ans: B Section Ref: 10.3

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

Ans: B Section Ref: 10.7

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

Ans: B Section Ref: 8.2

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

Ans: B Section Ref: 8.2

A static method can have which of the following types of parameters? A) Only implicit parameters. B) Only explicit parameters. C) Both implicit and explicit parameters. D) A static method cannot have parameters.

Ans: B Section Ref: 8.6

Which of the following statements about a Java interface is NOT true? A) A Java interface defines a set of methods that are required. B) A Java interface must contain more than one method. C) A Java interface specifies behavior that a class will implement. D) All methods in a Java interface must be abstract.

Ans: B Section Ref: 9.1

You have a class which extends the JComponent class. In this class you have created a painted graphical object. Your code will change the data in the graphical object. What additional code is needed to ensure that the graphical object will be updated with the changed data? A) You must call the component object's paintComponent() method. B) You must call the component object's repaint() method. C) You do not have to do anything - the component object will be automatically repainted when its data changes. D) You must use a Timer object to cause the component object to be updated.

Ans: B Section Ref: Common Error 9.6

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

Ans: B Section Ref: Quality Tip 8.3

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

Ans: B Section Ref: Section 7.1 Arrays

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

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

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

Ans: C Section Ref: 10.1

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

Ans: C Section Ref: 10.2

Consider the following code snippet: public class Coin { . . . public boolean equals(Coin otherCoin) { . . . } . . . } What is wrong with this code? A) A class cannot override the equals() method of the Object class. B) The equals method must be declared as private. C) A class cannot change the parameters of a superclass method when overriding it. D) There is nothing wrong with this code.

Ans: C Section Ref: 10.7.2

Which of the following questions should you ask yourself in order to determine if you have named your class properly? A) Does the class name contain 8 or fewer characters? B) Is the class name a verb? C) Can I visualize an object of the class? D) Does the class name describe the tasks that this class will accomplish?

Ans: C Section Ref: 8.1

Which of the following describes an immutable class? A) A class that has no accessor or mutator methods. B) A class that has no accessor methods, but does have mutator methods. C) A class that has accessor methods, but does not have mutator methods. D) A class that has both accessor and mutator methods.

Ans: C Section Ref: 8.3

Which of the following statements describes a precondition? A) A logical condition in a program that you believe to be true. B) A guarantee that the object is in a certain state after the method call is completed. C) A requirement that the caller of a method must meet. D) A set of criteria defined by the caller of a method.

Ans: C Section Ref: 8.5

Under which of the following conditions can you have local variables with identical names? A) If their scopes are nested. B) If they are of different data types. C) If their scopes do not overlap. D) If they both reference the same object.

Ans: C Section Ref: 8.8

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

Ans: C Section Ref: 9.10

Consider the following code snippet: class MouseClickedListener implements ActionListener { public void mouseClicked(MouseEvent event) { int x = event.getX(); int y = event.getY(); component.moveTo(x,y); } } What is wrong with this code? A) The mouseClicked method cannot access the x and y coordinates of the mouse. B) repaint() method was not called. C) The class has implemented the wrong interface. D) There is nothing wrong with this code.

Ans: C Section Ref: 9.11

Which of the following statements will compile without error? A) public interface AccountListener() { void actionPerformed(AccountEvent event); } B) public interface AccountListener() { void actionPerformed(AccountEvent); } C) public interface AccountListener { void actionPerformed(AccountEvent event); } D) public abstract AccountListener { void actionPerformed(AccountEvent event); }

Ans: C Section Ref: 9.7

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

Ans: C Section Ref: 9.7

char

Any character. Surrounded by single quotation marks.

How do you specify what the program should do when the user clicks a button? A) Specify the actions to take in a class that implements the ButtonListener interface. B) Specify the actions to take in a class that implements the ButtonEvent interface . C) Specify the actions to take in a class that implements the ActionListener interface. D) Specify the actions to take in a class that implements the EventListener interface.

Ans: C Section Ref: 9.9

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

Ans: C Section Ref: Section 7.2 Array Lists

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

Ans: C Section Ref: Section 7.2 Array Lists

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

Ans: C Section Ref: Section 7.6 Common Array Algorithms

Which of the following is true regarding inheritance? A) When creating a subclass, all methods of the superclass must be overridden. B) When creating a subclass, no methods of a superclass can be overridden. C) A superclass can force a programmer to override a method in any subclass it creates. D) A superclass cannot force a programmer to override a method in any subclass it creates.

Ans: C Section Ref: Special Topic 10.1

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

Ans: C Section Ref: Special Topic 10.2

Consider the following code snippet: final RectangleComponent component = new RectangleComponent(); MouseListener listener = new MousePressListener(); component.addMouseListener(listener); ______________ frame.add(component); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); Which of the following statements completes this code? A) private static final int FRAME_WIDTH = 300; B) private static final int FRAME_HEIGHT = 400; C) Frame frame = new Frame(); D) JFrame frame = new JFrame();

Ans: D

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

Ans: D Section Ref: 10.2

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

Ans: D Section Ref: 10.3

Which of the following is true regarding subclasses? A) A subclass may call the superclass constructor by using the this reserved word. B) A subclass cannot call the superclass constructor. C) If a subclass does not call the superclass constructor, it must have a constructor with parameters. D) If a subclass does not call the superclass constructor, it must have a constructor without parameters.

Ans: D Section Ref: 10.4

Which of the following statements generally describes the scope of a variable? A) The ability of a variable to access other variables in the same program. B) The amount of data in bytes that the variable can contain. C) The range of data types that the variable can legally be cast into. D) The region of a program in which the variable can be accessed.

Ans: D Section Ref: 8.8

Which of the following is not a reason to place classes into a package? A) to avoid name clashes (most important) B) to organize related classes C) to show authorship of source code for classes D) to make it easier to include a set of frequently used but unrelated classes

Ans: D Section Ref: 8.9

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

Ans: D Section Ref: 9.1

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

Ans: D Section Ref: 9.3

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

Ans: D Section Ref: 9.8

Which of the following code statements creates a graphical button which has "Calculate" as its label ? A) Button JButton = new Button("Calculate"). B) button = new Button(JButton, "Calculate"). C) button = new JButton("Calculate"). D) JButton button = new JButton("Calculate").

Ans: D Section Ref: 9.9

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

Ans: D Section Ref: Section 7.1 Arrays

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

Ans: D Section Ref: Section 7.2 Array Lists

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

Ans: D Section Ref: Section 7.2 Array Lists

Which of the following is considered by the text to be the most important consideration when designing a class? A) Each class should represent an appropriate mathematical concept. B) Each class should represent a single concept or object from the problem domain. C) Each class should represent no more than three specific concepts. D) Each class should represent multiple concepts only if they are closely related.

Ans:B Section Ref: 8.1

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

Classes in OOP, are related to each other & they're going to be related through an "IS-A" relationship or "HAS-A" relationship. > IS-A relationship result from inheritance > HAS-A relationship result from composition This comes from the need to reuse code. v47

Java bytecodes

Code that can execute on many different machines.

compound boolean expressions

Combination of two conditionals that evaluate to true or false.

Concatenation

Combining several strings into one string, or a string with other data into a longer string using the operator "+"

Is this valid? static final long APHELION = 152,097,701;

Commas are not allowed in numeric literals, so a compiler error will occur.

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

Comments

False

Comments that begin with // can be processed by javadoc

new type [nRows] [nCols]

Create a 2D array

Design Team

Creates Solution Code. Takes about 75% of Total Program/Solution Time

Declaration

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

Instantiation

Creating an object.

Overloading the method?

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

What kind of value and how much will be stored?

Data Type

Encapsulation?

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

type[] [] name

Declare a 2D array

[]

Declares arrays

--

Decrement by one

What is the difference between the default and protected access specifier?

Default does not allow sub class access. Both allow package access.

Null means nothing. It's a place holder.

Define "Null"

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

Define the keyword "abstract"

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

Define the keyword "catch"

used to create a subclass for an existing class.

Define the keyword "extends"

used to implement an interface.

Define the keyword "implements"

Only able to be modified inside the class.

Define the keyword "private"

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

Define the keyword "protected"

Arithmetic Expression Type

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

Syntax Template

Describes the basic form of a Java construct. Java has rules that determine its legal syntax or grammar.

Programmers

Design Team hands solution to these coders.

Operator precedence rules:

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

Digital vs Binary

Digital Binary 0 0 1 1 2 10 3 11 4 100 5 101 6 110 7 111 8 1000 9 1001 10 1010 11 1011 12 1100 13 1101 14 1111

/

Division operator

do{ code here } while ( argument here);

Do loop

Default constructor

Does not take any input values this constructor assigns default initial values to all instance variables.

Surround all String text with?

Double Quotes

CH11: With this type of "binding", the Java Virtual Machine determines at runtime which method to call, depending on the type of the object that a variable refences.

Dynamic

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

EOFException

Address

Each byte is assigned a unique

Thread

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

What is camel casing?

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

Advantages of Constants

Easier to Understand. Easier to Modify.

Floating Point Literals

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

Inheritance

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

String Literal

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

;

End of a statement

What are the two subclasses of the throwable class?

Error & Exception

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

Error & RuntimeExceptions

internal problems involving the Java virtual machine (the runtime environment). These are rare and usually fatal to the program; there's not much that you can do about them.

Errors

-Begins with a \ -Always comes in pairs

Escape sequences

Double var = input.nextDouble();

Establishes value inputed into scanner as a variable

Logical Expression

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

Semicolon

Every complete statement ends with a

Declared

Every variable must be declared,which sets aside memory for the storage location.

a.b()

Execute a method b which belongs to object a

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

Exercise. v(32)

Argument

Extra information sent to a program.

Accessor

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

Pseudo code

Fake Code. Every Programmer's way of Writing Down Steps in Soling a Problem.

All programs have at least two threads.

False

To select a predefined strategy for positioning components in a container, set up an association between a class that extends LayoutManager or LayoutManager2 and a container.

False

True or False, octal literals can start with \u.

False

True or False, octal literals can start with \x.

False

When designing a class that runs on a thread, extending Thread (as opposed to implementing Runnable) is the more flexible and usually preferred approach.

False

Persistence Broker, shown in the figure, uses JDBC.

False (Persistence Classes)

find the max

Math.max (x, y);

switch selector value

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

switch argument

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

HashMap<String, String>: Instantiation

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

Literals

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

What must variable names have/not have?

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

'A' is less than 'B'

How does the character 'A' compare to the character 'B'

Inheritance

How one class can be created from another.

CH12: FileNotFoundException inherits from ________.

IOException

InterruptedIOException is a subclass of?

IOException

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

Identifiers (name) Rules

Constants

Identifiers that always have the same value.

Variables

Identifiers used to store values that may change.

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

Identity

switch fall-through

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

What happens if a class has no modifier?

If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes)

False

If one of an operator's operands is a double, and the other operand is an int, Java will automatically convert the value of the double to an int.

What access is the generated constructor given when one is not supplied?

If the class is public, than it is public. Otherwise the default constructor is default.

What does casting have to do with interfaces?

If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface. As an example, here is a method for finding the largest object in a pair of objects, for any objects that are instantiated from a class that implements Relatable: public Object findLargest(Object object1, Object object2) { Relatable obj1 = (Relatable)object1; Relatable obj2 = (Relatable)object2; if ((obj1).isLargerThan(obj2) > 0) return object1; else return object2; } By casting object1 to a Relatable type, it can invoke the isLargerThan method.

If you want to define an unchecked exception, your exception must extend (directly or indirectly) which class?

If you want to define an unchecked exception, your exception must extend the RuntimeException class.

A stream of binary numbers

If you were to look at a machine language program, you would see

CH13: You can pass an instance of this class to the JLabel constructor if you want to display an image in the label.

ImageIcon

import java.util.Scanner;

Import the ability to use a scanner from database

base or radix

In an example of 2^X, 2 is the base or radix. The numeric in an exponent.

Objects have both _______ and _______.

Instance Variables && Methods

Int

Integer Range is typically of -2,147,483,648 to 2,147,483,648

IDE

Integrated Development Environment Provides an all-in-one environment for creating, editing, compiling, and executing program files.

Java

Interpreted, platform independent, object oriented language

LinkedList: iterate through list of strings and print each one

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

CH13: To display a dialog box that allows the user to select a color, you use this class.

JColorChooser

CH13: To display an open file or save file dialog box, you use this class.

JFileChooser

CH13: You use this class to create a menu bar.

JMenuItem

CH13: You use this class to create a radio button menu item.

JRadioButtonMenuItem

CH13: Components of this class are multi-line text fields.

JTextArea

Java virtual machine

JVM stands for

Java 7's Garbage-First (G1) garbage collector is planned as the long-term replacement of which collector?

Java 7's Garbage-First (G1) garbage collector is planned as the long-term replacement of the Concurrent Mark-Sweep (CMS) collector.

JDK

Java Development Kit

JRE

Java Runtime Environment Distributed by Sun Microsystems

JVM

Java Virtual Machine A theoretical computer whose machine language is the set of Java bytecodes.

Package

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

JDK

Java development kit

JRE

Java runtime environment

Primitive types

Java variable -- Simple values stored directly in the memory location associated with the variable

Concatenating

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

double

Larger real number (=/-) 10e-324 to 10e308.

<

Less than

<=

Less than or equal to

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

MalformedURLException

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

Map - Look in module about collections.

π

Math.PI;

absolute value of x - y

Math.abs(x - y);

arc cos x

Math.acos(x);

arc sin x

Math.asin(x);

Precedence

Level of importance of operations.

;

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

public static void main(String[] args){

Line 2 of program, opens programming block

Which lines will not compile? Integer luckyNumber = 66; System.out.println(luckyNumber.booleanValue()); System.out.println(luckyNumber.charValue()); System.out.println(luckyNumber.byteValue()); System.out.println(luckyNumber.shortValue()); System.out.println(luckyNumber.longValue()); System.out.println(luckyNumber.floatValue()); System.out.println(luckyNumber.doubleValue());

Lines two and three will not compile, because you cannot convert the Integer wrapper class to a boolean or char primitive. For the Integer class, the methods booleanValue and charValue do not exist.

LinkedList<String>: Instantiation

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

Which of the following are interfaces to ArrayList? List, Map, Queue, RandomAccess, and Set.

List and RandomAccess are interfaces to ArrayList.

Which literal data types must be cast in order to work with an int data type?

Literals of type long, float, and double must be explicitly cast to an int to be used with a variable of the type int.

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

Local variable

Runtime errors

Logic errors so severe that Java stops your programing from executing

Define how java classes are connected.

Loosely connected objects that interact with each other.

public static void main(String args[])

Main Method

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

Main method

Public int

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

cos x

Math.cos(x);

The Java Programming Environment

No matter what environment you use, you will follow the same basic three steps. 1. Type in a program as a Java Class 2. Compile the program file. 3. Run the compiled version of the program.

A no-argument constructor has....

No parameters.

Can a top-level class be marked as protected?

No, a top-level class can only be marked public or default. The protected access is just for member variables and methods, and allows subclasses outside the superclass package to inherit the protected members.

Can you compare a boolean to an int?

No, booleans are true and false keywords and nothing else.

Can a private method be overridden?

No, but the can be re-declared in the subclass. This is not polymorphism.

Can a constructor be declared static?

No, constructors are for creating new instance objects. Static methods are for non-instance code, so it makes no sense to have a static constructor.

Can a member variable be declared synchronized?

No, the keyword synchronized marks method code so that it cant be run by more than one thread at a time.

Does each source file need a public class in it?

No.

static

Not belonging to a class or individual objects.

White Space

Not recognized by compiler Indent (ex 3 spaces) for each new function selection or loop.

Reason Brackets are missing

Not required for single statement IF statements or Loops.

Logic Error Examples

Nothing Happens Infinite Loop Program output is incorrect Dividing by zero (Error Message at Run Time) Errors May be intermittent

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

NullPointerException

hexidecimal

Number utilizing base 16

CH12: The numeric wrapper classes' "parse" methods all throw an exception of this type.

NumberFormatException

Reasons to use "int"

Numbers -2 billion to, 2 billion

'if' statement

Of the form 'if( [logical_expression] ) { statements; }'. where the statements in the *body* are executed if the logical expression argument in the header parentheses evaluates to true. Note that the entire structure is considered a single statement.

If break statements are not used in a switch, what will happen?

Once a case statement is entered, the code will continue to execute in each case below it, until it hits a break statement.

nested or embedded

One control statement inside another, such as an if or loop.

static

One copy and everyone can see it

next()

One word String

Private variable declaration?

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

public class{

Opens and names your program

Logical Operators

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

Precedence and Parentheses

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

Increment and Decrement Unary Operators

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

Associativity

Order of Operation for Equal Level Precedence. Most operator have left to right associativity.

Input and Output (I/O)

Output :System.out.println('hello World!"); Input from Scanner: Note scanner is a build in type.

JAVA Libraries

Over 2000 of these exist, sometimes called packages. Can have access to them by Java.lang (package is imported automatically) on top of first class.

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

Overflow error

Can overriding methods throw different exceptions than that of the super?

Overriding methods cannot throw any new or broader exception that is checked. Unchecked does not apply.

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

Parameter

Methods

Part of an Object's behavior.

if...else if... statement

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

What is assumed to be true when a method is called

Precondition

Java Type Categories

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

Stores a specific type of value

Primitive data types

Integral Types

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

Will this compile? int ivar = 77; Integer integer = ivar;

Primitives and their wrapper classes are automatically converted back and forth with autoboxing and auto-unboxing.

System.out.print(" ");

Prints a string of text

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

Private

What are the access specifiers in order of most restrictive to least?

Private, Default, Protected, and Public.

Access Control

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

Simple rules to live by

Put class and method headers on lines by themselves. Put no more than one statement on each line. Indent your program properly. When an opening brace appears, increase the indentation of the lines that follow it. When closing brace appears, reduce the indentation. Indent statements inside curly braces by a consistent number of spaces (4 spaces are common) Use blank lines to separate parts of the program.

Single '

Quotation type used for character values.

Double "

Quotation type used for string values.

RAM

Random Access Memory Used to store programs that are being executed, along with their data. (Does not retain its contents when computer is turned off.)

Caching truth or falsity

Rather than constantly checking the truth of a logical expression, sometimes it is better to store the result in a boolean and use that subsequently. For example 'boolean isFlying = height > 0.5f; if(isFlying == true) { flapWings(); }'

float

Real Number.Range of Typically (=/-) 10e-45 to 10e38.

Stores (points to) the memory address of an object

Reference variable

ClassNotFoundException is a subclass of?

ReflectiveOperationException

IllegalAccessException is a subclass of?

ReflectiveOperationException

NoSuchMethodException is a subclass of?

ReflectiveOperationException

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

Runtime Exceptions

RMI

Remote Method Invocation

For Loop

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

Modulus

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

Fill in the blank. Import statements are ______.

Required in all versions of Java.

return function?

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

String method length()

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

Syntax

Rules for combining words into sentences

Semantics

Rules for interpreting the meaning of statements

Running out of Java heap memory is an example of what?

Running out of heap memory results in a java.lang.OutOfMemoryError unchecked error.

What is a Vector?

Similar to ArrayList, but synchronized

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

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

SDK

Software Development Kit or a set of tools useful to programmers

"static" modifier

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class. Class variables are referenced by the class name itself (not an object name), as in Bicycle.numberOfBicycles This makes it clear that they are class variables rather than instance variables.

Whitespaces

Space, Tab, newline characters

mantissa

Specifies the digits of a number when an exponent is used.

println

Starts a new line after displaying the text.

-Must end with a ; (semicolon)

Statements

Expressions

Statements that involve a mathematical equation and produce a result.

play 2001.mid

StdAudio.play("2001.mid");

draw circle at (x, y) radius = r

StdDraw.circle(x, y, r);

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

StdDraw.filledCircle(x, y, r);

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

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

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

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

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

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

draw point at (x, y)

StdDraw.point(x, y);

set pen color

StdDraw.setPenColor();

pen size to 0.05

StdDraw.setPenRadius(0.05);

set x and y window scale to -R , R

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

draw "text" at (x, y)

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

boolean for empty

StdIn.isEmpty()

read double

StdIn.readDouble();

read an integer

StdIn.readInt();

std print

StdOut.println();

algorithm

Step by step process.

Main Memory

Storage Location of Data in a Computer.

Char Type

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

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

String

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

String

What word is always capitalized in java syntax?

String

0 or more characters surrounded by double quotes?

String (always capital "S")

Example of variable declaration and explanation.

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

String declaration

String name = "";

nextLine()

String of words

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

String wrd = "cats";

Array: convert from Collection strs to Array

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

string Array: Instantiation

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

declare and initial string array, names, with length N

String[] names = new String [N];

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

Subclass

-

Subtraction operator

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

Syntax error

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

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

How do you print something in the output?

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

Print format statement to get 3.14 of pi

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

print (return) a command line input

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

Print statement

System.out.println("");

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

System.out.println("Hello");

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

System.out.println()

print (return)

System.out.println();

GUIs use a separate thread called the event dispatched thread for drawing and forwarding all paint requests to that thread.

True

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

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

Emergency exit

Sytem.exit(value);

Create a generic class as in v58

TODO

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

TODO

Create an example of Polymorphism that reflect v51

TODO

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

TODO

Create an example of composition. Create a car class that HAS a gas tank. After the car runs 200miles, make it request to add gas.

TODO inspired by v49 (paper tray example)

Create an example of inheritance and using a constructor by writing a method that print the name passed into the constructor. In the super class, use the keyword 'protected'

TODO v48

Create an example using 'wild cards'

TODO v61

What is erasure?

TODO v62

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

TODO - video on Excepions -->Try / Catch

What is a 'Queue' in Java?

TODO: Create a queue

%=

Take remainder and assign operator

%

Take remainder operator

Promotion

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

While Loop

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

Do While Loop

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

Comments

Text that programmers include in a program to explain their code. The compiler ignores comments. /* */ is one comment form ( everything in between is a comment) // a form used to indicate that the rest of the current line (everything to the right) is a comment

Output

Text that the computer prints to the console window.

Comment

Text, ignored by the compiler, used to explain the code to the reader

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

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

Logic error

The "dangling else problem"

Assignment operator:

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

AND

The AND operation is a binary operation, meaning that it needs two operands. c = a AND b Both a AND b must be true for the result to be true. Example: if (num1 > 0 && num1 < 100) // && indicates AND

What is the ArrayList class a representation of?

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

Byte code

The Java compiler generates___

NOT

The NOT operation is a unary operation with only one operand. c = NOT (a) It simply reverses the true or false value of the operand. Example: while (!exit) // ! Indicates NOT

OR

The OR operation is also a binary operation with two operands. c = a OR b If either a OR b is true, then the result is true. Example: if(num1<=0 || num1>= 100) // || indicates OR

Running

The Process of execution.

Executable

The Result of Compiling and Linking a Source Program; the ".exe" file that the Computer Can Run.

Iterator

The counter variable used to control a loop.

Properties

The data that represent the object and organized into a set of properties.

Method Overloading

The ability to define two or more different methods with the same name but different method signitures

Program Execution

The act of carrying out the instructions contained in a program.

Instantiation

The act of creating a new instance of an object.

File

The basic unit of storage on most computers. Every file has a name. A file name ends with an extension. Java files end with the extension .java

Precedence

The binding power of an operator which determines how to group parts of an expression

Class

The blueprint that defines the obejcts with the properties and the methods

What does break do?

The break statement has two forms: labeled and unlabeled. An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement.

Arrays.copyOf(values, n)

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

Source code:

The combination of the import statements and the program statements

string1.compareTo (string2) < 0

The compareTo method compares strings in lexicographic order.

termination condition

The condition that stops the loop.

What does continue do?

The continue statement skips the current iteration of a for, while, or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. A labeled continue statement skips the current iteration of an outer loop marked with the given label.

Destination

The converted version of the source in a new form.

Which statement is correct? ArrayList d1 = new ArrayList(); ArrayList d2 = new ArrayList<>(); ArrayList<> d3 = new ArrayList<>(); ArrayList<Double> d4 = new ArrayList<>(); ArrayList<Double> d5 = new ArrayList<Float>();

The declarations for d1, d2, and d4 are valid as they will compile.

Method header

The first line of a method.

Class header

The first line of the class. It might say something like public class Hello {

Literals

The following data 72 'A' "Hello World" 2.8712 Are all examples of

What is the new method of the Locale class to Java SE 7?

The getUnicodeLocaleAttributes method was introduced to the Locale class in JDK 1.7 along with the getDefault, setDefault, getScript, getExtension, getExtensionKeys, getUnicodeLocalType, getUnicodeLocaleKeys, toLanguageTag, forLanguageTag, and getDisplay script. It's presented here to stress your need to be familiar with the Javadoc documentation of the Java API specification.

Polymorphism

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

if...else statement

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

decision structure

The if statement is an example of a

If no listeners are registered, the event is delivered to the default listener.

True

Attribute

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

What best describes the result of the following code segment? The ArrayList sampleArrayList has already been declared and initialized. int i = 63; sampleArrayList.add(i);

The int is converted to an Integer via auto boxing and then placed into the ArrayList. Primitives cannot be stored in an ArrayList. However, if they are placed into their primitive wrapper class they can be stored. Java will automatically make that conversion via its autoboxing feature if a primitive is placed into an ArrayList.

Type

The kind of Value (e.g., Integer, Floating Point Number, Character) is being stored.

Setter methods

The methods that change a property's value are called setter methods setSize()

What is the keyword native?

The native keyword is applied to a method to indicate that the method is implemented in native code using JNI.

Unary

The negation operator is

Debugging

The process of finding and correcting errors in a program

Listeners

The objects that receive the information that an event occurred are called listeners.

Flow of Control

The order in which the statements of a Java program are executed

Flow of Control

The order in which the statements of a Java program are executed.

Scope

The part of a program in which a particular declaration is valid

Hardware

The physical components that make up a computer. CPU, RAM, main board, hard drive are examples

Object-oriented

The primary mode of execution of objects with each other

"private" modifier

The private modifier specifies that the member can only be accessed in its own class.

short-cut evalulation

The process in an "if statment" that allows it to skip the rest of the stated program, should it come to the conclusion prior to the end of the program.

Casting

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

What is the output of the following code segment? int value = 1; switch (value) { case 0: System.out.println("Dog"); case 1: System.out.println("Cat"); case 1: System.out.println("Fish"); default: System.out.println("Cow"); }

This will not compile because it includes a case statement with the same value twice.

Floating Point Types

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

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

Threads

CH12: All exception classes inherit from this class.

Throwable

braces {}

To create a block of statements, you enclose the statements in these

javax.swing.*;

To create lightwieght components for a GUI.

java.net.*;

To develop a networking application.

java.awt.*;

To paint basic graphics and images.

Return

To send a value out as the result of a method that can be used in an expression in the program. Void methods do NOT return a value.

initialization

To start, the first value given to a variable

java.io.*;

To utilize data streams.

java.lang.*;

To utilize the core java classes and interfaces.

java.util.*;

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

A Java application window is a frame window.

True

A connection from a DataSource object has the same type as one from a DriverManager object.

True

A subclass of Thread must provide an implementation of the run method because it implements the Runnable interface.

True

A type 1 driver is called the JDBC-ODBC bridge.

True

All components have the methods addFocusListener and add MouseListener.

True

All the classes java.util.TimerTask and java.uti.Timer provide methods for requesting that the JVM generate threads to run scheduled tasks.

True

Any thread that is executing can all interrupt on another thread.

True

Containers are components that house other components.

True

Deadlock can occur when all threads are in a blocked state.

True

For the listener interfaces with more than on method, you can implement the listener indirectly by extending its adapter class.

True

Escape sequences

Two-character sequences that are used to represent special characters They all begin with the backslash character. (\) \t tab character \n new line charachter \" quotation mark \\ backslash character

primative types or built in type

Type of sequence of letters or digits specified by int, boolean, or double.

Boolean Values

Type of variable that cannot be used in any Casting.

Stack overflow error

Typically this is caused when your recursive functions don't have the correct termination condition, so it ends up calling itself for ever.

Prefix Operator

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

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

Unchecked exceptions

Spelling Error Examples

Undefined Variable Name Unrecognized KeyWord

What version of Unicode is supported by Java SE 7?

Unicode standard, version 6.0.0

String operator '+'

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

Cast operator:

Used for explicit type conversion

relational operator

Used in boolean expressions that evaluate to true or false. Combinations of <. > or =

Ternary Operator

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

//

Used to comment out a line.

/* */

Used to comment out a paragraph or longer

double

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

int

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

byte

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

==

Used to equal a value

System.out.println();

Used to send one line of output to the console window. What is in the parenthesis must be in quotes to print it. A blank line will be printed if there is nothing in the parenthesis.

Variables

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

StringBuffer

Utility Class part of java.lang ; methods: insert, append - multy tread environments, synchronize use of a string among multiple treads

StringBuilder

Utility Class part of java.lang ; methods: insert, append - single treaded environments

blank.

Value

Initialization

Value given to a variable at declaration.

Assignment

Value given to a variable in execution statement.

False

Variable names may begin with a number

Variables

Variables are memory locations use to store data. Methods maintained their own variables which are local to the methods

Constants

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

Behavior

What an object does.

Initialization

When you first store something in a variables memory location.

overflow error

When you try to strore a value whose magnitude is too big an int variable.

Operator Overloading

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

Conditional Processing

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

Strongly Typed

Whereby, in a language (Java), every variable and expression has a type *when the program is compiled*. You cannot arbitrarily assign the value of one type to another.

nextDouble

Which Scanner class method would you use to read a double as input

nextLine

Which Scanner class method would you use to read a string as input

72 = amount; profit = 129

Which of the following are not valid assignment statements?

while(insert argument here) { insert code here }

While loop

Nesting Conditional Constructs

Within a code block, additional flow control structures can be nested. For example an if statement could be nested within the code block of another if statement, or a switch statement within the case of another switch statement. Note that stylistically, nesting results in further indentation so that flow can be followed easily.

"this" keyword

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter. public class Point { public int x = 0; public int y = 0; //constructor public Point(int x, int y) { this.x = x; this.y = y; } } Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.

Reserved words

Words that have predefined meanings that cannot be changed

Are there standard Java arrays built into the Java language?

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

Can a class be declared as final?

Yes, a class can be declared final; that is, the class cannot be sub-classed. This is done for security and design.

Is this valid? Object [] o = {"Song Book", 35.95, new Guitar(), 6};

Yes, it is fine to have subtypes as elements in an array of a supertype.

Are instance variables assigned a default value?

Yes, member or instance variables are always given a default value.

Can standard Java arrays be multi-dimensional?

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

Will this line compile without errors? Object [ ] obj = new Object [7];

Yes.

Will this line compile without errors? Object obj = new Object ();

Yes.

Will this line compile without errors? Object obj [ ] = new Object [7];

Yes.

Will this line compile without errors? Object obj [ ] = {new Object [1], new Object [2]};

Yes.

overloaded

a class having more than one method with the same name

System

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

Interfaces cannot extend ...

a class, or implement a class or interface.

Method Call

a command to execute another method

What does /* suggest

a comment

'final' reference variables cannot refer to ...

a different object once the object has been assigned to the 'final' variable.

Coordinate system

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

method

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

Package

a group of related classes in a named directory

Java Virtual Machine (JVM)

a hypothetical computer on which Java runs

Do loop

a loop that has 0 or more iterations of the loop body

while loop

a loop that has 1 or more iterations of the loop body

A local variable disappears when...

a method invocation ends.

println

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

print

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

Consider the following code snippet. int i = 10; int n = i++%5; a) What are the values of i and n after the code is executed? b) What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))?

a) i=11, n=0 b) i=11, n=1

Consider the following class: public class IdentifyMyParts { public static int x = 7; public int y = 3; } a) What are the class variables? b) What are the instance variables? c) What is the output from the following code: IdentifyMyParts a = new IdentifyMyParts(); IdentifyMyParts b = new IdentifyMyParts(); a.y = 5; b.y = 6; a.x = 1; b.x = 2; System.out.println("a.y = " + a.y); System.out.println("b.y = " + b.y); System.out.println("a.x = " + a.x); System.out.println("b.x = " + b.x); System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x);

a) x b) y c) a.y = 5 b.y = 6 a.x = 2 b.x = 2 IdentifyMyParts.x = 2

short hand a = a + 1;

a++;

short hand a = a - 1;

a--;

String comparing a to b

a.compareTo("b");

What is wrong with the following interface? public interface SomethingIsWrong { void aMethod(int aValue){ System.out.println("Hi Mom"); } }

aMethod() should not have a method body. Remove the {Sytem.out.println("Hi Mom");} to fix it.

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

ab"\c

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

ab\c

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

abc

An interface can have only ...

abstract methods, no concrete methods allowed.

Instance variables can't be ...

abstract, synchronized, native, or strictfp.

A class implementing an interface can itself be ...

abstract.

values[i] = 0;

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

types of modifiers

access modifiers,

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

access modifiers.

'static' methods do not have direct ...

access to non-static members.

Constructor Definition

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

+

add operator

CH13: To display a scroll bar with a JList component, you must _________.

add the JList component to a JScrollPane component

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

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

'public' members can be accessed by ...

all other classes, even in other packages.

"interface" type

an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. An interface defines a protocol of communication between two objects. An interface declaration contains signatures, but no implementations, for a set of methods, and might also contain constant definitions. A class that implements an interface must implement all the methods declared in the interface. An interface name can be used anywhere a type can be used.

Events

allow components to notify each other when something happens.

Inheritance

allows code defined in one class to be reused in other classes.

Type casting

allows one data type to be explicitly converted to another

concatenation operator

allows strings to be combined in Java

JOptionPane

allows you to produce dialog boxes

Exception

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

Syntax Error

an error of language resulting from code that does not conform to the syntax of the programming language

Logic error

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

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

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

An ___ is a container object that holds a fixed number of values of a single type.

array

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

array declaration and initialization

Array Element Access

arrayReference[index]

assert(a==b);

assert assumption that integer a equals b

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

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

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

assertions

b = a[2];

assign b to second item in array a

if(i==1) { j=2; }

assign j the value 2 when i is equal to 1

Arithemetic overflow

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

b

b

\\

backslash; causes a backslash to be printed

b

bb

CH11: Abstract classes cannot _______.

be instantiated

Objects

belong to classes

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

belong to the same class.

What will be printed? System.out.println("roberto".replaceAll("o", "!").substring(2, 6));

bert

IOException

class for error in io

public class _____

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

How do you make a Hello World program?

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

Instantiating an object

class name object name = classname();

The 'strictfp' modifier applies only to ...

classes and methods.

Default members can be accessed only by ...

classes in the same package.

CH12: If your code does not handle an exception when it is thrown, it is dealth with by this.

default exception handler

Local variables don't get ...

default values, so they must be initialized before use.

what is interface

collection of abstract methods

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

commas

//

comment

Consider the following code snippet. arrayOfInts[j] > arrayOfInts[j+1] Which operators does the code contain?

comparative operator "greater than" > arithmetic operator "plus" +

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

compares equality of 2 strings

plus sign

concatenation operator

Conditional operator

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

arithmetic expression

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

Interfaces can have ...

constants, which are always implicitly 'public', 'static', and 'final'.

Package

contains a group of built-in Java classes

Interfaces are ...

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

Math.toRadians(x)

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

Math.toDegrees(x)

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

Math.cos(x)

cosine of x

Clean Build

created when you delete a previously compuiled versions of a class before compiling again

primitive

data such as numbers and characters, NOT objects

String[] a = {"ab","cd"};

declare array a of two strings "ab" and "cd"

String s = "foo";

declare string s; set to foo

Scanner in = new Scanner(System.in);

declares Scanner "in"

String s = in.nextLine();

declares and inputs a line (a string of characters)

double d = in.nextDouble();

declares and inputs a real value (floating point #)

int i = in.nextInt();

declares and inputs integer value

Variable declaration statement

declares the identifier and data type for a variable

Example of Input

import java.util.Scanner; public class My Program { public class static void main class (String[ ] args) { Scanner scan=new Scanner(System.in); String lastname; System.out.print("Enter last name"); lastname=scan.next() Systm.out.printlin('You entered" +lastname);

Import statement for libraries

import others java.util

Importing a Class from a Package

import packageName.ClassName;

import java.util.Scanner

imports Scanner library

key word abstract

in abstract class keyword abstract must be use for all of its methods

Graphics context

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

access modifiers

in method declaration: public, private, protected, default

++/--

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

\n

indicates a newline character

\t

indicates a tab character

Arguments

information passed to a method so it can perform its task

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

inherits it - regardless of package.

'final' reference variables must be ...

initialized before the constructor completes.

The 'transient' modifier applies only to ...

instance variables.

The 'volatile' modifier applies only to ...

instance variables.

CH11: This operator can be used to determine whether a reference variable references an object of a particular class.

instanceof

Objects

instances of a class that are made up of attributes and methods

G g = new G(); g.m();

instantiate object g of class G; run its method m

An 'abstract' class cannot be ...

instantiated.

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

int

Declare and define integer a from double, b.

int a = (int) b;

declare and define command line integer argument, a

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

declare a as an int

int a;

CH13: This is a key that activates a component just as if the user clicked it with the mouse.

mnemonic

'final' is the only ...

modifier available to local variables.

when writting multiple catch clauses you should always start with ______

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

CH13: This is the JList component's default selection mode.

multiple interval selection mode

StringBuffer

mutable character holder

StringBuilder

mutable java 5 character holder; not thread safe

ArrayList: add "hi"

myArr.add("hi");

ArrayList: add "hi" to ArrayList at index i

myArr.add(i,"hi");

ArrayList: check if list contains item

myArr.contains(item);

ArrayList: grab item at index i

myArr.get(i);

ArrayList: get first index of item

myArr.indexOf(item);

ArrayList: get last index of item

myArr.lastIndexOf(item);

ArrayList: delete item at index i

myArr.remove(i);

ArrayList: replace item at index i with new item

myArr.set(i, newItem);

ArrayList: get size

myArr.size();

HashMap: see if map contains a key

myMap.contains("key");

HashMap: get value string from key string

myMap.get("key");

HashMap: get a Set of the keys

myMap.keySet();

HashMap: insert a key string and a value string

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

HashMap: get a Collection of the values

myMap.values();

What's wrong with the following program? public class SomethingIsWrong { public static void main(String[] args) { Rectangle myRect; myRect.width = 40; myRect.height = 50; System.out.println("myRect's area is " + myRect.area()); } }

myRect is declared, but it is not instantiated or initialized. area() is not a method of Rectangle. getArea() is the public method.

Initialize a variable

n = 5;

Indentifier

name of a program component such as a class, or variable

Identifier

name of a variable, method or class

Length method

name.length()

Variables

named computer memory locations that hold values that might vary

final int VOLUME = 8

names constant integer

______\n______ is the escape sequence for

new line

Array Construction

new tymeName[length];

instantiation operator

new, third highest precedence, right to left association

/n

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

String input

next() nextLine()

String input = in.next();

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

byte input

nextByte()

double input

nextDouble()

float input

nextFloat()

int input

nextInt()

short input

nextShort()

null

no value

The term "instance variable" is another name for...

non-static field - instance variables are specific to an object

Program Comments

nonexecuting statements that are added to code for the purpose of documentation

Standard Output Device

normally the monitor

Primitive data types

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

AssertionError

object thrown when assertion is untrue

Method call

object.methodName(parameters);

Integer.parseInt or Double.parseDouble

obtains the integer value of a string containing the digits

Logic Error

occurs when a program compiles successfully but produces an error during execution

Java

oject oriented language

A class can extend only ...

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

Interfaces can extend ...

one or more other interfaces.

All instances shares ...

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

/** */

opening comments

{ }

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

( )

opening/closing parentheses; used in a method header

*

operator for multiplication

-

operator for subtraction

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

optional in any combination.

How to define a class?

public class "class name" (no extension)

The Basic form of a Java Class

public class <name> { <method> <method> ... <method> }

How can this interface be correctly implemented? public interface TestInterface { public boolean errorState(); }

public class ClassX implements TestInterface{ public boolean errorState() { return false; } } An object can act as any interface it implements. and public class ClassX implements TestInterface{ private boolean errorState() { return false; } } An object can also act as any of its superclasses.

first line of program, HelloWorld

public class HelloWorld

Enum: Instantiate Enum for days of the week

public enum Day{ Monday(0),Tuesday(1), Wednesday(2), Thursday(3),Friday(4),Saturday(5),Sunday(6); private int value; private Day(int v){value = v;} public int getValue(){return this.value;} } //values() returns array of all constants defined in enum // valueOf() returns Enum with name matching to String passed to valueOf // Day.name() returns string name of enum

Classes can have only ...

public or default access.

Build a return method

public return

str.length()

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

Constants declaration

public static final NAME = value;

How do you make a main method?

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

main loop

public static void main (String[] args)

Standard Starting, to start code block?

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

Main Method

public static void main(String[] args) { } Required to create an executable Java program.

How do you create a method?

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

Build a void method

public void main

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

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

what access modifiers can be used for top level classes

public, abstract and final can be used for top level classes

Members can use all four access levels:

public, protected, default, private.

" "

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

(int) ((Math.random() * 10) + 1)

random integer between 1 and 10

'final' variables cannot be ...

re-initialized once assigned a value.

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

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

thread states

ready, running, waiting and dead states

java SentinelDemo < numbers.txt

redirects input

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

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

s.replace("a","b");

replace instances of value "a" with "b" in string s

str.charAt(pos)

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

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

restricts input to only letters, removes punctuation and numbers

console.nextDouble():

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

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

return

The return Statement

return expression;

return volume;

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

void

return type in method declaration. You are not returning anything from the method or the class if it is in main method.

/r

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

package

set of java programs together in same directory

How does a program destroy an object that it creates?

set the value to null

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

setDate(int, int);

CH13: You can use this method to make a text field read-only.

setEditable

CH13: This method is inherited from JComponent and changes the appearance of a component's text.

setFont

CH13: This method can be used to store an image in a JLabel or a JButton component.

setIcon

CH13: You use this method to place a menu bar on a JFrame.

setJMenuBar

CH13: This method sets the intervals at which major tick marks are displayed on a JSlider component.

setMajorTickSpacing

Naming standard for mutator method?

setXYZ();

mutator

sets a property

Procedures

sets of operations performed by a computer program

char newChar = (char)(mychr + x)

shift character by x numbers (use ASCII table values)

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

short

double ampersand.

short circuit "and" operator

double vertical line

short circuit "or" operator

//comment

short comments

Program Statements

similar to English sentences; they carry out the tasks that programs perform

Math.sin(x)

sine of x (x in radians)

programming vs natural languages

size, rigidity, literalness

String: get char at index i

str.charAt(i);

String: get first index of substring

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

String: get last index of substring

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

String: get substring "He" from "Hello"

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

String: remove whitespace

str.trim();

String: concatenate two strings

str1.concat(str2); str1 + str2;

String: compare two strings

str1.equals(str2)

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

structure for commenting before methods (javadoc)

CH11: In an inheritance relationship, this is the specialized class.

subclass

A 'final' class cannot be ...

subclassed.

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

subclasses are involved.

'private' members are not visible to ...

subclasses, so private members cannot be inherited.

-=

subtract and assign operator

CH11: This key word refers to an object's superclass.

super

CH11: The following is an explicit call to the superclass's default constructor.

super();

CH11: In an inheritance relationship, this is the general class.

superclass

Common behavior can be defined in a ___ and inherited into a ___ using the ___ keyword.

superclass, subclass, extends

Inheritance

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

Java API

the application programming interface, a collectionof information about how to use every prewritten Java class

Attributes

the characters that define an object as part of a class

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

the code in the same class.

Object Oriented

you can define objects using the Class construct. Example: JAVA, C++

The ___ statement allows for any number of possible execution paths.

switch

How do you make a Switch statement?

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

Switch statement

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

_______\t________ is the escape sequence

tab

Math.tan(x)

tangent of x

class

template for instantiating objects

Class

term that describes a group or collection of objects with common properties

throws FileNotFoundException

terminates main if FileNotFoundException occurs

for (initialization; condition; update) { statements }

terminating loop

false

the = operator and the == operator perform the same operation

Linking

the Action of Bringing in Already Written Code(Libraries) for Use in a New Program.

Compliling

the Action of Turning the Source Code into a Format the Computer Can Use

CH13: This is text that appears in a small box when the user holds the mouse cursor over a component.

tool tip

boolean

true or false

Boolean expression

true/false literals

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

try & catch

CH12: You can think of this code as being "protected" because the application will not halt if it throws an exception.

try block

stack

type of java memory. faster. primitive objects, depending on their context, maybe stored in stack or heap

heap

type of java memory. slower more dynamic. Complex objects are always stored in heap

Variable definition

typeName variableName = value;

double blah = (int) (blah + 3)

typecast; change variable type

CH12: These are exceptions that inherit from the Error class or the RuntimeException class.

unchected exceptions

how to get tread dump

unix command

"final" modifier

use "final" to create a constant. The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change. For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter): static final double PI = 3.141592653589793;

No classes instances are needed in order to ...

use 'static' members of the class.

Escape character (\)

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

superclass

used in inheritance, it is a class from which subclass inherits variables and methods

subclass

used in inheritance, it is a class that inherits variables and methods from its supper class

Import Statement

used to access a built-in Java class that is contained in a package

Relational or logical operators

used to compare primitive values

JFrame

used to show a frame(window)

()

used to surround perimeters

escape character

used when including 'special characters' in string literals

run-time errors

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

variable declaration statement

when a program declares the type of a variable

Run-Time-Error

when a programcompiles successfully but does not execute

syntax errors

when a syntax rule is violated

false

when an if statement is nested in the else clause of another statement, the only time the inner if statement is executed is when the boolean expression of the outer if statement is true

true

when an if statement is nested in the if clause of another statement, the only time the inner if statement is executed is when the boolean expression of the outer if statement is true

logic errors

when the computer is unable to express an answer accruately

Semantic Errors

when the correct word in the wrong context is used in program code

void

when used in a method header, indicates that the method does not return any value when it is called

Reasons to use comments

where un-obvious coding is performed. next to a variable declaration. Beginning at the Program.

while (cond) { }

while "cond" block syntax

The while Statement

while (condition) statement;

How do you write an infinite loop using the while statement?

while (true) { //do something }

while

while (true) { }

keywords

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

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

writes output to a file "output.txt"

Low-Level Programming Language

written to correspond closely to a computer processor's circuitry, a programming language that a computer can interpret quickly but that bears little resemblance to human language.

import x.y.z

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

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

x = x + 3;

What is the last value that is sent to standard out for x in the given code segment? int x=0; do{ x=x+2; System.out.println("x: " + x); }while(--x<5);

x: 6 The do while statement will increment x by 2 each time through the loop, and then, before it checks the while condition, it will first decrement it by 1.

Math.pow(x,y)

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

Block statement

{ statement; statement; }

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

{ } (braces, or curly brackets)

Program development Cycle

• Design a solution to a problem (design a program) • implement the solution (code the program ) • Test the solution (test the program) • Fix the solution (debug the program)


संबंधित स्टडी सेट्स

N400, PrepU for Ch 25 (Health Assessment)

View Set

CH 27 (Heat Treatment of Metals), Metal casting processes, CH 8 Multiple Choice Q's, Fundamentals of metal casting, Chapter 18, CH 15 Multiple Choice Q's, CH 18: Fundamentals of Metal Forming, Chapter 16: Powder Metallurgy

View Set

Chp 43 PrepU Loss, Grief, and Dying

View Set

Chapter 7 Audio music media Talk Across Media

View Set

Entrepreneurship Final Exam Review

View Set

EDS500 Chapter 2: Integration, Inclusion, and Support of Positive Outcomes

View Set

Ch 11 vital signs - objectives and key terms

View Set

Fluid and Electrolytes + 4 Categories of Diuretics

View Set