Java
Pass by value
- Primitive types - makes a copy so does not affect original
Numeric Data Sub-Types
int, long, float, double
int
9. Variables used to store integer values should be declared with keyword ________.
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
Integer
unsigned int, 0 -> 2^31 -1
stop
Debugger command that sets a breakpoint at the specified line of executable code.
run
Debugger command to begin executing an application with the Java debugger.
Long
unsigned long
jump
up and down
break mode
Debugger mode the application is in when execution stops at a breakpoint.
-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.
String mutation example to put into Java
Even though we can't change String value or length, several methods of the String class return new String objects that are modified versions of the original
Events
Every action creates an event on Event Dispatch Thread. Actions = button click, mouse over etc.
The string class
Every character string (enclosed in double quotation characters) is an object in Java defined by the String class Every character string can be used to create a string object Because strings are so common, we don't have to use the new operator to create a String object (special syntax that works only for strings) String name1 = "Steve Jobs"; It is equivalent to String name1 = new String("Steve Jobs");
Predefined Java classes
Example of 2: Object class & String class
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
Throwing & Catching Exceptions
Exceptions can be thrown either by the Java API or by your code. To throw an exception examples: throw new Exception(); throw new Exception("Some message goes here"); throw new LoginFailedException("User not authenticated"); Once an exception is thrown, the JVM starts looking for a handler in the call stack to transfer execution of the program. Exception handlers are declared in the context of a try/catch block. Catching Exceptions Java supports the catching of exceptions in what's known as a try/catch block or also known as a try/catch/finally block. Syntax for a try/catch block: try { ... } catch (SomeException e) { ... } The interpretation of the try/catch block is the following: the statements between the try and catch are executed sequentially, and if no exception occurs, then execution continues with the first statement that follows the try/catch block. On the other hand, if an exception occurs while executing the statements between the try/catch, execution transfers to the catch block, and then once the catch block finishes executing, execution continues with the first statement after the try/catch block.
The JOptionPane dialog icon typically used to caution the user against potential problems is the ____.
Exclamation point
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)
comment (//)
Explanatory text that is inserted to improve an application's readability.
Argument
Extra information sent to a program.
redundant parentheses
Extra parentheses used in calculations to clarify the order in which calculations are performed. Such parentheses can be removed without affecting the results of the calculations.
Accessor
Extracts information from an object without changing it. Usually prefixed with 'get'.
Decrementing
The process of subtracting 1 from an integer.
compiling
The process that converts a source code file (.java) into a .class file.
bounds property
The property that specifies both the location and size of a component.
horizontalAlignment property
The property that specifies how text is aligned within a JLabel is called:
editable property
The property that specifies the appearance and behavior of a JTextField (whether the user can enter text.)
icon property
The property that specifies the file name of the image displayed in a JLabel.
horizontalAlignment property
The property that specifies the text alignment in a JTextField (JTextField.LEFT, JTextField.CENTER, or JTextField.RIGHT).
text property
The property that specifies the text displayed by a JLabel.
location property
The property that specifies where a component's upper-left corner appears on the JFrame.
Problem Solving
The purpose of writing a program is to solve a problem The key to designing a solution is breaking it down into manageable pieces An object-oriented approach lends itself to this kind of solution decomposition We will dissect our solutions into pieces called classes (.java files) We design separate parts (classes) and then integrate them
Syntax
The rules of a language that define how we can combine symbols, reserved words, and identifiers to make a valid program -Identifiers cannot begin with a digit -Curly braces are used to begin and end classes and methods
Operator Precedence
The rules that govern the order in which operations are done.
Semantics
The semantics of a program statement define what that statement means (its purpose or role in a program) A program that is syntactically correct is not necessarily logically (semantically) correct A program will always do what we tell it to do, not what we meant to tell it to do
Token:
The smallest individual unit of a program written in any programming language.
String Concatenation
The string concatenation operator (the plus symbol) is used to append one string to the end of another. In the case of a long string, you must use concatenation to break it across multiple lines.
program control
The task of executing an application's statements in the correct order.
functionality
The tasks or actions an application can execute.
setText
The text on a JLabel is specified with _____.
JCheckBox text
The text that appears alongside a JCheckBox.
Sequence, selection and repetition
The three types of program control are _____.
countryName = countryName.trim();
The trim method returns the string with all white space at the beginning and end removed.
.java file
The type of file in which programmers write the Java code for an application.
.class file
The type of file that is executed by the Java Runtime Environment (JRE). A ____ file is created by compiling the application's .java file.
Use a remainder assignment operator to make c=3 when c=12
c%=9
Use a multiplication assignment operator to make c=8 when c=2
c*=4
Use a subtraction assignment operator to make c=5 when c=7
c-=2
Syntax rules:
determine the validity of instructions in a programming language.
System.out.println("fun\tny"); prints out
fun ny
System.out.println("funny"); prints out
funny
Collection Interface
general abstraction for a collection of objects. It provides a handful of methods that operate over all interfaces that extend Collection. <<interface>> Collection +add(E) : boolean +addAll(Collection) : boolean +clear() : void +contains(Object) : boolean +containAll(Collection) : boolean +isEmpty() : boolean +remove(Object) : boolean +size() : int Java API does not provide any direct class implementations of interface Collection. Instead, implementations are provided for interfaces that extend Collection, namely, List, Set, and Queue. Nevertheless, the Collection interface is often used to pass collections around since it represents the base behavior of all collections. We'll now take a look at List, Set, and Queue and see how they might be used in our Library application.
A classification hierarchy represents an organization based on _____________ and _____________.
generalization and specialization
Accessor instance method names typically begin with the word "____" or the word "____" depending on the return type of the method. 1. set, is 2. get, can 3. set, get 0% 4. get, is
get, is
Naming standard for accessor method?
getABC();
array.length
gives the length of the array (no parentheses!)
declare and initial int array, number, with length N
int[] number = new int [N];
Benefits of Refactoring
- Reduces maintenance problems - Reduces probability of errors - Reduces duplicated code.
Software Patterns
- Reusable solution to common problem. - Description/Template
Abstraction (extend)
- Segregation of implementation from interface. - cannot be instantiated - Partial implementation - Class can only extend one abstract class
Starvation
- Some threads allowed to be greedy and others starved of resources, making no progress So some of the philosophers eat everything others get nothing.
Local Repository
- Stored on local computer. - Individual checks out version from Version database.
Observer Pattern
- Synchronises state and/or responses across a collection of objects in response to an event. - Have Observer and Subject - Observer queries Subject to determine what was the change of state and responds appropriately based on Subjects new state. - Subject adds observers, sets state and gets state.
Livelock
- Thread acts in response to another thread, makes no progress but is not blocked - Thread states can and do change but no progress can be made - think of corridor dance example Philosophers pass fork back and forth but no one gets to eat.
JButton component
A component that, when clicked, commands the application to perform an action.
JLabel component
A component used to describe another component. This helps users understand a component's purpose.
Loop-Continuation Condition
A condition used in a repetition statement (such as while) that repeats only while the statement is true.
Constant
A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence As the name implies, it is constant and cannot be changed The compiler will issue an error if you try to change the value of a constant In Java, we use the final modifier to declare a constant final int NUM_SEASONS = 4; whenever you use the reference variable, NUM_SEASONS, it will equal 4 Constants are useful for three important reasons First, they give meaning to otherwise unclear literal values Example: MAX_LOAD means more than the literal 250 Second, they facilitate program maintenance If a constant is used in multiple places, its value need only be set in one place Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers
format
DecimalFormat method that *takes a double*, *returns a String* containing a *formatted number*.
type[] [] name
Declare a 2D array
Why is the method "main" Declared static?
This allows the JVM to invoke "main" without creating an object of the class
Loop
This causes a computer program to return to the same place more than once.
Escape Character
This character (\) allows you to form escape sequences.
Exception
This class indicates issues that an application may want to catch. A subclass of the class Throwable.
multiplication operator
This operator is an asterisk (*), used to ____ its two numeric operands.
% (remainder operator)
This operator yields the remainder after division.
assignment operator
This operator, =, copies the value of the expression on the right side into the variable.
if statement
This single-selection statement performs action(s) based on a condition.
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).
==
Used to equal a value
JDBC (Java Database Connectivity)
Used to interface DBMS and Java code. - Gives database vendor independence. - Java gives platform dependence Allows: 1. Making connection to database 2. Creating SQL or MySQL statements 3. Executing SQL or MySQL queries to database 4. Viewing and modifying the resulting records.
Semicolon
Used to separate sections.
Comma
Used to separate things within a section.
ResultSet (JDBC)
Used to store the result of an SQL query. // get all current entries ResultSet rs = select.executeQuery(); // use metadata to get the number of columns int columnCount = rs.getMetaData().getColumnCount(); // output each row while (rs.next()) { for (int i = 0; i < columnCount; i++) { System.out.println(rs.getString(i + 1)); }
Variables
Used to store values that can be used repeatedly in a class
JTextField.CENTER
Used with setHorizontalAlignment to center align the text in a JTextField.
JTextField.LEFT
Used with setHorizontalAlignment to left align the text in a JTextField.
JTextField.RIGHT
Used with setHorizontalAlignment to right align the text in a JTextField.
The comparing method: equals(Object)
Using equals(Object): boolean areEqual = book1.equals(book2); It compares object references, compares to see if book1 and book2 reference the same Book object in memory. In the example above, book1 and book2 reference different Book objects, so the boolean variable areEqual is set to false. This one would be true: Book book1 = new Book(); Book book2 = book1; boolean areEqual = book1.equals(book2);
How do you declare a CONSTANT in Java?
Using the keyword "final": final float pi = 3.14159f;
What are the three ways to call a method?
Using the method name itself within the same class Using the object's variable name followed by a dot (.) and the method name to call a non static method of the object. Using the class name and a dot(.) to call a static method of a class: Math.pow
blank.
Value
This type of method method performs a task and sends a value back to the code that called it.
Value-returning
This type of method method performs a task and sends a value back to the code that called it. A. Local B. Void C. Complex D. Value-returning
Value-returning
argument
Values inside of the parentheses that follow the method name in a method call are called ____(s).
parameter
Variable passed to a method that provides more information for the method.
double
Variable type that is used to store floating-point numbers.
Which of the following is NOT an actual parameter? 1. Expressions used in a method call 2. Constant values used in a method call 3. Variables used in a method call 4. Variables defined in a method heading
Variables defined in a method heading
Thread safe variables
Variables that belong to only one thread. - Local variables are thread safe! - Instance and static variables are not thread safe
Constants
Variables that do not change in value; typed in all-caps.
'
\'
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
Pseudocode
____ is an artificial and informal language that helps programmers develop algorithms.
Program control
____ refer(s) to the task of executing an application's statements in the correct order.
short hand a = a * n
a *= n;
short hand a = a + n;
a += n;
short hand a = a - n;
a -= n;
1. Create an Array called 'number' w/ 3 slots 2. Write out the 2nd number
int[] numbers = new int[3];
" "
quotation marks; encloses a string of characters, such as a message that is to be printed on the screen
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is visible in method one? 1. x (block three's local variable) 2. local variables of method two 3. rate (before main) 4. one (method two's formal parameter)
rate (before main)
What is the class before the keyword, extends called? the one after?
subclass Superclass
-=
subtract and assign operator
Maps
supports the ability to add and retrieve items from a collection using a key value pair. The key (K) is the lookup identifier and the value (V) is the item being looked up. The methods for inserting/retrieving items in/out of the Map are put(...) and get(...). General accounts - For general public use. Business accounts - For commercial organizations. Nonprofit accounts - For nonprofit organizations. The above account types can be abstracted as a Java enum (enumerator): enum AccountType {general, business, nonprofit}; Each user is allowed to have one account of each type. Accounts for a given user could be contained in a Map data structure where the key for each account is one of the above enum values (general, business, or nonprofit) as shown below: Account generalAccount = new Account(); Account businessAccount = new Account(); Account nonprofitAccount = new Account(); //... Map<AccountType, Account> accountsMap = new HashMap<AccountType, Account>(); accountMap.put(AccountType.general, generalAccount); accountMap.put(AccountType.business , businessAccount); accountMap.put(AccountType.nonprofit , nonprofitAccount); Retrieval of the accounts from the map is then achieved with the key: Account generalAccount = accountMap.get(AccountType.general); Account businessAccount = accountMap.get(AccountType.business); Account nonprofitAccount = accountMap.get(AccountType.nonprofit); In summary, the key is used to place values in the map and also to retrieve values from the same map. advantage, code readily accommodates additional account types. simply add to the enum type: enum AccountType {general, business, nonprofit, government, education};
How do you set up a switch method?
switch () Case #: (statement)(++acount) (break;) Case #: (statement) (break;) Case #: (statement)
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:
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is visible in block three? x (one's formal parameter) t (before main) z (before main) local variables of main
t (before main)
_______\t________ is the escape sequence
tab
Math.tan(x)
tangent of x
Escape character (\)
used in codes to represent characters that cannot be directly typed into a program
JFrame
used to show a frame(window)
()
used to surround perimeters
escape character
used when including 'special characters' in string literals
You cannot declare the same ____ name more than once within a block, even if a block contains other blocks.
variable
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
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is visible on the line marked // main block? 1. All identifiers are visible in main. 2. local variables of method two 3. w (before method two) 4. z (before main)
w (before method two)
run-time errors
when a computer is asked to do something that is considered illegal
What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] > value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 1, 3, 5, 7, 0, 0 } 2. { 1, 3, 5, 0, 0, 0 } 3. { 1, 3, 7, 5, 0, 0 } 4. { 5, 1, 3, 7, 0, 0 }
{ 1, 3, 5, 7, 0, 0 }
What must every method and class have an open and closed of?
{ } (braces, or curly brackets)
What does a contain after the following loop? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; for (int i = size; i > pos; i--) a[i - 1] = a[i]; size--; 1. {3, 7, 0, 0, 0, 0} 2. {0, 0, 0, 0, 0, 0} 3. {3, 7, 7, 0, 0, 0} 4. {1, 1, 1, 0, 0, 0}
{0, 0, 0, 0, 0, 0}
Redundant
1. Parentheses that are added to an expression simply to make it easier to read are known as ________ parentheses.
Mismanaged threads result in
1. Race Conditions 2. Deadlock 3. Starvation 4. Livelock
Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (size < capacity && value > 0) { a[size] = value; size++; 1. Reads one value and places it in the remaining three unused spaces in a. 2. Reads up to 3 values and places them in the array in the unused space. 3. Reads up to 3 values and inserts them in the array in the correct position. 4. Crashes at runtime because it tries to write beyond the array.
1. Reads one value and places it in the remaining three unused spaces in a.
Client/server programming (Daemon thread)
1. Server listens using daemon thread for each port 2. Request comes, daemon thread responds 3. Creates/calls another thread to do work 4. Worker thread terminates naturally 5. Daemon thread continues monitoring port
Subtype rules
1. Signature rule 2. Methods rule 3. Properties rule
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
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x += a[i]; System.out.println(x); 1. Sums the even elements in a. 2. Finds the largest value in a. 3. Finds the smallest value in a. 4. Counts the even elements in a.
1. Sums the even elements in a.
Test Driven Development (TDD)
1. Tests developed before code is written. 2. Once code passes, new tests added 3. Code extended to pass new tests and refactored if necessary. Create tests you know will fail because you know implementation not in place.
Version control principles
1. The Lock 2. The Merge
Valid Identifier
1. The name of a variable must be a ____.
The reference to an object that is passed to any object's nonstatic class method is called the ____. 1. this reference 2. magic number 3. literal constant 4. reference
1. This
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
setBackground
1. Use ___ to specify the content pane's background color.
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements replaces the first object in the collection with element? 1. a.set(0, element); 2. a.set(element, 0); 3. a.add(0, element); 4. a[0] = element;
1. a.set(0, element);
Methods that retrieve values are called ____ methods. 1. accessor 2. class 3. mutator 4. static
1. accessor
___________________ is one of the primary mechanisms that we use to understand the natural world around us. Starting as infants we begin to recognize the difference between categories like food, toys, pets, and people. As we mature, we learn to divide these general categories or classes into subcategories like siblings and parents, vegetables and dessert. 1. classification 2. encapsulation 3. specialization 4. generalization
1. classification
A(n) ____ method is a method that creates and initializes objects. 1. constructor 2. non-static 3. instance 4. accessor
1. constructor
You can use ____ arguments to initialize field values, but you can also use arguments for any other purpose. 1. constructor 2. field 3. data 4. object
1. constructor
The inside block, which is contained entirely within an outside block, is referred to as ____. 1. nested 2. out of scope 3. ambiguous 4. a reference
1. nested
Which of the following lines of code explicitly calls the toString() method, assuming that pete is an initialized Student object variable? 1. println(pete.toString()); 2. println("" + pete); 3. println(super.toString()); 4. println(pete)
1. println(pete.toString());
To call a superclass method from a subclass method, when both methods have the same name and signature, prefix the call to the superclass method with: 1. super 2. the name of the superclass (that is, Person, if that is the name of the superclass) 3. no prefix is necessary. You cannot call an overridden superclass method from the subclass method you've overridden. 4. this 5. base
1. super
At
10. When application execution suspends at a breakpoint, the next statement to be executed is the statement ____ the breakpoint.
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.
logic error
An error that does not prevent the application from compiling successfully, but does cause the application to produce erroneous results when it runs.
logic error
An error that does not prevent your application from compiling successfully but does cause your application to produce erroneous results.
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
syntax error
An error that occurs when code violates the grammatical rules of a programming language.
left operand
An expression that appears on the left side of a *binary operator*.
right operand
An expression that appears on the right side of a binary operator.
Mixed expression:
An expression that has operands of different data types.
operand
An expression that is combined with an operator (and possibly other expressions) to perform a task (such as multiplication).
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.
object
An individual instance of a class. An object can only exist during runtime.
pseudocode
An informal language that helps programmers develop algorithms.
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.
instance
An object.
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.
binary operator
An operator that requires two operands.
unary operator
An operator with only one operand (such as + or -).
Loop
Another general name for a repetition statement.
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
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
switch argument
Has to be an expression of type int, char, short or byte. Notably not float, double and long (too imprecise or large).
Types of Maps
HashMap: unordered, use for max speed TreeMap: ordered by key LinkedHashMap: inseretion ordered.
HashMap<String, String>: Instantiation
HashMap<String, String> myMap = new HashMap<String,String>();
Types of sets
HashSet<E>: unordered TreeSet<E>: ordered based on value LinkedHashSet<E> : insertion ordered
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).
The line of text that is added to a JTextArea to clarify the information that will be displayed in tabular format is called a _____.
Header
Consider the following declaration. int[] alpha = new int[3]; Which of the following input statements correctly input values into alpha? (i) alpha = cin.nextInt(); alpha = cin.nextInt(); alpha = cin.nextInt(); (ii) alpha[0] = cin.nextInt(); alpha[1] = cin.nextInt(); alpha[2] = cin.nextInt(); 1. Only (i) 2. Only (ii) 3. None of these 4. Both (i) and (ii)
Only (ii)
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.
The body of a while statement executes _____.
If it's condition is true
What compilation error should you be aware of when using arguments and parameters?
If the amount of arguments(maximum(a, b, c) does not match the amount of parameters(maximum( double x, double, y, double z, double d) this creates a compilation error
2
If the variable x contains the value 5, what value will x contain after the expression x -= 3 is executed?
Basic Program Execution
If there are errors the compiler will complain and not let us go onto the next step. We must trace back to the source and fix the problem in our code. It's important to understand why you're getting errors. LOOK IT UP debuggers can help you find errors in your code
What syntax error should you be aware of when entering parameters for a method?
If you set two variables as the same type, but don't use two type indentifiers then it creates a syntax error. You should always use a type identifier for each variable: double x, y = NO double x, double y = YES
What are the 3 selection statements? And the 3 Repetition Statements?
If, If...else, and Switch While, do...while, and for
Double
If... else is a ____-selection statement.
import java.util.Scanner;
Import the ability to use a scanner from database
The Main Method
In Java, everything goes in a class (object-oriented) After you compile the source code (.java) into a bytecode or class file (.class), you can run the class using the Java Virtual Machine (JVM) When the JVM loads the class file, it starts looking for a special method called main, and then keeps running until the code in main is finished
An action
In an activity diagram, a rectangle with curved sides represents _____.
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Where is identifier x (block three's local variable) visible? 1. In two and block three 2. In block three and main 3. In block three only 4. In one and block three
In block three only
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.
If you pass the first element of the array ar to the method x() like this, x(ar[0]); the element ar[0] :
cannot be changed by the method x()
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
\
char that comes after is exempted from compiler (ie printing "")
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'.
in.hasNextDouble()
checks for numerical input; false if the next input is not a floating-point number
Constructors have the same name as the ____. 1. data members 2. package 3. class 4. member methods
class
How do you start a program?
class (name of program) { //Your program goes here!! }
public class _____
class header; indicates a publicly accessible class named "_____"
How do you make a Hello World program?
class helloWorld { public static main (String[] args) { String hw = "Hello, World!"; System.out.println(hw); } }
Declaring a class to a package
class is declared to belong to a package by including a package statement at the beginning of the source file, it must be the first statement in the file: package mypackage; public class MyClass { ... } If package is not declared, the class will belong to the "default package". Not recommended for larger programs.
Instantiating an object
class name object name = classname();
Disadvantages of the the Lock (version control)
- Unnecessary serialisation of development steps - Programmers forget to release the lock - Doesn't consider dependencies between classes that may be out to different people at the same time.
not equal
!=
What package is the ArrayList part of?
" java.util package " The ArrayList class is part of the java.util package.
String combination identifier
"+"
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
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."
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
&&
What are LOGICAL operators of Java? What does each one mean?
&& which is the Conditional AND operator-Statement is only true when both conditions are true (true && true) | |-the Conditional OR operator-Statement is only true as long as one of the statements are true(true || false) (true || true) (false || true) & which is the Boolean logical AND operator-... | which is the boolean logical inclusive OR operator-... ^- the boolean logical exclusive operator OR -Statement is only true when one condition is false and one is true (true ^ false) (false ^ true) ! which is the logical NOT operator- does the same function as != except this operator comes before the statement (!(statement))
Logical Operators
&& ||
Integer value: 48
'0'
Integer value: 65
'A'
Integer value: 97
'a'
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.
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
Central Repository
- Version database stored on server. - Team checks out version from database. - Checkout = make local copy.
Generics
- accept another type as a parameter - collections <E> <X>
Benefits of Continuous Integration
- allow team detect problems early - reduce integration problems - increase visibility
Target (ANT)
- can depend on other targets - 'depends' specifies order targets should be executed.
Safely stop thread
- control loop with stopFlag - make sure stopFlag independent of other threads - check value frequently - use end() private volatile boolean stopflag; stopflag = false; //in run() try block: while (!stopflag) { d = Math.log(i++); sleep(1);} public void end() { stopflag = true;}
Encapsulation*
- data hiding - make fields in class private, accessible via public methods - protective barrier against outside code - access is controlled by interface - Alter code without affecting those that use it
Disadvantages of TDD
- difficult for programs with complex interactions with their environment e.g. GUI - Bad tests = bad code - if programmer write own code = blind spots - scalability debated.
Advantages of exceptions
- error handling is separated from normal code - allows different kind of errors to be distinguished
Unchecked exception
- errors and run time exceptions - result of programming errors AssertionError, VirtualMachineError, ArithmeticException, NullPointerException, IndexOutOfBoundsException
How do you create variables?
(A kind of variable) (name of the variable) = (value of variable); For example, String var = "Hello, World";
int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the value of num.length in the array above? 1. 0 2. 100 3. 99 4. 101
100
Reasons to use "double"
1023 digits after the decimal point
{ }
(Curly braces). Marks the beginning and end of a unit, including a class or method description.
Thread safety
- for GUIs use EventDispatch thread and SwingUtilities.invokeLater(new threadClass()) public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); SwingUtilities.invokeLater(new HelloWorldSwing());
Checked exception
- if can throw 'checked' exception must: 1. include exception handling code to catch exception or 2. Declare to its caller that it potentially throws exception
java.lang.Runnable
- implemented by classes that run on threads - implement instead of extending Thread Need a Thread wrapper - Thread one = new Thread(new HelloRunnable());
Timer
- implements Runnable - runs a TimerTask object on JVM background thread - so use to Schedule Tasks (threads) // set Timer as a daemon thread Timer timer = new Timer(true); timer.schedule(hello1, 1000); // will run after 1000 milisec timer.schedule(hello2, 2000);
Maps
- maps keys to values - can have duplicate keys - each key maps to one value
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
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
while
(i != TotalNum) { } // code in here
Applying Encapsulation*
- Make fields private - make accessors (getters) and mutators (setters) public - make helper (utility) methods private
Threads
- Multiple processes within a single program. - Executed in slices or parallel. - Based on a priority system : this thread before that thread - Separate units of a parent process that share the resources of the parent process
Cast
(typeName) expression
Sets
- No Duplicates - Usually unordered
Pass by reference
- Objects and arrays - Changes affect original as it is given access to the address not just a copy.
Synchronization
- Only allows one thread access at a time. - Sets a lock on the method or object - When synchronized method terminated, lock released - Places an overhead on execution time (Don't over use it)
What operator multiplies two numbers?
*
Software Layers and responsibilities
* Presentation Layer - rendering the user interface, responding to user event, creating and populating domain objects, and invoking the business layer. * The Business Layer - managing workflow by coordinating the execution of services located in the service layer. * The Service Layer - service interfaces and implementations, the movement of objects in and out of the application, and the hiding of technology choices. * The Domain Layer - abstracting domain objects (i.e., the nouns) as they appear in the problem space. Data types for: user interface ->> Presentation Layer; manage use case workflow ->>Business Layer; move objects in and out of application ->>Service Layer; abstract the "nouns" of problem space ->> Domain Layer
multiplication operator
*, fourth highest precedence, left to right association
Preincrement
++counter
addition operator
+, fifth highest precedence, left to right association
unary plus operator
+, third highest precedence
Interfaces (implement)
- Abstract methods. All methods are public. - Cannot be instantiated. - Class that 'implements' an interface inherits its abstract methods.
Event Adapters
- Adapter = Design Pattern - Each Listener has a corresponding Adapter abstract class
Atomic Swing Components
- Basic Controls JButton, JComboBox, JList, JMenu, JSlider, JSpinner, JTextField - Uneditable Displays JLabel, JProgressBar - Interactive Displays JColorChooser, JFileChooser, JTable, JTextArea, JTree
Deadlock
- Blocked waiting for a resource held by another blocked thread - all philosophers pick up the left fork at the same time before any can pick up the right fork - No progress possible.
Top Swing Level
- Can appear anywhere on desktop. - Serve as root of containment hierarchy, all others must be contained in top lvl container - have content pane - can have menu bar added JFrame, JDialog, JApplet
Disadvantages of Centralised Servers
- Central point of failure - Latency if remote - Inaccessibility if off-line
Collections
- Compound data type that groups multiple elements of the same type together. - Encapsulates the data structure needed to store the elements and the algorithms needed to manipulate them. - Group of elements of the same type
Race Conditions
- Concurrent access problem - outcome depends on which thread gets to a value first - Results in asynchronous changes = can't predict variables affected by threads - Shared variables need 'volatile' keyword
JPanel
- Contain parts of UI - Can contain other JPanels - Contain multiple different types of components.
The Merge (version control)
- Copy-modify-merge - Harry and Sally access at same time, both edit, Sally publishes first and Harry receives 'out-of-date' error. - Version control system performs diff operation and identifies conflicts. - Manual intervention required if conflicts. - Harry has to compare latest version with his own, creates merge and publishes merge.
GIT
- Distributed version control. - Snapshot based = takes snapshot of each version. - Uses checksums to identify changes to files.
The Lock (version control)
- Lock-modify-unlock - When Harry accesses file he LOCKS it, reads/edits then releases lock. Sally then LOCKS it and does the same. - Only 1 person can access file at time!
Checkout
- Make a local copy of code/file. - Checkout from Version Database.
Object lock (synchronization)
- must be final, otherwise could change and dif threads synchronize on dif objects private final static Object sharedLock = new Object(); public static void displayMessage(JumbledMessage jm) throws InterruptedException { synchronized(sharedLock) { for (int i = 0; i < jm.message.length(); i++) { System.out.print(jm.message.charAt(i)); Thread.currentThread().sleep(50); } System.out.println();}}
Java
- object oriented - architecture neutral - portable - fast -secure -network aware - syntax based on C and C++
Queues
- ordered sequence of elements - access via endpoints - structures for LIFO and FIFO
Lists
- ordered sequence of elements - indexable by individual elements or range - elements can be insereted at or removed from any position - can have duplicates
final
- prevents class from being extended or overridden - prevents variables from being altered = constant
ANT
- specifies how to build something. - require configuration file build.xml - A depends on B means that B needs to occur before A. - if B compiled then A will compile immediately.
volatile
- thread goes straight to source and doesn't locally ache - ensuring working with up to date data "Go back and check" - reduce concurrent thread access issues. private volatile boolean pleaseStop; while (!pleaseStop) { // do some stuff... }
Instance variables
- variables inside class but not in methods - instantiated when class loaded - accessed by any method in class
subtraction operator
-, fifth highest precedence, left to right association
unary minus operator
-, third highest precedence
Predecrement
--counter
LinkedList: add item to beginning of list
-addFirst(item);
method selector operator
., second highest precedence, left to right association
Defining Parameters
...
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
...
This method is present in all exceptions, and it displays a detailed error message describing what happened.
.getMessage() method
What operator divides two numbers?
/
division operator
/, fourth highest precedence, left to right association
What symbols are used to make comments in Java? (Both single and block comments)
// and /* */
numChars = name1.length();
// returns the number of characters name1 contains
How do you make a comment?
//Comment /*Multi-Line Comment*/ /**JavaDoc Comment *Describes Program or *Method **/
Which of the following about Java arrays is true? (i) Array components must be of the type double. (ii) The array index must evaluate to an integer.
Only (ii)
Which of the following creates an array of 25 components of the type int? (i) int[] alpha = new[25]; (ii) int[] alpha = new int[25];
Only (ii)
What does the following loop print? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = a[0]; for (int i = 1; i < len; i++) if (a[i] < x) x = a[i]; System.out.println(x); 1. 36 2. 12 3. 1 4. 6
1
double[] as = new double[7]; double[] bs; bs = as; How many objects are present after the code fragment above is executed? 1. 2 2. 14 3. 1 4. 7
1
int[] hit = new hit[5]; hit[0] = 3; hit[1] = 5; hit[2] = 2; hit[3] = 6; hit[4] = 1; System.out.println(hit[1 + 3]); What is the output of the code fragment above? 1. 1 2. 5 3. 6 4. 3
1
random number between 1 and n
1 + Math.random() * n;
3 different groups of patterns
1. Creational: managing the creation of objects 2. Structural: provide a more workable interface for client code. 3. Behavioural: managing common interactions
byte
1 byte, stores an integer
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.
What does the following loop print? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = a[0]; for (int i = 1; i < len; i++) if (a[i] < x) x = a[i]; System.out.println(x); 1. 1 2. 12 3. 6 4. 36
1. 1
int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; How many components are in the array above? 1. 100 2. 0 3. 50 4. 99
1. 100
What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 5; for (j = 1; j < 5; j++) { if (j % 2 == 0) alpha[j] = alpha[j - 1] + 2; else alpha[j] = alpha[j - 1] + 3; } 1. 13 2. 15 3. None of these 4. 10
1. 13
double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} How many rows are in the array above? 1. 4 2. 0 3. 2 4. 3
1. 4
int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the index number of the last component in the array above? 1. 99 2. 100 3. 0 4. 101
1. 99
.java
1. A source code file has the ____ extension.
Event loop
1. Action (button click, mouse movement...) registered generating event that can be tracked 2. Event passed to affected component, 3. Listen for Event 4. Respond to Event.
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
How many constructors can a class have? 1. Any number 2. 2 3. 1 4. 0
1. Any number
What are the rules for forming a structured program?
1. Begin with the simplest activity diagram { @->(action state)->(@)} 2. Any action state can be replaced by two action states in sequence. (A.K.A stacking rule) 3. Any action state can be replaced by any control statement. (A.K.A the nesting rule) 4. Rules 2 and 3 can be applied as often as you like and in any order.
Suppose you have the following declaration. char[] nameList = new char[100]; Which of the following range is valid for the index of the array nameList. (i) 1 through 100 (ii) 0 through 100 1. Both are invalid 2. Only (i) 3. None of these 4. Only (ii)
1. Both are invalid
Black box Steps
1. Considered input and output values 2. Partition inputs and outputs into ranges 3. For each equivalence class produce a) set of typical test that cover normal cases b) set of boundary value tests at or around the extreme limits of the equivalence class
TDD Mantra
1. Create new tests that fail (RED) 2. Write code to pass the test (GREEN) 3. Refactor
Interface rules
1. Exceptions should be declared by interface method. 2. Signature and return type should be the same for interface and implemented class. 3. A class can implement multiple interfaces. 4. An interface can extend another interface.
Refactoring Techniques
1. Extract Method 2. Extract Class 3. Rename 4. Move class 5. Replace conditional with Polymorphism 6. Decompose conditional 7. Encapsulate collection 8. Replace error code with exception 9. Split Loop
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] < a[x]) x = i; System.out.println(x); 1. Finds the position of the smallest value in a. 2. Sums the elements in a. 3. Finds the position of the largest value in a. 4. Counts the elements in a.
1. Finds the position of the smallest value in a.
An object is a(n) ____ of a class. 1. instance 2. method 3. field 4. constant
1. Instance
Describe 2 classes can have.
1. Is a - inheritance 2. Has a - composition / aggregation V47
4 heavyweight Swing components
1. JFrame 2. JWindow 3. JDialog 4. JApplet
Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (value > 0) { a[size] = value; size++; value = cin.nextInt(); } 1. May crashe at runtime because it can input more elements than the array can hold 2. Reads up to 3 values and inserts them in the array in the correct position. 3. Reads one value and places it in the remaining first unused space endlessly. 4. Reads up to 3 values and places them in the array in the unused space.
1. May crashe at runtime because it can input more elements than the array can hold
Levels of synchronization
1. None 2. Class methods only (ensure class variables thread safe) 3. Class and Instance methods - protect integrity of all fields - allow different threads share objects - all fields protected from simultaneous access and modification
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 1; if (j > 2) alpha[j - 1] = alpha[j] + 2; } 1. None of these 2. alpha = {1, 2, 3, 4, 5} 3. alpha = {1, 5, 6, 7, 5} 4. alpha = {4, 5, 6, 7, 9}
1. None of these
If a class's only constructor requires an argument, you must provide an argument for every ____ of the class that you create. 1. object 2. type 3. parameter 4. method
1. Object
Suppose you have the following declaration. double[] salesData = new double[1000]; Which of the following range is valid for the index of the array salesData. (i) 0 through 999 (ii) 1 through 1000 1. Only (i) 2. None of these 3. Both are invalid 4. Only (ii)
1. Only (i)
Consider the following statements. public class Circle { private double radius; public Circle() { radius = 0.0; } public Circle(double r) { radius = r; } public void set(double r) { radius = r; } public void print() { System.out.println(radius + " " + area + " " + circumference()); } public double area() { return 3.14 * radius * radius; } public double circumference() { return 2 * 3.14 * radius; } } Assume, also that you have the following two statements appearing inside a method in another class: Circle myCircle = new Circle(); double r; Which of the following statements are valid (both syntactically and semantically) in Java? (Assume that cin is Scanner object initialized to the standard input device.) (i) r = cin.nextDouble(); myCircle.area = 3.14 * r * r; System.out.println(myCircle.area); (ii) r = cin.nextDouble(); myCircle.set(r); System.out.println(myCircle.area()); 1. Only (ii) 2. Both (i) and (ii) 3. Only (i) 4. None of these
1. Only (ii)
int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the value at index 10 of the array above?
10
What is the output of the following Java code? int[] alpha = {2, 4, 6, 8, 10}; int j; for (j = 4; j >= 0; j--) System.out.print(alpha[j] + " "); System.out.println();
10 8 6 4 2
Picture elements
10. Pixels are ____.
10. The debugger command ________ allows you to "peek into the computer" and look at the value of a variable.
Reasons to use "float"
127 digits after the decimal point
What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 5; for (j = 1; j < 5; j++) { if (j % 2 == 0) alpha[j] = alpha[j - 1] + 2; else alpha[j] = alpha[j - 1] + 3; } 1. None of these 2. 13 3. 15 4. 10
13
char[][] array1 = new char[15][10]; What is the value of array1.length? 1. 15 2. 0 3. 2 4. 10
15
short
16 bit integer
char
16 bit unicode character
short
16 bit, useful if memory an issue
What will be returned from the following method? public static double methodA() { double a = 8.5 + 9.5; return a; }
18.0
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
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
What does the following loop print? int[] a = {6, 1, 9, 5, 12, 7}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x++; System.out.println(x); 1. 4 2. 22 3. 18 4. 2
2
short
2 bytes, stores integer values
Assuming a=3, the values of a and b after the assignment b=a-- are _____.
2, 3
Suppose that sales is a two-dimensional array of 10 rows and 7 columns wherein each component is of the type int , and sum and j are int variables. Which of the following correctly finds the sum of the elements of the fifth row of sales? 1. sum = 0; for(j = 0; j < 10; j++) sum = sum + sales[5][j]; 2. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[4][j]; 3. sum = 0; for(j = 0; j < 10; j++) sum = sum + sales[4][j]; 4. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[5][j];
2. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[4][j];
What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; for (j = 4; j >= 0; j--) { alpha[j] = j + 5; if (j <= 2) alpha[j + 1] = alpha[j] + 3; } 1. 8 2. 10 3. 9 4. 5
2. 10
char[][] array1 = new char[15][10]; What is the value of array1[3].length? 1. 15 2. 10 3. 2 4. 0
2. 10
What is the value of alpha[4] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 2; for (j = 1; j < 5; j++) alpha[j] = alpha[j - 1] + 3; 1. 11 2. 14 3. 5 4. 8
2. 14
char[][] array1 = new char[15][10]; How many dimensions are in the array above? 1. 3 2. 2 3. 1 4. 0
2. 2
public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } How many constructors are present in the class definition above? 1. 3 2. 2 3. 1 4. 0
2. 2
Assume that two arrays are parallel. Assume the first array contains a person's id number and the second contains his or her age. In which index of the second array would you find the age of the person in the third index of the first array? 1. 2 2. 3 3. 1 4. It cannot be determined from the information given.
2. 3
int[] hits = {10, 15, 20, 25, 30}; copy(hits); What is being passed into copy in the method call above? 1. 10 2. A reference to the array object hits 3. The value of the elements of hits 4. A copy of the array hits
2. A reference to the array object hits
How many constructors can a class have? 1. 2 2. Any number 3. 1 4. 0
2. Any number
public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } Which of the following statements would you use to declare a new reference variable of the type Illustrate and instantiate the object with a value of 9 for the variable x? 1. Illustrate.illObject(9); 2. Illustrate illObject = new Illustrate(9); 3. Illustrate illObject(9); 4. illObject = Illustrate(9);
2. Illustrate illObject = new Illustrate(9);
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int z = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Where is identifier z (block three's local variable) visible? 1. In block three and main 2. In block three only 3. In two and block three 4. In one and block three
2. In block three only
Methods that require you to use an object to call them are called ____ methods. 1. accessor 2. instance 3. internal 4. static
2. Instance
The RGB values of Color.RED
255, 0, 0
The toString() method is automatically inherited from the __________________ class. 1. GObject 2. Object 3. java.lang 4. Root 5. Component
2. Object
Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following statements are valid in Java? (Assume that cin is Scanner object initialized to the standard input device.) (i) bigRect.length = cin.nextDouble(); bigRect.width = cin.nextDouble(); (ii) double l; double w; l = cin.nextDouble(); w = cin.nextDouble(); bigRect.set(l, w); 1. Only (i) 2. Only (ii) 3. Both (i) and (ii) 4. None of these
2. Only (ii)
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x += a[i]; System.out.println(x); 1. Counts the even elements in a. 2. Sums the even elements in a. 3. Finds the largest value in a. 4. Finds the smallest value in a.
2. Sums the even elements in a.
/
2. The ________ operator performs division.
Compiler
2. The __________ converts a .java file to a .class file.
Which of the following is used to allocate memory for the instance variables of an object of a class? 1. the reserved word public 2. the operator new 3. the operator + 4. the reserved word static
2. The operator new
Which of the following statements is NOT true? 1. Reference variables contain the address of the memory space where the data is stored. 2. The operator new must always be used to allocate space of a specific type, regardless of the type. 3. Reference variables do not directly contain the data. 4. A String variable is actually a reference variable of the type String.
2. The operator new must always be used to allocate space of a specific type, regardless of the type.
int[] x = new int[10]; x[0] = 34; x[1] = 88; println(x[0] + " " + x[1] + " " + x[10]); What is the output of the code fragment above? 1. 34 88 88 2. This program throws an exception. 3. 34 88 0 4. 0 34 88
2. This program throws an exception.
Javac
2. To compile an application, type the command ____ followed by the name of the file.
Primitive
2. Types already defined in Java, such as int, are known as ____ types.
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int x = 0; for (int e : a) x += a; 1. Sums all the elements in a. 2. Will not compile (syntax error) 3. Finds the largest value in e. 4. Counts each element in a.
2. Will not compile (syntax error)
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements adds the object to the beginning of the collection? 1. a[4] = element; 2. a.add(0, element); 3. a.insert(element); 4. a.add(element, 0); 5. a[0] = element;
2. a.add(0, element);
A variable comes into existence, or ____, when you declare it. 1. is referenced 2. comes into scope 3. overrides scope 4. goes out of scope
2. comes into scope
A(n) ____ constructor is one that requires no arguments. Student Response Value Correct Answer Feedback 1. write 2. default 3. class 4. explicit
2. default
Programmers frequently use the same name for a(n) ____ and an argument to a method simply because it is the "best name" to use. 1. block 2. instance field 3. variable 4. constant
2. instance field
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is NOT part of the heading of the method above? 1. static 2. int smaller; 3. minimum(int x, int y) 4. public
2. int smaller;
Clock ---------------------------------------- -hr: int -min: int -sec: int --------------------------------------- +Clock() +Clock(int, int, int) +setTime(int, int, int) : void +getHours() : int +getMinutes() : int +getSeconds() : int +printTime() : void +incrementSeconds() : int +incrementMinutes() : int +incrementHours() : int +equals(Clock) : boolean +makeCopy(Clock) : void +getCopy() : Clock ---------------------------------------- According to the UML class diagram above, which of the following is a data member? 1. printTime() 2. min 3. Clock() 4. Clock
2. min
To access the name instance variable from inside a method defined in the Student class, name must use the _____________ modifier. (We'll ignore the default package-private access if no modifier is used.) 1. public 2. protected or public 3. private or protected 4. private 5. protected 6. Any of them
2. protected or public
Which of the following is NOT true about return statements? 1. A method can have more than one return statement. 2. return statements can be used in void methods to return values. 3. Whenever a return statement executes in a method, the remaining statements are skipped and the method exits. 4. A value-returning method returns its value via the return statement.
2. return statements can be used in void methods to return values.
What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] < value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 1, 3, 5, 0, 0, 0 } 2. { 5, 1, 3, 7, 0, 0 } 3. { 1, 3, 5, 7, 0, 0 } 4. { 1, 3, 7, 5, 0, 0 }
2. { 5, 1, 3, 7, 0, 0 }
boolean
A data type that represents a true or false value.
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Based on the above code, what would be the output of the statement int s = minimum(5, minimum(3, 7)); 1. 5 2. There would be no output; this is not a valid statement. 3. 7 4. 3
3
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Based on the above code, what would be the output of the statement int s = minimum(5, minimum(3, 7));
3
What does the following loop print? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = a[0]; for (int i = 1; i < len; i++) if (a[i] > x) x = a[i]; System.out.println(x); 1. 36 2. 6 3. 12 4. 1
3. 12
What does the following loop print? int[] a = {6, 9, 1, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] < a[x]) x = i; System.out.println(x); 1. 6 2. 1 3. 2 4. 4
3. 2
What is the value of alpha[2] after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) alpha[j] = 2 * j + 1; 1. 1 2. 4 3. 5 4. 6
3. 5
The arguments in a method call are often referred to as ____. 1. concept parameters 2. constants 3. actual parameters 4. argument lists
3. Actual parameters
Consider the following declaration. int[] list = new int[10]; int j; int sum; Which of the following correctly finds the sum of the elements of list? (i) sum = 0; for (j = 0; j < 10; j++) sum = sum + list[j]; (ii) sum = list[0]; for (j = 1; j < 10; j++) sum = sum + list[j]; 1. Only (ii) 2. Only (i) 3. Both (i) and (ii) 4. None of these
3. Both (i) and (ii)
When you override a method defined in a superclass, you must do all of these except: 1. Use exactly the same number and type of parameters as the original method 2. Use an access specifier that is at least as permissive as the superclass method 3. Change either the number, type, or order of parameters in the subclass. 4. Return exactly the same type as the original method.
3. Change either the number, type, or order of parameters in the subclass.
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; for (int e : a) e = 0; 1. Changes each element in a to 0. 2. Compiles, but crashes when run. 3. Changes each element e to 0 but has no effect on the corresponding element in a. 4. Will not compile (syntax error)
3. Changes each element e to 0 but has no effect on the corresponding element in a.
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int x = 0; for (int e : a) x++; 1. Sums all the elements in a. 2. Will not compile (syntax error) 3. Counts each element in a. 4. Finds the largest value in e.
3. Counts each element in a.
Name and type
3. Every variable has a ________.
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] > a[x]) x = i; System.out.println(x); 1. Sums the elements in a. 2. Finds the position of the smallest value in a. 3. Finds the position of the largest value in a. 4. Counts the elements in a.
3. Finds the position of the largest value in a.
What does the following loop do? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] > value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. Removes (deletes) value from a so that the array remains ordered. 2. Places value in the last element of a 3. Inserts value into a so that the array remains ordered. 4. Places value in the first unused space in a (where the first 0 appears)
3. Inserts value into a so that the array remains ordered.
double
A data type that represents decimals.
Consider the following statements. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println("Length = " + length + "; Width = " + width + "\n" + + " Area = " + area() + "; Perimeter = " + perimeter()); } public double area() { return length * width; } public void perimeter() { return 2 * length + 2 * width; } } What is the output of the following statements?
3. Length = 14.0; Width = 10.0 Area = 140.0; Perimeter = 48.0
Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public void perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(); Which of the following sets of statements are valid in Java? (i) bigRect.set(10, 5); (ii) bigRect.length = 10; bigRect.width = 5; 1. Only (ii) 2. None of these 3. Only (i) 4. Both (i) and (ii)
3. Only (i)
Which of the following class definitions is correct in Java? (i) public class Student { private String name; private double gpa; private int id; public void Student() { name = ""; gpa = 0; id = 0; } public void Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } (ii) public class Student { private String name; private double gpa; private int id; public Student() { name = ""; gpa = 0; id = 0; } public Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } 1. Both (i) and (ii) 2. None of these 3. Only (ii) 4. Only (i)
3. Only ii
public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } What does the default constructor do in the class definition above? 1. Sets the value of x to 0 2. There is no default constructor. 3. Sets the value of x to 1 4. Sets the value of x to a
3. Sets the value of x to 1.
Empty String
3. The ____ is represented by "" in Java.
Size, style, and name
3. The font property controls the ____ of the font displayed by the Jlabel.
public static String exampleMethod(int n, char ch) Which of the following statements about the method heading above is NOT true? 1. The method has two parameters. 2. exampleMethod is an identifier giving a name to this specific method. 3. The method cannot be used outside the class. 4. It is a value-returning method of type String.
3. The method cannot be used outside the class.
Consider the following method definition. public int strange(int[] list, int item) { int count; for (int j = 0; j < list.length; j++) if (list[j] == item) count++; return count; } Which of the following statements best describe the behavior of this method? 1. This method returns the sum of all the values of list. 2. None of these 3. This method returns the number of times item is stored in list. 4. This method returns the number of values stored in list.
3. This method returns the number of times item is stored in list.
setTitle
3. Use ____ to set the text that appears on a JFrame's title bar.
Which of the following is the array subscripting operator in Java? 1. . 2. {} 3. [] 4. new
3. []
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following is an example of a local identifier in the example above? 1. w (line 20) 2. t (line 5) 3. a (line 25) 4. rate (line 3)
3. a (line 25)
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements adds the object to the end of the collection? 1. a[3] = element; 2. a[4] = element; 3. a.add(element); 4. a.add(element, 4);
3. a.add(element);
Methods that retrieve values are called ____ methods. 1. static 2. mutator 3. accessor 4. class
3. accessor
Constructors have the same name as the ____. 1. data members 2. member methods 3. class 4. package
3. class
When you create your own new, user-defined types, there are really three different strategies you can use. Which of these is not one of those strategies? 1. defining a component from scratch, inheriting only the methods in the Object class 2. extending an existing component by adding new features 3. defining a component from scratch, inheriting no methods whatsoever 4. combining simpler components to create a new component
3. defining a component from scratch, inheriting no methods whatsoever
int
A data type that represents whole numbers.
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements assigns the last object in the collection to the variable element? 1. element = a[3]; 2. element = a[4]; 3. element = a.get(3); 4. a.get(3, element); 5. a.get(element, e);
3. element = a.get(3);
The keyword ____ indicates that a field value is non-changable. 1. const 2. readonly 3. final 4. static
3. final
A(n) ____ variable is known only within the boundaries of the method. 1. instance 2. double 3. local 4. method
3. local
Assigning ____ to a field means that no other classes can access the field's values. 1. key access 2. user rights 3. private access 4. protected access
3. private access
Person -name: String +setName(String name): void +getName(): String ^ Student -studentID: long +Student(String sname, long sid) +setID(): long To access the name instance variable from inside a method defined in the Student class, name must use the _____________ modifier. (We'll ignore the default package-private access if no modifier is used.) 1. Any of them 2. public 3. protected or public 4. protected 5. private 6. private or protected
3. protected
Consider the following method which takes any number of parameters. Which statement would return the first of the numbers passed when calling the method? int first = firstNum(7, 9, 15); public int firstNum(int..nums) { // what goes here? } 1. return nums[0] 2. return nums; 3. return nums...0 4. return nums.first;
3. return nums..0
Which of the following words indicates an object's reference to itself? 1. public 2. that 3. this 4. protected
3. this
Mutator methods typically have a return type of ______________. 1. boolean 2. String 3. void 4. int
3. void
What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] > value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 5, 1, 3, 7, 0, 0 } 2. { 1, 3, 7, 5, 0, 0 } 3. { 1, 3, 5, 7, 0, 0 } 4. { 1, 3, 5, 0, 0, 0 }
3. { 1, 3, 5, 7, 0, 0 }
Assuming c=5, the value of variable d after the assignment d=c * ++c is _____.
30
int
32 bit
int
32 bit integer
float
32 bit real number
What does the following loop print? int[] a = {6, 1, 9, 5, 12, 7}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 1) x++; System.out.println(x); 1. 18 2. 2 3. 22 4. 4
4
double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is the value of vals.length in the array above? 1. 16 2. 4 3. 0 4. 3
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 the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; for (j = 4; j >= 0; j--) { alpha[j] = j + 5; if (j <= 2) alpha[j + 1] = alpha[j] + 3; } 1. 9 2. 5 3. 8 4. 10
4. 10
What is the value of alpha[4] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 2; for (j = 1; j < 5; j++) alpha[j] = alpha[j - 1] + 3; 1. 5 2. 11 3. 8 4. 14
4. 14
char[][] array1 = new char[15][10]; What is the value of array1.length? 1. 0 2. 10 3. 2 4. 15
4. 15
int[] array1 = {1, 3, 5, 7}; for (int i = 0; i < array1.length; i++) if (array1[i] > 5) System.out.println(i + " " + array1[i]); What is the output of the code fragment above? 1. 0 3 2. 7 3 3. 5 1 4. 3 7
4. 3 7
What is the value of alpha[2] after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) alpha[j] = 2 * j + 1; 1. 4 2. 6 3. 1 4. 5
4. 5
double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is in vals[2][1]? 1. 3.3 2. 3.5 3. 1.3 4. 5.3
4. 5.3
Consider the following statements. public class PersonalInfo { private String name; private int age; private double height; private double weight; public void set(String s, int a, double h, double w) { name = s; age = a; height = h; weight = w; } public String getName() { return name; } public int getAge() { return age; } public double getHeight() { return height; } public double getWeight() { return weight; } } Assume you have the following code fragment inside a method in a different class: PersonalInfo person1 = new PersonalInfo(); PersonalInfo person2 = new PersonalInfo(); String n; int a; double h, w; Which of the following statements are valid (both syntactically and semantically) in Java? (i) person2 = person1; (ii) n = person1.getName(); a = person1.getAge(); h = person1.getHeight(); w = person1.getWeight(); person2.set(n, a, h, w); 1. None of these 2. Only (ii) 3. Only (i) 4. Both (i) and (ii)
4. Both (i) and (ii)
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] > a[x]) x = i; System.out.println(x); 1. Finds the position of the smallest value in a. 2. Sums the elements in a. 3. Counts the elements in a. 4. Finds the position of the largest value in a.
4. Finds the position of the largest value in a.
Assume you have a Student object and a Student variable named bill that refers to your Student object. Which of these statements would be legal? bill.name = "Bill Gates"; // I bill.setName("Bill Gates"); // II println(bill.getName()); // III bill.studentID = 123L; // IV println(bill.getID()); // V 1. II, III, IV, VI 2. IV, V 3. All of them 4. II, III, V 1 5. None of them
4. II, III, V
Parentheses
4. In Java, use ________ to force the order of evaluation of operators.
What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] < value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 1, 3, 7, 5, 0, 0 } 2. { 1, 3, 5, 0, 0, 0 } 3. { 1, 3, 5, 7, 0, 0 } 4. { 5, 1, 3, 7, 0, 0 }
4. { 5, 1, 3, 7, 0, 0 }
Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following sets of statements are valid (both syntactically and semantically) in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); 1. Both (i) and (ii) 2. Only (ii) 3. None of these 4. Only (i)
4. Only (i)
Which of the following class definitions is correct in Java? (i) public class Student { private String name; private double gpa; private int id; public void Student() { name = ""; gpa = 0; id = 0; } public void Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } (ii) public class Student { private String name; private double gpa; private int id; public Student() { name = ""; gpa = 0; id = 0; } public Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } 1. Only (i) 2. Both (i) and (ii) 3. None of these 4. Only (ii)
4. Only (ii)
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 7}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 1) x += a[i]; System.out.println(x); 1. Finds the largest value in a. 2. Finds the smallest value in a. 3. Counts the odd elements in a. 4. Sums the odd elements in a.
4. Sums the odd elements in a.
Compiler
4. Syntax errors are found by the ____.
setIcon
4. Use ____ to specify the image to display on a JLabel.
setText()
4. Use the ____ method to clear any text displayed in a JTextField.
Which of these are superclass members are not inherited by a subclass? 1. a protected method 2. a protected instance variable 3. a public instance variable 4. a public constructor 5. a public method
4. a public constructor
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements adds the object to the end of the collection 1. a[3] = element; 2. a.add(element, 4); 3. a[4] = element; 4. a.add(element);
4. a.add(element);
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = 2 * j; if (j % 2 == 1) alpha[j - 1] = alpha[j] + j; } 1. alpha = {0, 2, 4, 6, 8} 2. alpha = {0, 3, 4, 7, 8} 3. alpha = {0, 2, 9, 6, 8} 4. alpha = {3, 2, 9, 6, 8}
4. alpha = {3, 2, 9, 6, 8}
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 5; if (j % 2 == 1) alpha[j - 1] = alpha[j] + 2; } 1. alpha = {5, 6, 10, 8, 9} 2. alpha = {8, 6, 7, 8, 9} 3. alpha = {5, 6, 7, 8, 9} 4. alpha = {8, 6, 10, 8, 9}
4. alpha = {8, 6, 10, 8, 9}
Person -name: String +setName(String name): void +getName(): String ^ Student -studentID: long +Student(String sname, long sid) +setID(): long Which of these fields or methods are inherited (and accessible) by the Student class? 1. getName(), setName(), name 2. name, getName(), setName(), getID() 3. studentID, name, getName(), setName(), getID() 4. getName(), setName(), toString() 5. None of them 6. getName(), setName(), studentID, getID()
4. getName(), setName(), toString()
int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the data type of the array above? 1. list 2. num 3. char 4. int
4. int
If a method in the superclass is declared protected, you may replace it in the subclass as long as the subclass method that you define: 1. has a different number, type, or order of parameters 2. has a different return type 3. is defined as protected or private 4. is defined as public or protected 5. is defined only as public
4. is defined as public or protected
A locally declared variable always ____ another variable with the same name elsewhere in the class. 1. uses 2. creates 3. deletes 4. masks
4. masks
Which of the following lines of code explicitly calls the toString() method, assuming that pete is an initialized Student object variable? 1. println(super.toString()); 2. println("" + pete); 3. println(pete); 4. println(pete.toString());
4. println(pete.toString());
Mutator methods typically begin with the word "____". 1. read 2. get 3. call 4. set
4. set.
double
A datatype that can *represent numbers with decimal points*.
What does a contain after the following loop? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; for (int i = size; i > pos; i--) a[i - 1] = a[i]; size--; 1. {3, 7, 7, 0, 0, 0} 2. {1, 1, 1, 0, 0, 0} 3. {3, 7, 0, 0, 0, 0} 4. {0, 0, 0, 0, 0, 0}
4. {0, 0, 0, 0, 0, 0}
Left to right
5. If an expression contains several multiplication, division and remainder operations, they are performed from ________.
.java
5. Java source code files have the extension ____.
the line number of the error; a brief description of the error.
5. Upon finding a syntax error in an application, the compiler will notify the user of an error by giving the user ____.
Replaces
5. When a value is placed into a memory location, the value ____ the previous value in that location.
When you define a subclass, like Student, and don't supply a constructor, then its superclass must: 1. have an explicit working constructor defined 2. have no constructors defined 3. have an explicit default (no-arg) constructor defined 4. have an explicit copy constructor defined 5. have no constructors defined or have an explicit default (no-arg) constructor defined.
5. have no constructors defined or have an explicit default (no-arg) constructor defined.
When you define a subclass, like Student, and add a single constructor with this signature Student(String name, long id), an implicit first line is added to your constructor. That line is: 1. No implicit lines are added to your constructor 2. this(); 3. super(name, id); 4. base(); 5. super();
5. super();
When you create a new class using inheritance, you use the extends keyword to specify the __________________ when you define the ________________. 1. derived class, subclass 2. derived class, base class 3. superclass, base class 4. subclass, base class 5. superclass, subclass 6. subclass, superclass
5. superclass, subclass
double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is in vals[2][1]? 1. 1.3 2. 3.3 3. 3.5 4. 5.3
5.3
Nondestructive
6. Reading a value from a variable is a ________ process.
word is spelled incorrectly; parentheses is omitted.
6. Syntax errors occur for many reasons, such as when a(n) ____.
Size and location of component
6. The bounds property controls the ____.
Not changed
6. When a value is read from memory, that value is ____.
long
64 bit
long
64 bit integer
double
64 bit real number
What is the ASCII value of 'A'?
65
Comment
9. A breakpoint cannot be set at a(n) ____.
setText
7. A Jlabel component displays the text specified by ____.
In straight-line form
7. Arithmetic expressions in Java must be written ____ to facilitate entering expressions into the computer.
KeyPressed
7. Pressing a key in JTextField raises the ________ event.
byte
8 bit integer
byte
8 bit, useful if memory an issue
double
8 bytes, stores floating-point numbers
Stop
8. The debugger command ________ sets a breakpoint at an executable line of source code in an application.
Before
8. The expression to the right of the assignment operator (=) is always evaluated ____ the assignment occurs.
setHorizontalAlignment
8. Use ____ to align the text displayed inside a Jlabel.
Components of a color
9. RGB values specify the ____.
What is the ASCII value of 'a'?
97
A debugger command that is used to examine the values of variables and expressions.
Header
A line of text at the top of a JTextArea that clarifies the information being displayed.
String
A line of text that can include letters, numbers, punctuation, and other characters.
Variable
A location in memory used to hold a data value.
variable
A location in the computer's memory where a value can be stored for use by an application.
Infinite Loop
A logical error in which a repetition statement never terminates.
NOT (!) operator
A logical operator that enables a programmer to reverse the meaning of a condition, true is false, false is true if evaluated.
XOR operator (^)
A logical operator that evaluates to true if and only if one operand is true.
OR operator (||)
A logical operator used to ensure that either or both of two conditions are true. Performs short-circuit evaluation.
AND operator (&&)
A logical operator used to ensure that two conditions are both true before choosing a path of execution. Performs short-circuit evaluation.
Variables
A variable is a name for a location (a chunk) in memory that holds a value (a fixed type of data) Variables come in two flavors: primitive and reference primitive: integer (such as 1, 2,...), floating point number (such as 1.2, 3.5, etc.), boolean (true or false) and char (such as 'A', 'B',...) reference: "address" of an object that resides in memory A variable declaration specifies the variable's name and the type of information that it will hold
True and False
A variable of type boolean can be assigned the values _____.
Counter
A variable often used to determine the number of times a block of statements in a loop will execute.
A variable or an expression can be examined by the _____ debugger command.
field
A variable that belongs to the entire class (not just a method).
primitive type
A variable type already defined in Java. (Examples: boolean, byte, char, short, int, long, float and double)
Constant
A variable whose value cannot be changed after its initial declaration is called a _____.
constant
A variable whose value cannot be changed after its initial declaration.
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
.....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.
Class variables
Declared with 'static' keyword. In class but not in methods. One per class - if it is set to 5 and an object changes it to 6 it will then be changed to 6 for all instances of the class.
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
[]
Declares arrays
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
--
Decrement by one
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"
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
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"
statement
A unit of code that performs an action and ends with a semicolon.
Statement
A unit of executable code, terminated by a semi-colon.
single-selection statement
A statement, such as the if statement, that selects or ignores a single action or sequence of actions.
Attribute
A value an object stores internally.
Variable
A storage place that can hold information, which may change.
Literal
A value represented as an integer, floating point, or character value that can be stored in a variable.
Able to be modified by the class, package, subclass, and world.
Define the keyword "public"
Counter-Controlled Repetition (Definite Repetition)
A technique that uses a counter to limit the number of times that a block of statements will execute.
Method that returns.
Define the keyword "return"
newline
A character that is inserted in code when you press Enter.
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
Does not change. Cannot make an instance of.
Define the keyword "static"
Java Class Libraries
A class library is a collection of classes to facilitate programmers when developing programs The Java standard class library is part of any Java development environment (available after installing JDK) The Java standard class library is sometimes referred to as the Java API (Application Programming Interface) Its classes are not part of the Java language per se, but we rely heavily on them Various classes we've already used (System, String) are part of the Java API
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.
JOptionPane
A class that provides a method for displaying message dialogs and constants for displaying icons in those dialogs.
String
A collection of characters. Surrounded by double quotation marks.
In Java, every program statement ends with what?
; (a semicolon)
What is the end of file indicator for windows? and for UNIX/Linux/Mac OS X?
<Ctrl> z <Ctrl> d
Type parameter
<X> ...of type X. <String> is of type String. <Tree> is a Tree object
What are 6 assignment operators?
= += -= *= /= %= ----------------- v20
assignment operator
=, lowest precedence, right to left association
Comparison operators: Equal to, Not equal to, greater than, greater than or equal to, less than, less than or equal to
== != > >= < <=
Make g conditional upon some statement
?:g
input JTextField
A JTextField used to get user input.
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.
comment
A ____ begins with two forward slashes (//).
Transfer of control
A ______ occurs when an executed statement does not directly follow the previously executed statement in the written application.
end-of-line comment
A comment that appears at the *end of a code line*.
full-line comment
A comment that appears on a line by itself in source code.
JTextField component
A component that can accept user input from the keyboard or display output to the user.
Boolean Expressions
A boolean expression often uses one of Java's equality operators or relational operators, which all return boolean results: Note the difference between the equality operator (==) and the assignment operator (=)
When a method tests an argument and returns a true or false value, it should return
A boolean value
Boolean
A boolean value represents a true or false condition (1 bit) The reserved words true and false are the only valid values for a boolean type boolean done = false; A boolean variable are usually used to indicate whether a particular condition is true, such as whether the size of a dog is greater than 60
JDK
A bundled set of development utilities for compiling, debugging, and interpreting Java Applications.
state button
A button that can be in the on/off (true/false) state, such as a CheckBox.
What must a class name always start with?
A capital letter then camel case with no spaces.
Charachters
A char variable stores a single character (16 bits) Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' Example of declarations with initialization: char topGrade = 'A'; char terminator = ';', separator = ' '; Note the difference between a primitive character variable, which holds only one character (enclosed by single quotes), and a String object, which can hold multiple characters (enclosed by double quotes)
Source file:
A file containing the source code, having the file extension .java.
source code file
A file with a .java extension. These files are editable by the programmer, but are not executable.
bug
A flaw in an application that prevents the application from executing correctly.
Repetition Statement
A general name for a statement that allows the programmer to specify that an action or actions should be repeated, depending on a condition.
Method
A group of Attributes and Behaviors.
block
A group of code statements that are enclosed in curly braces ({ and }).
OOP Program
A group of objects that work together to get something done.
Method
A group of programming statements given a name.
Array
A group of related variables that share the same type and are being arranged.
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.
breakpoint
A marker that can be set in the debugger at any executable line of source code, causing the application to pause when it reaches the specified line of code.
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.
b()
A method called b
Refactor - encapsulate collection
A method returns a collection - make it return a read-only view and provide add/remove methods. (get, set, add, remove..)
Refactor - replace error code with exception
A method returns a special code to indicate an error - throw an exception instead.
getText
A method that accesses (or gets) the text property of a component such as a JLabel, JTextField or a JButton.
Append
A method that adds text to a JTextArea component.
Double.parseDouble
A method that converts a String containing a floating-point number into a double value.
String.valueOf
A method that converts a numeric value (such as an integer) into text.
String.equals
A method that evaluates whether a String contains specific text specified.
setText
A method that sets the text property of a component, such as a JLabel, JTextField or JButton.
What's a method?
A mini-program that is referred to by the program and others.
floating-point number
A number with a decimal point, such as 2.3456, 0.0 and -845.4680
What must come after a declared class?
A pair of brackets that contain the method(s) between them
What do you attach to a method if it requires more information?
A parameter that represents additional information: Method: public static double _maximum_(Parameters(double x, double y, double z))
Relative Path
A path that is not anchored to the root of a drive. Its resolution depends upon the current path. Example ../usr/bin.
Java bytecode
A platform independent instruction set that's produced when Java source code is compiled.
Java Virtual Machine (JVM)
A platform-targeted runtime environment that knows how to execute Java bytecode.
pixel
A point on your computer screen. ____ is short for "picture element".
What is the definition of an algorithm?
A procedure for solving a problem in terms of: The actions to execute and the order in which these actions execute
algorithm
A procedure for solving a problem, specifying the actions to be executed and the order in which these actions are to be executed.
Programming:
A process of planning and creating a program.
control
A program statement (such as if, if...else, switch, while, do...while or for) that specifies the flow of ____.
Platform Independent
A program that does not have to be written for a specific operating system.
Application
A program that runs locally, on your own computer.
Applet
A program that runs on a web page.
Method that does not return.
Define the keyword "void"
An object is this type of variable
A reference variable
String
A sequence of characters that represents text information.
String literal
A sequence of characters within double quotes.
Computer program:
A sequence of statements whose objective is to accomplish a task.
Escape Sequence
A sequence used to represent special characters.
identifier
A series of characters consisting of letters, digits and underscores used to *name classes and GUI components*.
The Java Software Development Kit (JDK)
A set of command line tools (e.g., compilers, de-compilers, debuggers) used to develop Java programs. The JDK also contains the JRE, which contains the JVM.
The Java Runtime Environment (JRE)
A set of libraries that define the application programming interface (API) of the Java language. The JRE also contains the JVM application.
Programming language:
A set of rules, symbols, and special words.
block
A set of statements that is enclosed in curly braces ({ and }).
body
A set of statements that is enclosed in curly braces ({ and }). This is also called a *block*. Another name for this is a ____.
Data type:
A set of values together with a set of operations.
char
A single character
Iteration
A single trip through a loop.
Empty String
A special string literal, denoted by "".
Constructor?
A special type of method that is called when an object is created to initialize variables.
While Statement
A specific control statement that executes a set of body statements while a loop continuation condition is true.
Assignment Statement
A statement assigning a value to a variable.
nested statement
A statement that is placed inside another control statement.
multiline statement
A statement that is spread over multiple lines of code for readability.
double-selection statement
A statement, such as if...else, that selects between two different actions or sequences of actions.
Charachter Strings
A string literal is represented by putting double quotes around the text examples: "I Rule!" "The World" "123 Main Street" "X" "" literal is an explicit data (constant) value used in a program Every character string is an object in Java, defined by the String class Every string literal represents a String object A string literal can contain any valid characters, including numeric digits, punctuation, and other special characters.
empty string ("")
A string that does not contain any characters.
book-title capitalization
A style that capitalizes the first letter of each significant word in the text (for example, Calculate the Total).
sentence-style capitalization
A style that capitalizes the first letter of the first word In the text (for example, Cartons per shipment): other letters in the text are lowercase, unless they are the first letters of proper nouns.
Pseudocode
A stylized half-English, half-code language written in English but suggestion Java code
Merge Symbol
A symbol in the UML that joins two flows of activity into one flow of activity.
white space
A tab, space or newline is called a(n) _____.
In the following code, System.out.println(num), is an example of ________. double num = 5.4; System.out.println(num); num = 0.0;
A void method
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.
integer
A whole number, such as 919, -11 or 0 (not a decimal or fraction)
keyword
A word that is reserved by Java. These words cannot be used as identifiers. Also called *reserved word*.
reserved word
A word that is reserved for use by Java and cannot be used to create your own identifiers. Also called *keyword*.
Algorithm
A(n) ___ is a procedure for solving a problem in terms of the actions to be executed and the order in which these actions are to be executed.
name [row] [col]
Access an element
Public
Accessible by all.
Protected
Accessible if in same package.
Private instance variables can be accessed from outside their class through ______ methods and changed with _________ methods
Accessor methods && Mutator methods
Local variables (field)
Defined inside methods, constructors or blocks. Initialized within method and destroyed when method complete.
{}
Defines a block of code
The value of the last element in the array created by the statement int[] ar = new int[3]; is : A. 0 B. 1 C. 2 D. 3
A. 0
Categorize each of the following situations as a compile-time error, run-time error, or logical error.
A. Multiplying two numbers why you mean to add them. logical error B. Dividing by zero run-time error C. Forgetting a semicolon at the end of a programming statement compile-time error D. Spelling a word incorrectly in the output logical error E. Producing inaccurate results logical error F. Typing { when you should have typed a ( compile-time error
Polymorphism*
Able to perform operations without knowing the subclass of the object (just superclass). Apply the same operation on values of different types as long as they have common ancestor. * parent class reference is used to refer to a child class object - program decides which to run at run time
J2EE
Acronym for Java 2 Platform, Enterprise Edition.
J2ME
Acronym for Java 2 Platform, Micro Edition.
J2SE
Acronym for Java 2 Platform, Standard Edition.
When an object, such as a String, is passed as an argument, it is
Actually a reference to the object that is passed
When an object, such as a String, is passed as an argument, it is A. Passed by value like any other parameter value B. Actually a reference to the object that is passed C. Encrypted D. Necessary to know exactly how long the string is when writing the program
Actually a reference to the object that is passed
+=
Add and assign operator
Concatenation
Adding one string to another.
++ (unary increment operator)
Adds one to an integer variable.
Scanner input = new Scanner(System.in);
Adds scanner to program
selected
Defines if a component has been selected. (property)
Three
All Java applications can be written in terms of ____ types of program control.
.java
All Java file names have to have this extension.
Capital Letter
All java file names must have this at the beginning.
8 primitive data types
All of Java's numeric primitive data types are signed. Boolean (1 bit): true, false char (2 bytes): Unicode characters, ranging from 0 TO 65,535 byte (1 byte): -128 to 127 short (2 bytes): -32,768 TO 32,767 int (4 bytes): -2,147,483,648 TO 2,147,483,647 long (8 bytes): -9,223,372,036,854,775,808 TO +9,223,372,036,854,775,807 float (4 bytes): 1.40129846432481707e-45 TO 3.40282346638528860e+38 (+ or -) double (8 bytes): 4.94065645841246544e-324d TO 1.79769313486231570e+308d (+ or -)
Local variables A. Lose the values stored in them between calls to the method in which the variable is declared B. May have the same name as local variables in other methods C. Are hidden from other methods D. All of the above
All of the above
flow control structures
Allow different segments of code to be executed under different circumstances. Keywords : if...else, switch..case (all selection statements).
dot separator
Allows programmers to call methods of a particular class or object.
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
The if-else Statement
An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both
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.
event
An action that can trigger an event handler.
method
An application segment containing statements that perform a task.
forward slash (/)
An arithmetic operator that indicates division.
asterisk (*)
An arithmetic operator that performs multiplication.
Declaration with Initialization
An assignment statement changes the value of a variable The assignment operator is the = sign If you wrote keys = 80; The 88 would be overwritten You should assign a value to a variable that is consistent with the variable's declared type
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
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
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
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
Constructors are special methods defined in a class that are used to initialize ___ ___.
Answer: object instances Constructors must have the same name as the class name; the class Book will have constructors named Book (must be identical). Constructs are not allowed to explicitly declare that they return a type; rather, the implicit type they return is the enclosing class type in which they're defined.
char
Any character. Surrounded by single quotation marks.
How many JCheckBoxes in a GUI can be selected at once?
Any number
How many constructors can a class have? 1. Any number 2. 0 3. 1 4. 2
Any number
String Literal
Anything within double quotation marks.
All @param tags in a method's documentation comment must
Appear after the general description of the method
JTextArea method _ adds text to a JTextArea.
Append
Methods?
Are always public. They return data. Methods are made so that you can call on them so that you can use its functionality.
Statement (JDBC)
Defines methods that enable send SQL commands and receive data from DB. Statement st = connection.createStatement(); connection.execute(); etc.
Parameters are filled in with _________________ when invoking a method.
Arguments
Types of Queues
ArrayDeque: double ended ArrayBlockingQueue: fixed capacity, FIFO PriorityQueue: ordered based on value
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>();
Types of Lists
ArrayList: resizable array LinkedList: FIFO Stack: LIFO Vector: deprecated
ArrayList<String> friends = new ArrayList<String>();
ArrayList<typeParameter> variableName = new ArrayList<typeParameter>(); typeParameter cannot be a primitive type
class
Defines the characteristics and actions of an object. Models things from the problem domain.
Assertions
Assert that particular state must be true for program to proceed. Used for defensive programming and can be basis of formal programming proofs.
=
Assignment
=
Assignment Operator
Assignment Conversion
Assignment conversion occurs when a value of one type is assigned to a variable of another Only widening conversions can happen via assignment
Counter-controlled repetition is also called _.
Definite repetition
The last element in the array created by the statement int[] ar = { 1, 2, 3 }; is : A. ar[3] B. ar[2] C. ar(3) D. ar(2)
B. ar[2]
If you pass the first element of the array ar to the method x() like this, x(ar[0]); the element ar[0] : A. will be changed by the method x() B. cannot be changed by the method x() C. may be changed by the method x(), but not necessarily D. None of these
B. cannot be changed by the method x()
Name 9 primitive types
BSILF DB CS byte short int long float double boolean char String
Counter-controlled repetition is also called _____ because because the number of repetitions is known before the loop begins executing.
Definite repetition
Code Block
Delimited by curly-brackets, enables a set of statements to be treated as a single statement.
Where must all import declarations appear?
Before the first class declaration
Naming Methods?
Begins with public then is whatever data is going to be returned. ex. public String displayname()
UML Diagrams - list the behavior diagrams
Behavior Diagrams - STIACUS Sequence Timing Interactive Activity Communication Use Case State
BLOB
Binary Large OBject - converted to byte arrays before being stored - important in cloud services - data that doesn't fit in standard data types e.g. pictures, media files, archives - alternative to serialization
&
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.
==
Boolean equals
!
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.
If you pass the array ar to the method m() like this, m(ar); the element ar[0] : A. will be changed by the method m() B. cannot be changed by the method m() C. may be changed by the method m(), but not necessarily D. None of these
C. may be changed by the method m(), but not necessarily
Consider the following declaration. Scanner cin = new Scanner(System.in); int[] beta = new int[3]; int j; Which of the following input statements correctly input values into beta? (i) beta[0] = cin.nextInt(); beta[1] = cin.nextInt(); beta[2] = cin.nextInt(); (ii) for (j = 0; j < 3; j++) beta[j] = cin.nextInt();
Both (i) and (ii)
The condition exp1 || exp2 evaluates to false when ___.
Both are false.
The condition expression1 && expression2 evaluates to true when __.
Both expressions are true.
Casting Conversion
Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value being converted double money = 84.69; int dollars =(int) money; // dollars = 84
Methods are commonly used to
Break a problem down into small manageable pieces
methods are commonly used to
Break a problem down into small manageable pieces.
Engaging in OOP
Breaking down computer programs in the same way a pie chart is broken down.
Here is a loop that should average the contents of the array named ar : double sum = 0.0; int n = 0; for (int i=0; i < ar.length; i++, n++) sum = sum + ar[i]; if ( ?????? ) System.out.println("Average = " + ( sum / n ); What goes where the ???? appears : A. sum > 0 B. n == 0 C. n > 0 D. None of these
C. n > 0
Continuous Integration (CI)
Build generated whenever: - change to a defined repository - fixed intervals e.g. CruiseControl, Jenkins (previously Hudson) - configured using config.xml file - effectiveness depends on quality of system integration tests. limited by GUI's etc. Use mocks etc to overcome issues. http://www.thoughtworks.com/continuous-integration
CruiseControl
Build scheduler - <listeners> listen to the status of the build - <bootstrappers> actions to do before build
Objects example illustrated
CLASS Book title: String author: String isCheckedOut: boolean checkOut(): void checkIn(): void If a user checks out 2 books, each of them are assigned the class properties: Book Book title: Call of the Wild title: Gone with the Wind author: J. London author: M. Mitchell isCheckedOut: true isCheckedOut: true class is a type, and objects are instances of those types
static fields and methods
By default, data members and methods are "instance" members and are said to be "non static." Non static instance data members are copied to each object instance of the class, so each object has its own copy. Non static methods can reference these copied data members through an implicit object reference (but you can access it via "this" when necessary). The concept of non static instance members is illustrated below. public class Book { private String title = ""; public void setTitle(String title) { this.title = title; } } When there's a need to not copy data members to each object instance, such as constants. They can remain in the class definition. Data members and methods that are not associated with object instances are call "class" members; they are local to the class and are not affiliated with the objects. Annotated with the keyword "static": public static final int CHECKOUT_DURATION = 21; Because the above data member is a class variable, it can be accessed through the class name as follows: int duration = Book.CHECKOUT_DURATION; Methods can also be designated as static: private static int nextId = 1; public static int getNextId() { return nextId++; } Above, method getNextId() provides access to the static data member and manages its next value. IMPORTANT: "static only sees static" but "non-static sees everything" static members can only access other static members; in particular, static members cannot access non-static members. Non-static members have access to all members (both static and non-static).
How can a method send a primitive value back to the caller?
By using the return statement
Assume that you have an ArrayList variable named a containing many elements. You can rearrange the elements in random order by writing:
Collections.shuffle(a);
To print the number of elements in the array named ar, you can write : A.System.out.println(length); B.System.out.println(ar.length()); C.System.out.println(ar.length); D.System.out.println(ar.length-1);
C. System.out.println(ar.length);
You can create an array of three doubles by writing : A. double ar[] = 3; B. double ar[3]; C. double ar[] = { 1.1, 2.2, 3.3 }; D. double[] ar = double(3);
C. double ar[] = { 1.1, 2.2, 3.3 };
Which of the following methods returns an array ? A. int acpy(int n) { ... } B. int acpy(int[] n) { ... } C. int[] acpy(int n) { ... } D. None of these
C. int[] acpy(int n) { ... }
To create the array variable named ar, you would use : A. int ar; B. int() ar; C. int[] ar; D. None of these
C. int[] ar;
What does the 'new' key word do here when creating an instance? Printer myPrinter = new Printer();
Calls the default constructor on the Printer class.
Methods rule (subtypes)
Calls to the subtype methods must behave like calls to the corresponding supertype method.
Public modifier
Can be applied to a class and/or individual data members and methods within a class; indicates that the given item is accessible across package boundaries, the following class and method are both accessible outside the package in which they're defined. package domain; public class Book { public void checkOut() { } }
Default (no modifier)
Can be applied to a class and/or individual data members and methods within a class; indicates that the given item is not accessible across package boundaries (i.e., it limits access to members of the same package) e.g., the following class and method are NOT accessible outside the package in which they're defined. package domain; class Book { void checkout() { } }
Protected modifier
Can be applied to individual data members and methods (but cannot be applied to a class); when applied, it restricts access to members of the same class and any derived class; e.g., the following method, setHashCode, is only accessible to members of the LibraryItem class and any derived classes (e.g., Book). package domain; public class LibraryItem { protected void setHashCode() { } } package domain; public class Book extends LibraryItem { public LibraryItem () { setHashCode(); } }
Private
Can be applied to individual data members and methods (but cannot be applied to a class); when applied, it restricts access to members of the same class; e.g., the following data member, isbn, is only accessible to members of the Book class, and nowhere else. package domain; public class Book { private String isbn; public void getIsbn() { return isbn } }
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.
Attributes (ANT)
Can contain references to a property. References resolved before task executed
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.
Method
a sequence of instructions that accesses the data of an object
When you overload a method defined in a superclass, you must do which one of these? 1. Change either the number, type, or order of parameters in the subclass. 2. Use an access specifier that is at least as permissive as the superclass method 3. Return exactly the same type as the original method. 4. Use exactly the same number and type of parameters as the original method.
Change either the number, type, or order of parameters in the subclass.
When you override a method defined in a superclass, you must do all of these except:
Change either the number, type, or order of parameters in the subclass.
Conversion
Changing one type of primitive data to another.
Work with Java Arrays
Chapter 6 Objective 1
CLOB
Character Large OBject
semicolon (;)
Character used to terminate each statement in an application.
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.
Working directory
Checkout of the latest version of a project. May contain modified files that are not staged or committed. (Local)
Arithmetic expressions
a sequence of operands and operators that computes a value
-All programs start with a ? -Must have { and } -Identifier (name) begins with a CAPITAL letter EX: public class Westlake
Class
Decimal, Text
Class DecimalFormat is used to control how ____ numbers are formatted as ____.
RuntimeException
Class is the superclass of those exceptions that can be thrown during normal runtime of the Java virtual machine.
UML Class diagram w/ general syntax
ClassName Properties Here Behaviors Here Book title: String author: String isCheckedOut: boolean checkOut(): void checkIn(): void Each property name is followed by its data type (e.g., String, boolean). Each method name is followed by its return type (e.g., void).
Object Construction
ClassName objectName = new ClassName(parameters);
How do you call a method from a class?
ClassName.methodName(arguments)
Static method call
ClassName.methodName(parameters);
Object-Oriented Programming
Classes are the building blocks of a Java program; a blueprint for which individual objects can be created Each class is an abstraction of similar objects in the real world E.g., dogs, songs, houses, etc Once a class is established, multiple objects can be created from the same class. Each object is an instance (a concrete entity) of a corresponding class E.g., a particular dog, a particular song, a particular house, etc
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
Refactoring
Cleans code whilst preserving behaviour.
What is the output of the following Java code? int[] list = {0, 5, 10, 15, 20}; int j; for (j = 1; j <= 5; j++) System.out.print(list[j] + " "); System.out.println(); 1. 5 10 15 20 0 2. 5 10 15 20 20 3. 0 5 10 15 20 4. Code contains index out-of-bound
Code contains index out-of-bound
event handler
Code that executes when a certain event occurs.
statement
Code that instructs the computer to perform a task. Every statement ends with a semicolon ( ; ) character. Most applications consist of many statements.
declaration
Code that specifies the name and type of a variable.
signature
Combination of identifiers, return value, name and parameters of a method. Example: public int calculateMonth(String name)
JComboBox
Combine text field and drop down list. Text field can be editable.
dir command
Command typed in a Command Prompt window to list the directory contents.
// marks the single line ? /* block ? */
Comments
git commit
Commits staged files to Repo.
Refactor - decompose conditional
Complicated if-then-else: extract methods from the condition, then part, then else parts. if (date.before(SUMMER_START)) charge = quantity * winterRate + winterService Charge; else charge quantity * summerRate BECOMES if(notSummer(date)) charge = winterCharge(quantity) else charge = summerCharge(quantity)
JLabel
Component that displays a text or an image that the user cannot modify
GridBagLayout
Components placed in a grid. - given distinct sizes (# rows and # columns assigned to component. Most common for sophisticated GUIs.
BoxLayout
Components placed in box. Can be aligned left, centre, right, top, middle, bottom etc.
Intermediate Swing Level
Components used for laying out the UI (User Interface). JPanel, JInternalFrame, JScrollPane, JSplitPane, JTabbedPane (e.g. chrome browser has tabs at top)
Connection interface (JDBC)
Connection to DB through connection object Uses Singleton pattern = only one instance of connection. connection = DBConnection.getInstance(); try { Statement st = connection.createStatement();
Final
Constants are declared with keyword ____.
If method A calls Method B, and method B calls method C, and method C calls method D, when method D finishes, what happens?
Control is returned to method C
JTextArea
Control that allows the user to view multiline text.
Casting
Converting information from one form to another.
A _ is a variable that helps control the number of times that a set of statements will execute.
Counter
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x++; System.out.println(x); 1. Sums the even elements in a. 2. Finds the largest value in a. 3. Counts the even elements in a. 4. Finds the smallest value in a.
Counts the even elements in a.
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x++; System.out.println(x); 1. Sums the even elements in a. 2. Counts the even elements in a. 3. Finds the smallest value in a. 4. Finds the largest value in a.
Counts the even elements in a.
BufferedReader stdin = new BufferedReader(new InputStreamReader(system.in)) input = stdin.readLine();
Create BufferedReader instance containing a InputStreamReader instance with byte stream as input.
new type [nRows] [nCols]
Create a 2D array
inheritance
Creating a new class based on an existing class (also called *extending a class*). This action is called ____.
extending a class
Creating a new class based on an existing class (also called *inheritance*). This action is called ____.
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
To print the last element in the array named ar, you can write : A. System.out.println(ar.length); B. System.out.println(ar[length]); C. System.out.println(ar[ar.length]); D. None of these
D
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
clear
Debugger command that displays a list of all the breakpoints in an application.
Which of the following is not a benefit derived from using methods in programming? A. Code reuse B. Problems are more easily solved C. Simplifies programs D. All of the above are benefits
D. All of the above are benefits
To print the last element in the array named ar, you can write : A. System.out.println(ar.length); B. System.out.println(ar[length]); C. System.out.println(ar[ar.length]); D. None of these
D. None of these
Suppose we have these two array definitions in main(): String[] hospName = new String[100]; int[] hospCode = new int[100]; hospCode[I] stores the code for a specific hospital. hospName[J] stores the name of the hospital that has code J. Suppose the code 24 is stored at position 13 of hospCode. Which expression below references 24's corresponding name? A. hospName[13] B. hospCode[24] C. hospCode[hospName[13]] D. hospName[hospCode[13]] E. hospName[hospCode[24]]
D. hospName[hospCode[13]] General Feedback: What we want is the name for hospital with code 24. We could get that with hospName[24], but that's not one of the options. However, we know that hospCode[13] contains the value 24, so we can use that instead.
Which of the following would be a valid method call for the following method? public static void showProduct (int num1, double num2) { int product; product = num1 * (int)num2; System.out.println("The product is " + product); } A. showProduct(10.0, 4); B. showProduct(33.0, 55.0); C. showProduct(5.5, 4.0); D. showProduct(10, 4.5);
D. showProduct(10, 4.5);
Here is a loop that is supposed to sum each of the values in the array named ar : double sum = 0.0; for (int i=0; i < ar.length; i++) // ??? System.out.println(sum); What goes on the line containing ???? : A. i = sum + ar[i]; B. sum + ar[i]; C. sum = sum + i; D. sum += ar[i];
D. sum += ar[i];
Debugger command that displays the value of a variable when an application is stopped at a breakpoint during execution in the debugger.
set
Debugger command that is used to change the value of a variable.
cont
Debugger command that resumes program execution after a breakpoint is reached while debugging.
this
Denotes current object. Resolves ambiguity problems. this.tree = tree;
left brace ({)
Denotes the beginning of a *block of code*.
right brace (})
Denotes the end of a *block of code*.
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.
Definition of class
Describes the properties and behavior of a prototypical object. During runtime, the application creates individual instances of classes where the instances are called objects. For example: class - Book properties - title, author behaviors - checkOut(), checkIn() Then at runtime, the application creates a separate object for each book as they are requested by users.
In a @return tag statement the description
Describes the return value
In a @return tag statement the description A. Describes the return value B. Must be longer than one line C. Cannot be longer than one line D. Describes the parameter values
Describes the return value
Operator precedence rules:
Determine the order in which operations are performed to evaluate an expression.
The UML represents both the merge symbol and the decision symbol as _____.
Diamonds
JTextArea
Display textual data or accept large amounts of text input.
case sensitive
Distinguishes between uppercase and lowercase letters in code.
/
Division operator
do{ code here } while ( argument here);
Do loop
Creating Objects: Reference Variable
Dog is the data type. That's what reference allows us to do. It makes it user friendly by letting us make our own data types. We tell the computer to set aside a chunk of space for the data type, Dog. The size of the chunk will be big enough to hold an address, because reference is indirect. No actual amount will go in like with primitive datatypes where we know the amount of storage being used. It will just leave space (a placeholder)
Surround all String text with?
Double Quotes
How to Execute Programs
Each type of CPU executes only a particular machine language A program must be translated into machine language before it can be executed Compiler: translates only once Most high-level languages: C, C++, etc. Interpreter: translates every time you run programs Most scripting languages: python, perl, etc. The Java approach is somewhat different. It combines the use of a compiler and an interpreter.
Suppose we want to store a tic-tac-toe board in a program; it's a three-by-three array. It will store "O", "X" or a space at each location (that is, every location is used), and you use a two-dimensional array called board to store the individual tiles. Suppose you pass board to a method that accepts a two-dimensional array as a parameter. If the method was designed to process two-dimensional arrays of various sizes. What information about the size of the array would have to be passed to the method so it could properly process the array? A. the number of columns in the array B. the number of rows in the array C. the number of cells in the array D. Both A and B E. No additional information is needed, as the array carries its size information with it.
E. No additional information is needed, as the array carries its size information with it.
Suppose we define a class called NameInfo. It has several private fields, including String hospName; and several public methods, including one that accesses hospName: String getName(); Now, we define an array like this: NameInfo[] listOfHospitals = new NameInfo[100]; Which expression below correctly accesses the name of the hospital that's stored in position 5 (that is, the 6th element) of the listOfHospitals? A. listOfHospitals.getName(5) B. listOfHospitals.hospName[5] C. listOfHospitals[5].hospName D. listOfHospitals[getName(5)] E. listOfHospitals[5].getName()
E. listOfHospitals[5].getName()
Exception that occurs when you're reading from a file and the file ends before you expected it to end.
EOFException
Bit Permutations
Each additional bit doubles the number of possible permutations Each permutation can represent a particular item N bits can represent up to 2^N unique items, so to represent 50 states, you would need 6 bits: 1 bit: 2^1 = 2 items 2 bits: 2^2 = 4 items 3 bits: 2^3 = 8 items 4 bits: 2^4 = 16 items 5 bits: 2^5 = 32 items Five bits wouldn't be enough, because 2^5 is 32. Six bits would give us 64 permutations, and some wouldn't be used.
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
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
Users cannot edit the text in a JTextArea if its _ property is set to false.
Editable
Primitive Data Types
Eight commonly used data types.
The condition Exp1 ^ exp2 evaluates to true when ____.
Either exp1 is false and exp2 is true or exp1 is true and exp2 is false.
Floating Point Literals
Either written with a whole and fractional part separated by a dot '45.98' or with scientific notation which allows significant digits that are multiplied by a power of 10 specified after the character 'e'. 'double speedOfLight = 2.998e8'. It seems that both double and float use the same literals, unlike C++.
Inheritance
Enables one object to inherit behavior and attributes from another object.
What does a scanner do for a program?
Enables the program to read data (ints, dbls, char etc.)
String Literal
Enclosed in double quotation marks. E.g. "Jonathan withey". This actually creates a String object to be referenced, for example 'String aString = "Character Sequence";'.
;
End of a statement
Glass box steps
Ensure 1. Statement coverage (every statement is executed at least once. 2. Branch coverage (each condition is evaluated at least once). 3. Path coverage (all control flow paths are executed at least once).
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
Staging area
File indicating the modified files in the working directory to be included in the next commit. (Local). Use 'git add'.
How is the filename of a public class formatted?
Filename.java
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] > a[x]) x = i; System.out.println(x); 1. Finds the position of the largest value in a. 2. Sums the elements in a. 3. Finds the position of the smallest value in a. 4. Counts the elements in a.
Finds the position of the largest value in a.
Which of the following creates an array of 25 components of the type int? (i) int[] alpha = new[25]; (ii) int[] alpha = new int[25]; 1. Only (ii) 2. None of these 3. Only (i) 4. Both (i) and (ii)
Only (ii)
Data Type Sizes
Fixed in Java, to ensure portability across implementations.
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
Packages
For purposes of accessing them, classes in the Java API are grouped into packages
Three types of Loops
For, While, and Do-While.
- 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)
name[0].length
Get the number of columns
name.length
Get the number of rows
Quick Check: The Random Class
Given a Random object reference named gen, what range of values are produced by the following expression?
Quick Check: Booelan Expressions
Given the following declarations, what is the value of each of the listed boolean conditions?
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
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.
GUI
Graphical User Interface
>
Greater than
>=
Greater than or equal to
Arrays
Group (or collection) of items that are the same type. declares an array object, daysOfWeek, as an array of seven String objects: String [ ] daysOfWeek = new String[7]; assign the seven elements as follows: daysOfWeek[0] = "Sunday"; daysOfWeek[1] = "Monday"; daysOfWeek[2] = "Tuesday"; daysOfWeek[3] = "Wednesday"; daysOfWeek[4] = "Thursday"; daysOfWeek[5] = "Friday"; daysOfWeek[6] = "Saturday"; values could be initialized at the point of declaration: private String [ ] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday" , "Thursday", "Friday", "Saturday"}; The size of the array is available via the length property (e.g., daysOfWeek.length), allowing you to iterate through its values in a "for loop": for (int i = 0; i<daysOfWeek.length; i++) { System.out.println(daysOfWeek[i]); } Array downside, once declared, their size is fixed. Can create a new, larger array and move the contents of the first array into the second, but that is clumsy. Typically used only for grouping items whose size is fixed.
Java Collection Framework
Group of interfaces, classes, and algorithms that together provide a rich set of abstractions for grouping objects. Maps - A collection whose entries are accessed by some unique identifier. Lists - A collection whose entries can be accessed with an index. Sets - A collection whose entries are guaranteed to be unique. Queues - A collection whose entries are ordered, based on some scheme.
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 '=='.
JTextField
Hold any text. Can be editable. Use for small amounts of input.
Inheritance
How one class can be created from another.
Java Program Structure
In the Java programming language: -A program is made up of one or more classes defined in source files (with the .java extension) -A class contains one or more methods -A method contains program statements
Creating objects
How to create objects once a class is established? How to "hold" those created objects? For primitive types (such as byte, int, double), we use a variable of that particular type as a cup to store its actual value BUT Objects are different There is actually no such thing as an object variable, because we can't put a number on it. There is only an object reference variable An object reference variable holds something like a pointer or an address that represents a way to get to the object. When you copy a string object, you're really copying it's address.
JOptionPane.ERROR_MESSAGE
Icon containing a stop sign, alerts the user of errors or critical situations.
JOptionPane.WARNING_MESSAGE
Icon containing an exclamation point, cautions the user of potential problems.
-Must start with a letter -Can contain letters, numbers, and underscore character -Cannot contain spaces -Cannot contain reserved (key) words
Identifiers (name) Rules
Java Identifiers
Identifiers are the "words" in a program -Name of a class: Dog, MyFirstApp, and Lincoln -Name of a method: bark and main -Name of a variable: args (later in this course) Rules: A Java identifier can be made up of -letters -digits (cannot begin with a digit) -the underscore character ( _ ), -the dollar sign ($) Java is case sensitive: -Total, total, and TOTAL are different identifiers By convention, programmers use different case styles for different types of identifiers, such as title case for simple class names - Lincoln camel case for compound words - MyFirstApp upper case for constant variables - MAXIMUM
Constants
Identifiers that always have the same value.
case sensitive
Identifiers with identical spelling are treated differently if the capitalization of the identifiers differs. This kind of capitalization is called _____.
++
Increment by one
A(n) _ loop occurs when a condition in a while statement never becomes false.
Infinite
Access Modifiers
Information hiding is achieved through the use of access modifiers, which are keywords that are used to augment the visibility of various constructs. Public Default (no modifier) Protected Private
Source
Information in it's original form.
Binary Numbers
Information is stored in memory in digital form using the binary number system A single binary digit (0 or 1) is called a bit A single bit can represent two possible states, like a light bulb that is either on (1) or off (0) Permutations of bits are used to store values Devices that store and move information are cheaper and more reliable if they have to represent only two states
git init
Initialise an empty repository
Inner & Anonymous Classes
Inner classes are defined within the context of another class. package domain; public class Book extends LibraryItem implements AuthorableItem, PrintedMaterial { BookReader reader = new BookReader(); // .rest of Book definition public String nextLine() { return reader.readNextLine(); } // Note that this is not a "public" class- //only an instance of Book can access the BookReader class BookReader { public BookReader() { } public String readNextLine() { // Implementation of this method. } } // BookReader } // Book Anonymous classes are also inner classes that are defined within the context of another class, but these classes do not have a name, hence the name anonymous. Anonymous inner classes are often used as event handlers in the implementation of graphical user interfaces.
Objects have both _______ and _______.
Instance Variables && Methods
Each class declares Instance Variables and Methods (Unique Values for the Objects in the Class)
Instance variables: descriptive characteristics or states of the object Ex. students are an instance variable of a class Methods: behaviors of the object (the actual doing thing of each instance variable) Ex. doing homework or taking exams are the methods of the instance variable "student"
Java Runtime Environment (JRE)
Interpreter for compiled Java byte code programs. = Java Virtual Machine (JVM)
Dangers of threads
Introduce ASYNCHRONOUS BEHAVIOUR - multiple threads access same variable/storage location can become unpredictable. - only one should alter data at a time.
Which of the following statements creates alpha, a two-dimensional array of 10 rows and 5 columns, wherein each component is of the type int? 1. Both (i) and (ii) 2. Only (ii) 3. None of these 4. Only (i)
Only (ii)
String Indexes
It is occasionally helpful to refer to a particular character within a string This can be done by specifying the character's numeric index The index begins at zero in each string In the string "Hello" H is at the index 0 and o is at the index 4
In a (for), (while), or, (do...while) statement what does the break statement do? and a continue statement?
It breaks out of the loop using an if statement ' Ex: if (count==5) break; 1 2 3 4 It skips the number defined Ex: if (count==5) continue; 1 2 3 4 6 7 8 9 10
What is the scope of a variable?
It defines where the variable can be used in a program.
Scanner Class
It is often useful to design interactive programs that read input data from the user The Scanner class provides convenient methods for reading input values of various types A scanner object can be set up to read input values from various sources including the user typing values on the keyboard The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner(System.in); Once created, the Scanner object can be used to invoke various input methods, such as: String answer = scan.nextLine(); The nextLine method reads all of the input until the end of the line is found, and return it as one String
What does a UML activity diagram do?
It models the workflow(also called the activity) of a portion of a software system.
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.
Package
Items of related functionality, each item in the package has a unique name. Thus, a package is a namespace, where a namespace is a collection of uniquely named items. One of main packages is "java", does not contain any data types, it's used to aggregate other packages that are nested within it. java.applet java.awt java.beans java.io java.util nested package example: java.util.concurrent.locks other nested packages do contain type definitions: - java.util contains the Date class (and other classes) - java.util.concurrent contains the Semaphore class (and other classes) - java.util.concurrent.locks contains the LockSupport (and other classes)
LinkedList: iterate through list of strings and print each one
Iterator<String> iter = list.iterator(); while(iter.hasNext()){ System.out.println(iter.next()); } don't forget: iterators have a remove() function!
iterator()
Iterator<String> iter = names.iterator(); while(iter.hasNext()){ System.out.println(iter.next()); }
When an argument is passed to a method,
Its value is copied into the method's parameter variable
The text that appears alongside a JCheckBox is referred to as the ____.
JCheckBox Text
The ___ constant can be used to display an error message in a message dialog.
JOptionPane.ERROR_MESSAGE
The _ component allows users to add and view multiline text.
JTextArea
uneditable JTextField
JTextField in which the user cannot type values or edit existing text. Such JTextFields are often used to display the results of calculations.
Swing
Java GUI programming toolkit - Native code windows - 4 heavyweight components - lightweight - look and feel can be changed (can be set or depend on platform) - wide range of widgets
Abstract Windowing Toolkit (AWT)
Java GUI programming toolkit - native widgets - heavyweight components - small range of widgets - look and feel can not be changed. - Dependent on platform. OLD.
JSE JEE JME Java Card
Java Standard Edition - Contains the core functionality of the Java language; used to develop desktop applications. Java Enterprise Edition - Provides additional functionality required of enterprise applications, including web applications. Java Micro Edition - A scaled-down version used for mobile phones and other handheld devices. Java Card - The smallest Java footprint used for integrated circuits (e.g., memory and microprocessor cards).
JSE API
Java Standard Edition Application Programming Interface Libraries
What does JVM stand for?
Java Virtual Machine
Package
Java classes grouped together in order to be imported by other programs
Java Development Kit (JDK)
Java compiler and interpreter. includes JRE and JSE API
Java portability
Java source code (.java) > Java compiler > Java bytecode program (.class or .jar) > OS Just In Time (JIT) compiler > OS machine code
String class
Java's String class is used to represent a sequence (i.e., string) of characters. A simplified class diagram of String is shown below: STRING count : int value : char[] String() String(orig:String) length : int charAt(index:int) : char concat(st : String) : String equals(obj : String) : boolean indexOf(str : String) : int isEmpty() : boolean lastIndexOf(str : String) : int length() : int replace(oldChar : char , newChar : char) : String substring(beginIndex : int, endIndex : int) : String toLowerCase() : String toUpperCase() : String toString : String * Extends class Object and thus inherits Object's properties and behavior, including method equals(Object); * Encapsulates private fields (e.g., count and value), prevents direct access to these fields by other objects; indirect access is provided through public methods; e.g., the method length() provides access to the count field; * Has two overloaded constructors, String() and String(String s). The first constructor takes no parameters, and the second takes a String object that is copied into the new String object; * Overrides methods toString() and equals() inherited from class Object by providing its own implementations; * Exhibits polymorphism (one interface, multiple behaviors) with methods toString() and equals();
Read an int from the Scanner object and store it in an int
Java: Int varx= input.nextint();
Create a Scanner object that reads from System.in
Java: Scanner input= new Scanner(System.in)
Prompt the user
Java: System.out.println
Read a double from the Scanner object and store it in a double
Java: double varX= input.nextDouble();
Import the Scanner Class
Java: import java.util.Scanner;//at top of the file
Create a Method called methodX
Java: public static void methodX(){
Who will do the Java compiling?
Javac is the complier, not Eclipse. Eclipse is the software that runs javac. The Java virtual machine (the executable response) is called java For one class... what is the mechanism that allows us to run it? Answer: we are using an existing object
Concatenating
Joining one string to another string. Also known as pasting.
Class=Blueprint
Just like how one blueprint (class) is used to create several similar, but different houses (objects)
final
Keyword that precedes the data type in a declaration of a constant.
What type of structure are stacks usually known as?
LIFO structures (Last-in, First-out) which means that the last item pushed onto the stack is the first to be taken off.
<
Less than
<=
Less than or equal to
What are the three ways to return control to the statement that calls a method?
Let the second bracket of the called method return control use return; to return control use return (expression); to return a variable as well as control
;
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
LinkedList<String>: Instantiation
LinkedList<String> myList = new LinkedList<String>();
Event Listeners (Observer?)
Listen for events in components. Instances of Listener classes. Provided in interfaces.
A variable declared in a method is said to be a ____________________.
Local variable
Define how java classes are connected.
Loosely connected objects that interact with each other.
What are the three types of class variables?
Public, Allows them to be used in your own classes Static, allows them to be accessed vie that class name and a dot (.) separator Final, indicates that they are constants--- their values cannot change after they are initiated.
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
Benefits of Encapsulation*
Maintainability, Flexibility and Extensibility.
Public int
Makes it possible to modify the variable from another program that is using the object.
join (Threads)
Makes other thread/next thread wait until the first thread terminated. one.start(); two.start(); one.join(); three.start(); // Three has to wait on one
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.
Pi
Math.PI
π
Math.PI;
absolute value?
Math.abs(#)
absolute value of x - y
Math.abs(x - y);
arc cos x
Math.acos(x);
arc sin x
Math.asin(x);
Round to smallest integer not less than number input(round number up)?
Math.ceil(#) Ex: ceil(9.2)=10
Cosine?
Math.cos(#)
cos x
Math.cos(x);
How do you put e to a power? Ex: e^x
Math.exp(x)
Round to the largest integer not greater than number input?(round down)
Math.floor(#)
Natural logarithm of a number?
Math.log()
find the max
Math.max (x, y);
larger value of x and y?
Math.max(x,y)
find the min
Math.min (x, y);
Smaller value of x and y?
Math.min(x,y)
x^y
Math.pow (x, y);
Power or Exponent
Math.pow(x,y)
Random Number
Math.random()
random number between 0 and n
Math.random() * (n + 1);
random number between 0 and 1
Math.random();
Sine?
Math.sin(#)
sin x
Math.sin(x);
Square Root
Math.sqrt
square root of a
Math.sqrt (a);
Tangent?
Math.tan(x)
radians to degrees
Math.toDegrees();
degrees to radians
Math.toRadians();
Expressions that use logical operators can form complex conditions
Max +5, then less than sign, then the logical not and logical & operators Think of it like true always wins
exceptions that usually occur because of code that isn't very robust.
Runtime Exceptions
When something goes wrong while the program is running. (Also known as exception)
Runtime error
void
Means that the method does something but does not return any value at the end
In a UML activity diagram, a(n) _ symbol joins 2 flows of activity into 1 flow of activity.
Merge
Differences in String
S is Capitalized. Type of Object.
initialization value
The beginning value of a variable.
format
Method ____ of DecimalFormat can display double values in a special format, such as with two digits to the right of the decimal point.
This part of a method is a collection of statements that are performed when the method is executed.
Method body
polymorphism
Method overloading is an example of polymorphism. polymorphism can be defined as "one interface with multiple behaviors." Another form of polymorphism is method overriding, which is an example of dynamic binding. Method overriding is discussed later in this topic.
Mutator
Method that alters the attributes of an object.
toUpperCase
Method which converts any String to uppercase equivalent by creating a new String object
-Segments of code that perform some action -Always followed by parenthesis EX: System.out.println("abc") <--- print is the ?
Methods
All objects in a class have the same _______ and same types of _______.
Methods && Instance Variables
Event Handlers
Methods that host the response code (tells what to do if event occurs).
-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
Mocking
Mocks objects that exist outside the program. Use for TDD.
Abstract Data Types
Model of a data structure e.g. Stack(). Describes the behaviour of the data type.
formatting
Modifying the appearance of text for display purposes.
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}}
Thread communication
Multiple threads notify each other when conditions change, when to wait or stop waiting. - void wait(), wait(long time), wait(long time, int nano) - void notify() - void notifyAll()
*
Multiplication operator
*=
Multiply and assign operator
{}
The body of an if statement that contains multiple statements is placed in _____.
A no-argument constructor has....
No parameters.
Are primitive data types considered objects in Java?
No, primitive types are the only elements of the Java language that are not modeled as objects.
Does Java have multiple inheritance?*
No. Instead deal with interfaces.
Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Which of these fields or methods are inherited by the Person class? 1. getName(), setName(), studentID, getID() 2. getName(), setName(), name 3. None of them 4. studentID, name, getName(), setName(), getID() 5. name, getName(), setName(), getID()
None of them
Consider the following declaration. double[] sales = new double[50]; int j; Which of the following correctly initializes all the components of the array sales to 10. (i) for (j = 0; j < 49; j++) sales[j] = 10; (ii) for (j = 1; j <= 50; j++) sales[j] = 10;
None of these
To print the last element in the array named ar, you can write : A. System.out.println(ar.length); B. System.out.println(ar[length]); C. System.out.println(ar[ar.length]); D. None of these
None of these
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 1; if (j > 2) alpha[j - 1] = alpha[j] + 2; }
None of these
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 1; if (j > 2) alpha[j - 1] = alpha[j] + 2; } 1. alpha = {1, 2, 3, 4, 5} 2. alpha = {4, 5, 6, 7, 9} 3. alpha = {1, 5, 6, 7, 5} 4. None of these
None of these
Suppose you have the following declaration. int[] beta = new int[50]; Which of the following is a valid element of beta. (i) beta[0] (ii) beta[50]
Only (i)
Which of the following about Java arrays is true? (i) All components must be of the same type. (ii) The array index and array element must be of the same type.
Only (i)
Reason Brackets are missing
Not required for single statement IF statements or Loops.
exceptions happen when you try to use a variable that doesn't refer to an object yet.
NullPointerException
Reasons to use "int"
Numbers -2 billion to, 2 billion
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
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.
Object class
Object is base class of all Java classes. All Java classes extend (inherit) class Object either directly or indirectly. these 2 definitions are exactly the same: public class Book {...} public class Book extends Object {...}
A class is a type whose values are ______
Objects
'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.
Assignment Operators
Often we perform an operation on a variable, and then store the result back into that variable Java provides assignment operators to simplify that process For example, the statement num += count; is equivalent to num = num + count; Other assignment operators: -=, *=, /=, %=
Which of the following statements creates alpha, an array of 5 components of the type int, and initializes each component to 10? (i) int[] alpha = {10, 10, 10, 10, 10}; (ii) int[5] alpha = {10, 10, 10, 10, 10}
Only (i)
Reference Assignment
Once a String object has been created, neither its value nor its length can be changed (it's immutable) However, its reference variables can change
Inheritance
One class can be used to derive another via inheritance Classes can be organized into hierarchies
static
One copy and everyone can see it
message dialog
The general name for a dialog that displays messages to users.
Inheritance
One of the 3 main pinnacles of object-oriented programming (the others being encapsulation and polymorphism). Inheritance is a means by which a class extends another class, it acquires the properties and behavior of the class that's being extended. Sometimes called generalization/specialization, also called an "is a" relationship. For example, the class declarations of Book, Audio, and Periodical are shown below: package domain; public class Book extends LibraryItem { // properties and behavior of Book go here } package domain; public class Audio extends LibraryItem { // properties and behavior of Audio go here } package domain; public class Periodical extends LibraryItem { // properties and behavior of Periodical go here } class can only extend one other class -- cannot extend multiple classes
Breakpoint
One reason to set a _____ is to be able to examine the values of variables at that point in the application's execution.
next()
One word String
Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following sets of statements are valid (both syntactically and semantically) in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); 1. Both (i) and (ii) 2. Only (ii) 3. Only (i) 4. None of these
Only (i)
Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following sets of statements are valid (both syntactically and semantically) in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); 1. Only (ii) 2. None of these 3. Only (i) 4. Both (i) and (ii)
Only (i)
Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Which of the following statements correctly instantiate the Rectangle object myRectangle? (i) myRectangle Rectangle = new Rectangle(10, 12); (ii) class Rectangle myRectangle = new Rectangle(10, 12); (iii) Rectangle myRectangle = new Rectangle(10, 12); 1. Only (ii) 2. Only (iii) 3. Only (i) 4. Both (ii) and (iii)
Only (iii)
Private variable declaration?
Only applies to that class. ex. private String first;
Danger of using GIT
Only one repository.
The lifetime of a method's local variable is
Only while the method is executing
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.
logical operators
Operators (&&, ||, &, |, ^ and !) that can be used to form complex conditions by combining simple ones.
relational operators
Operators < (less than), > (greater than), <= (less than or equal to) and >= (greater than or equal to) that compare two values.
equality operators
Operators == (is equal to) and != (is not equal to) that compare two values.
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.
Expressions
Order of operations is applied: Multiplication, division, and remainder are evaluated before addition, subtraction, and string concatenation Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order Assignment operator is last
Another Example
Output A quote by Abraham Lincoln: Whatever you are, be a good one.
During runtime, value assigned that exceeds positive bounds of a variable
Overflow error
Overriding*
Overriding and overloading support polymorphism. - Abstract class (or concrete class) implement method - subclass with same signature override superclass method. - JVM begins at bottom of type hierarchy and searches up until match found to determine which method to run. - within subclass can call superclass method with super.method()
Incrementing
The process of adding 1 to an integer.
A _____________ is like a blank in a method definition...
Parameter
Methods
Part of an Object's behavior.
Operator && __.
Performs short-circuit evaluation
Task (ANT)
Piece of code that can be executed - can have multiple attributes (arguments) name: name of task <name attribute1="value1" attribute2="value2"...>
FlowLayout
Place components in the window from left to right, top to bottom.
Nesting
Placing an if...else statement inside another one is an example of ____ if-else statements.
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)
overloaded
a class having more than one method with the same name
Head pointer (GIT)
Points to the current branch.
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.
PreparedStatement (JDBC)
Precompiled SQL statements at object creation time rather than execution time. - Use ? to indicate parameters for the statement and fill in later. public static final String SELECT_SQL = "SELECT * FROM names ORDER BY age"; select = connection.prepareStatement(SELECT_SQL); ResultSet rs = select.executeQuery(); insert.setString(1, "Zaphod Beeblebrox"); insert.setInt(2, 26); insert.executeUpdate(); // So 1 is names and 2 is age.
What is assumed to be true when a method is called
Precondition
draw point at (x, y)
StdDraw.point(x, y);
set pen color
StdDraw.setPenColor();
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
Declare the data type of a variable.
Primitive types are used to declare the data types of variables where a variable is a named memory location. datatype variableName = initialvalue; The following statements illustrate the use of Java's eight primitive data types in variable declarations: char c = 'a'; Boolean succeeded = false; byte age = 0; short index = 0; int ssn = 0; long length = 0; float pi = 3.14159f; double d = 0.0; floating point literals are defaulted to a "double" data type. To compile certain types, such as float, add a suffix to the literal: float pi = 3.14159f;
Integral Types
Primitive types, all signed : byte, short, int, long. Fixed length, regardless of platform. Can all take integer literals. An integer variable can hold the result of an *arithmetic expression*.
System.out.println("Hello")
Prints Hello to console on a new line.
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
Inheritance*
Process where one object acquires the properties of another.
OO definitions
Programming paradigm that views programs as cooperating objects, rather than sequences of procedures Focuses on design of abstract data types, which define possible states and operations on variables of that type
Objects
Programs that you create. These can be thought of as physical items that exist in the real world.
Promotion Conversion
Promotion happens automatically when operators in expressions convert their operands Example: int count = 12; double sum = 490.27; double result = sum / count; The value of count is converted to a floating point value to perform the division calculation
font property
Property specifying font name (Times New Roman), style (Bold) and size (12) of any text.
background property
Property that specifies the background color of a content pane component.
size property
Property that specifies the width and height, in pixels, of a component.
Executable
Pseudocode usually only describes ____ lines of code.
declare a class
Public Class MemorizeThis {
Access Control
Public or Private; Determines how other objects made from other classes can use the variable, or if at all.
set up main method
Public static void main (string[], args) {
pen size to 0.05
StdDraw.setPenRadius(0.05);
git push
Publishes committed local files to remote repo.
Commit
Publishes file to GIT directory (Repository). Making it accessible by team. Use 'git commit -m "Message"'.
wait() (Thread Communication)
Puts current thread into blocked state. - can only call from method that has a lock (is synchronized) - Releases lock - Either waits specified time or until notified by another thread. - Best to put in while loop. - useful when all threads
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()
Single '
Quotation type used for character values.
Double "
Quotation type used for string values.
Caching truth or falsity
Rather than constantly checking the truth of a logical expression, sometimes it is better to store the result in a boolean and use that subsequently. For example 'boolean isFlying = height > 0.5f; if(isFlying == true) { flapWings(); }'
Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (size < capacity && value > 0) { a[size] = value; } 1. Reads up to 3 values and places them in the array in the unused space. 2. Reads one value and places it in the remaining first unused space endlessly. 3. Reads up to 3 values and inserts them in the array in the correct position. 4. Crashes at runtime because it tries to write beyond the array.
Reads one value and places it in the remaining first unused space endlessly.
Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (size < capacity && value > 0) { a[size] = value; size++; value = cin.nextInt(); } 1. Reads one value and places it in the remaining first unused space endlessly. 2. Crashes at runtime because it tries to write beyond the array. 3. Reads up to 3 values and places them in the array in the unused space. 4. Reads up to 3 values and inserts them in the array in the correct position.
Reads up to 3 values and places them in the array in the unused space.
Batch processing (JDBC)
Reduce overhead by executing a large number at once.
Stores (points to) the memory address of an object
Reference variable
read double
StdIn.readDouble();
read an integer
StdIn.readInt();
CallableStatement (JDBC)
Relies on a stored procedure. Can contain ? placeholders. public static final String INSERT_SQL = "call addName(?, ?)"; insert = connection.prepareCall(INSERT_SQL); ResultSet rs = select.executeQuery(); insert.setString(1, "Zaphod Beeblebrox"); insert.setInt(2, 26); insert.executeUpdate();
What does the following loop do? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; a[pos] = a[size - 1]; size--;
Removes the 1 from the array, replacing it with the 7. Array now unordered.
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).
Which of the following is not part of a method call? A. Return type B. Parentheses C. Method name D. All of the above are part of a method call
Return type
executeQuery (SQL command)
Returns ResultSet. Use for SELECT. ResultSet rs = st.executeQuery("SELECT * FROM names")
return function?
Returns and expression. ex. return first + " " + middle + " " + last;
execute (SQL command)
Returns boolean use for RENAME, DROP TABLE etc. st.execute("DROP TABLE names");
executeUpdate (SQL command)
Returns number of rows affected. Use for INSERT, UPDATE or DELETE. rows = st.executeUpdate("UPDATE names SET age = 21 WHERE name = 'John Howard'");
Integer.parseInt
Returns the integer equivalent of a String.
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
operator precedence
Rules of ____ ____ determine the precise order in which operators are applied in an expression.
Suite of tests
Run multiple test classes as a single test @RunWith(Suite.class) @Suite.SuiteClasses({class_name, ...})
Initialize scanner
Scanner keyboard= new Scanner (System.in);
declared scanner class
Scanner myScanner=new Scanner(System.in); System.out.println("Please enter #:");
What Java Can Do
Science and Technology -Popular machine learning libraries are written in Java: Mahout, Weka -Has been adopted in many distributed environments (Hadoop) Web development -Most web backend are developed using Java Mobile application development -Android development platform Graph user interface (GUI) design: menu, windows, ...
;
Semicolon
std print
StdOut.println();
Sequential
The process of application statements executing one after another in the order in which they are written is called ____ execution.
Data Type 'String'
Sequence of characters, a reference data type.
Java vocabulary
Set of all words and symbols in the language
name [row] [col] = value
Set the value of an element
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.
setEditable
Sets the editable property of the JTextArea component to specify whether or not the user can edit the text in the JTextArea.
setText
Sets the text property of the JTextArea component.
long totalMilliseconds = System.currentTimeMillis();
Sets total number of milliseconds since midnight, January 1, 1970, as a variable
Block Statements
Several statements can be grouped together into a block statement delimited by braces A block statement can be used wherever a statement is called for in the Java syntax rules The if clause, or the else clause, or both, could be governed by block statements
What is a Vector?
Similar to ArrayList, but synchronized
Logical AND and Logical OR
Since && and || each have two operands, there are four possible combinations of conditions a and b
Why is there a semicolon (;) at the end of each statement?
So Java knows that it is the end of a statement.
debugger
Software that allows you to monitor the execution of your applications to locate and remove logic errors.
return
Some methods, when called, __ a value to the statement in the application that called the method. The returned value can then be used in that statement.
Data Conversion
Sometimes it is convenient to covert data from one type to another For example in a particular situation we may want to treat an integer as a floating point value These conversions do not change the type of a variable or the value that's stored in it - they only convert a value as part of a computation Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) In Java, data conversions can occur in three ways: -assignment conversion -promotion -casting
White Space
Spaces, new lines, and tabs are called white space White space is used to separate words and symbols in a program Extra white space is ignored by the computer A valid Java program can be formatted many ways Programs should be formatted to enhance readability, using consistent indentation
method
Specifies the actions of an object.
type
Specifies what kind of thing a variable or a parameter is. Example: int, char, boolean...
isSelected
Specifies whether the JCheckBox is selected (true) or deselected (false): JCheckBox._____. (method)
What is program control?
Specifying the order in which statements(actions) execute in a program.
BorderLayout
Splits area into 5 predefined spaces: South, north, west, east and center
What are the local variables/parameters of a method stack known as?
Stack frames/activation records
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.
println
Starts a new line after displaying the text.
jdb
Starts the Java debugger when typed at the Command Prompt.
-Must end with a ; (semicolon)
Statements
Expressions
Statements that involve a mathematical equation and produce a result.
Static Variables and Threads
Static Variables are NOT thread safe. - Use ThreadLocal or InheritableThreadLocal type declaration
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");
Char Type
Store single unicode characters (international character set) and can be initialised with character literals enclosed in '. E.g. 'a'.
Distributed version control
Stored local, everyone has a copy of the entire repository and its history. - very low latency for file inspection, copy and comparisons.
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
public static String exampleMethod(int n, char ch) Based on the method heading above, what is the return type of the value returned? 1. char 2. String 3. int 4. Nothing will be returned
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 ";".
declare and initialize string variables
String itemToCheck; itemToCheck = "";
String declaration
String name = "";
Some String Methods
String name1 = new String("Steve Jobs"); int numChars = name1.length(); char c = name1.charAt(2); String name2 = name1.replace('e', 'x'); String name3 = name1.substring(1, 7); String name5 = name1.toLowerCase();
nextLine()
String of words
Which of the following lines of code implicitly calls the toString() method, assuming that pete is an initialized Student object variable?
String s = "President: " + pete;
System
a class that holds objects/methods to perform system-level operations, like output
Syntax to create a String
String s1 = new String("Hello World"); Can be created and initialized without using new: String s2 = "Hello World"; Can be concatenated with the + operator: String s3 = "Hello " + "World"; Operator == compares object references (and not the object's state), and since s1, s2 and s3 reference different String objects, == returns false: (s1 == s2); // returns false (s2 == s3); // returns false (s1 == s3); // returns false String's implementation of equals(Object) examines the values of the strings, this is true: s1.equals(s2); s2.equals(s3); s1.equals(s3); Strings objects created with the "new" operator that have the same value (the same string of characters) are always "equals()" to each other, but since they are different objects, they are never "==" to each other. One last subtle point: strings created using the double quote syntax with the same value without the new operator are always = = to each other. String s4 = "Hello World"; String s5 = "Hello World"; (s4 == s5); // returns true
How could you define a String variable named wrd and initialize it to the word cats?
String wrd = "cats";
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];
UML Diagrams - list the structure diagrams
Structure Diagrams - CCCODPP Composite Structure Class Component Object Deployment Profile Package
__________ method cannot throw more exceptions (either exceptions of different types or more general exception classes) than its superclass method.
Subclass
Method overriding
Subclass method can override methods from abstract or concrete classes. Within a subclass an override method in the super can still be called with super.method().
-
Subtraction operator
-- (unary decrement operator)
Subtracts one from an integer variable.
Signature rule (subtypes)
Subtypes must have signature-compatible methods for all of the supertypes methods. ArrayList<String> is a subtype of List<String>
Properties rule (subtypes)
Subtypes must preserve all of the provable properties of the supertype. Anything provable about A is provable about B.
Create an example using 'wild cards'
TODO v61
What is erasure?
TODO v62
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]);
Example of the Dot Operator in Use
System.out.println revisited There is a class called System, which contains an object reference variable out as one of its instance variables The object referenced by out has a method called println
Print statement
System.out.println("");
Command to print to the console? (what letter is capitalized)
System.out.println("Hello");
concatenate and output
System.out.println("this with "+ thisEnter);
What System.out method moves the cursor to the next line?
System.out.println()
print (return)
System.out.println();
To print the last element in the array named ar, you can write : A. System.out.println(ar[length-1]); B. System.out.println(ar[length()-1]); C. System.out.println(ar[ar.length-1]); D. System.out.println(ar[ar.length]);
System.out.println(ar[ar.length-1]);
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
%=
Take remainder and assign operator
%
Take remainder operator
git add
Tells git to track files. Tells git to stage tracked files that have been modified. Recursive.
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).
@Test(timeout = T)
Test fails if runs longer than T milliseconds.
@Test(expected = X.class)
Test is expected to throw exception X.
Glass box
Testing code (can see code)
Black box
Testing to specifications (code unseen)
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.
In the Swing GUI framework use event handlers to respond to GUI based actions. Case of component responding to button click, models works by requiring:
That the component implement the actionListener interface, that the JButton add the component as an active listener in its collection and that the component provide suitable responses to be called from within the actionPerformed method once the event is triggered.
What does empty Parenthesis at the end of a method declaration mean?
That the data for the method will be put in later.
Multiplies
The *= operator ____ the value of its left operand by the value of the right one and store it in the left one.
*decision*
The *diamond-shaped* symbol in a UML activity diagram that indicates a ____ is to be made.
The + Operator
The + operator is also used for arithmetic addition The function that it performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation If both operands are numeric, then it adds them The + operator is evaluated left to right, but parentheses can be used to force the order If both of its operands are strings, or if one is a string and one is a number, it performs string concatenation. But if both operands are numeric, it performs addition.
Assignment operator:
The = (the equals sign). Assigns a value to an identifier.
What is the ArrayList class a representation of?
The ArrayList class is an object-orientated representation of a standard Java array.
The Math Class
The Math class is part of the java.lang package The Math class contains methods that perform various mathematical functions These include: absolute value square root exponentiation trigonometric functions The methods of the Math class are static methods (also called class methods) Static methods never use instance variable values Math class does not have any instance variables Nothing to be gained by making an object of Math class Static methods are invoked through the class name - no object of the Math class is needed value = Math.abs(90) + Math.sqrt(100);
The Random Class
The Random class is part of the java.util package It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values nextFloat() generates a random number [0, 1) nextInt() generates a random integer over all possible int values (positive or negative) nextInt(n) generates a random integer [0, n-1]
More About System.out
The System.out object represents a destination (the monitor screen) to which we can send an output The System.out object provides another service in addition to println The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line
Diamond (in the UML)
The UML symbol that represents the decision symbol or the merge symbol, depending on how it is used.
size
The ____ of a variable holds the number of bytes required to store a value of the variable's type. For example, an int is stored in four bytes of memory and a double is stored in eight bytes.
name
The ____ of a variable is used in an application to access or modify a variable's value.
type
The ____ of a variable specifies the kind of data that can be stored in a variable and the range of values that can be stored, such as an integer holding 1, and a double holding 1.01.
+=
The _____ operator assigns to the left operand the result of adding the left and right operands.
==, <= and <
The ______ operators return false if the left operand is greater than the right operand.
workflow
The activity of a portion of a software system.
RGB value
The amount of red. green and blue needed to create a color.
Title bar
The area at the top of a JFrame where its title appears.
destructive
The process of assigning data (or writing) to a memory location, in which the previous value is overwritten or lost.
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.
multiple instances
The case when there are multiple objects from the same class instantiated at runtime.
semicolon ( ; )
The character used to indicate the end of a Java statement.
Which of the following statements about strings is NOT true? 1. The class String contains many methods that allow you to change an existing string. 2. A String variable is actually a reference variable. 3. When a string is assigned to a String variable, the string cannot be changed. 4. When you use the assignment operator to assign a string to a String variable, the computer allocates memory space large enough to store the string.
The class String contains many methods that allow you to change an existing string.
DecimalFormat
The class used to format floating-point numbers (that is, numbers with decimal points).
class declaration
The code that defines a class, beginning with the class keyword.
Escape Sequence
The combination of a backslash and a character that can represent a special character, such as a newline or a tab.
Source code:
The combination of the import statements and the program statements
javac command
The command that compiles a source code file (.java) into a . class file.
string1.compareTo (string2) < 0
The compareTo method compares strings in lexicographic order.
How Java Works
The compiled bytecode is not the machine language for traditional CPU and is platform-independent javac and java (two command-line tools) can be found in the directory of bin/ of Java Development Kit (JDK) you will install
JLabel
The component that displays text or an image that the user cannot modify.
Destination
The converted version of the source in a new form.
Functional decomposition is
The process of breaking a problem down into smaller pieces.
Iterator
The counter variable used to control a loop.
Class
The data type of an object
What is wrong with the following method call? displayValue (double x);
The data type of the argument x should not be included in the method call
The header of a value-returning method must specify this.
The data type of the return value
The header of a value-returning method must specify this. A. The method's local variable name B. The data type of the return value C. The name of the variable in the calling program that will receive the returned value D. All of the above
The data type of the return value
What does it mean in an && operator statement to have a dependent condition?
The dependent condition is the one that gets tested first and must come after the && operator
The Dot Operator
The dot operator (.) gives you access to an object's instance variables (states) and methods (behaviors) It says: use the Dog object referenced by the variable myDog to invoke the bark() method Think of a Dog reference variable as a Dog remote control When you use the dot operator on an object reference variable, it is like pressing a button on the remote control for that object
Decimal points
The double type can be used to store numbers with ____ ____.
keyPressed event
The event that occurs when any key is pressed in a JTextField.
Demo
The filename of the source file must be the same as the class name (###case sensitive###) java MyFirstApp (###not MyFirstApp.class###)
Polymorphism
The idea that we can refer to objects of different but related types in the same way.
class name
The identifier used as the name of a class.
if...else statement
The if statement can be extended to include an alternative code block to be executed if the header argument evaluates to false. For example 'if(isFlying) { flapWings(); } else { closeWings(); }'.
The if Statement
The if statement has the following syntax: if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression (must evaluate to either true or false) If the condition is true, the statement is executed. If it is false, the statement is skipped. An if statement with its boolean condition: if (total == sum) system.out.println("total equals sum"); Another if statement with its boolean condition: if (total != sum) system.out.println("total does NOT equals sum");
Attribute
The information that describe the object and show how it is different than other objects.
extends keyword
The keyword the specifies that a class inherits data and functionality from an existing class.
class keyword
The keyword used to begin a class declaration.
actionPerformed
The kind of event that occurs when a JButton is clicked.
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.
debugging
The process of locating and removing errors in an application.
setBounds
The location and size of a JLabel can be specified with _____.
Logical NOT
The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then !a is false; if a is false, then !a is true Logical expressions can be shown using a truth table. A truth table shows all possible true-false combinations of the terms.
straight-line form
The manner in which arithmetic expressions must be written so they can be typed in Java code.
Program Development
The mechanics of developing a program include several activities: -writing the program (source code) in a specific programming language (such as Java) using an editor -translating the program (through a compiler or an interpreter) into a form that the computer can execute -investigating and fixing various types of errors that can occur using a debugger Integrated development environments, such as Eclipse, can be used to help with all parts of this process
The 2nd argument passed to method JOptionPane.showMessageDialog is ____.
The message displayed by the dialog
nondestructive
The process of reading from a memory location, which does not modify the value in that location.
String Concatenation Operator
The name for a plus (+) operator that combines its two operands (Strings) into a single String.
The UML decision/merge symbols can be distinguished by _.
The number of flowlines entering or exiting the symbol and whether or not they have guard conditions. (Both of the above)
Objects and the Heap
The number of objects that a program creates is not known until the program is actually executed Java uses a memory area called the heap to handle this situation, which is a dynamic pool of memory on which objects that are created are stored When an object is created, it is placed in the heap -Two or more references that refer to the same object are called aliases of each other -One object can be accessed using multiple reference variables -Changing an object through one reference changes it for all of its aliases, because there is really only one object
Which of the following statements is NOT true?
The operator new must always be used to allocate space of a specific type, regardless of the type.
Conditional Statements
The order of statement execution is called the flow of control A conditional statement lets us choose which statement will be executed next The Java conditional statements are the: -if and if-else statement -switch statement
value of a variable
The piece of data that is stored in a variable's location in memory.
content pane
The portion of a JFrame that contains the GUI components.
What is an actual parameter?
The value passed into a method by a method call
return value
The value that comes back from a method after it is run. In the following method: public int calculateMonth(String name), the return value is an integer.
state
The values of all of the variables in an object at a given time.
int value
The variable type that stores integer values.
Class Statement
The way you give your computer program a name.
Boolean Literal
The words true and false.
Primitive Types
There are eight Primitive data types in Java Four of them represent integers • byte, short, int, long Two of them represent floating point numbers • float, double One of them represents a single character • char And one of them represents boolean values • boolean
Language Levels
There are four programming language levels. Each type of CPU has its own specific machine language The other levels were created to make it easier for a human being to read and write programs
Comments
There are two forms of comments, which should be included to explain the purpose of the program and describe processing steps They do not affect how a program works
Another way to generate a Random Number
There is another way to generate a random double number [0,1) double newRand = Math.random(); as opposed to import java.util.Random; Random generator = new Random(); float newRand = generator.nextFloat();
double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is the value of vals[4][1] in the array above? 1. 7.1 2. There is no such value. 3. 7.3 4. 1.1
There is no such value.
arithmetic operators
These operators are used for performing calculations.
Logical Operators
They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands)
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.
if...else statement
This double-selection statement performs action(s) if a condition is true and performs different action(s) if the condition is false.
-g compiler option
This flag or option causes the compiler to generate debugging information that is used by the debugger to help you debug your applications.
What is the definition of the Java class Library A.K.A Java A.P.I(Java Application Programming Interface)?
This is the list of preprocessed classes, packages, and methods that you may use at your disposal such as the Math....() methods.
Do While Execution
This loop will always execute at least once, even if the conditions are not met.
parts of a program set up to run on their own while the rest of the program does something else.
Threads
javax.swing.*;
To create lightwieght components for a GUI.
java.net.*;
To develop a networking application.
java.awt.*;
To paint basic graphics and images.
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 JCheckBox is selected when the isSelected method returns __.
True
T or F: The name of a local variable can be reused outside of the method in which it is declared ?
True
True or False, by catching a exception superclass you can also catch any subclass exceptions that are thrown?
True
Classes contain methods that determine the behaviors of objects
Two common usages of methods: -change the values of the instance variables, e.g., making deposits to a bank account object should change its current balance -methods can behave differently based on the values of the instance variables, e.g., playing a "Darkstar" song object and a "My Way" song object should be somehow different...
Boolean Values
Type of variable that cannot be used in any Casting.
Prefix Operator
Unary operator that appears before it's operand. E.g. the negation operator '-' which negates the value to it's right. e.g. 'int negative speed = -speed;'
subclasses of the RuntimeException and Error classes and are usually thrown by the Java runtime itself.
Unchecked exceptions
Hashcode (GIT)
Uniquely identify each commit.
Input Tokens
Unless specified otherwise, white space is used to separate the tokens (elements) of the input White space includes space characters, tabs, new line characters The next method of the Scanner class reads the next input token and returns it as a string Methods such as nextInt and nextDouble read data of particular types (int and double)
setText
Use _____ to set the text on the face of a JButton.
JInternalFrame
Use for Multiple Document Interface (MDI)
Observable
Use instead of Subject interface for Observer pattern, Observable aware of its status and it's Observers unlike Subject.
Scanner keyboard = new Scanner(System.in); x = keyboard.nextInt(); y = keyboard.nextLine();
Use scanner for keyboard input. nextInt() scans in next token as an integer nextLine() scans in current line
JDesktopPane
Use to create a virtual desktop or multiple-document interface. Use as main frame when you want to have internal frame.
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
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.
Throwable
Used to define own exceptions.
showMessageDialog
Used to display a message dialog: JOptionPane.____.
Nested if Statements
We can put an if-else statement as part of another if statement, these are called nested if statements if ( condition1 ) if ( condition2 ) statement1; else statement2; An else clause is always matched to the last unmatched if (no matter what the indentation implies) Braces can be used to specify the if statement to which an else clause belongs Both if statements must be true for statement 1 to be printed
Behavior
What an object does.
Escape Sequence
What if we wanted to print the quote character? The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\) System.out.println ("I said \"Hello\" to you.");
i
What is the standard convention for un-named variables?
Quick Check: Nested Statements
What output is produce by the following code fragment given the assumptions below?
Post Condition?
What will be true after a method is called
What is counter controlled repetition?
When a loop is controlled by a counter such as x>3
What is sentinel controlled repetition?
When a loop is controlled by a sentinel value such as s!=3
Void
When a method does not return a value.
What is control statement stacking?
When a number of control statements are placed one after another in a sequence within a program.
Implicit type coercion:
When a value of one data type is automatically changed to another data type.
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.
Garbage Collection
When an object no longer has valid references to it, it can no longer be accessed by the program The object is useless and therefore is called garbage Java performs automatic garbage collection periodically, returning and object's memory to the system for use In other languages the programmer is responsible for performing garbage collection
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 should camel case be used?
When defining the type of an input: int greatNumber, dbl, char etc. When naming a method or class: class( QuadraticFormula), Method(equationProcessor)
Encapsulation
When each object protects its own information.
When can you not use a (while) statement instead of a (for) statement? How does it differ?
When the (while) statement has an increment after a continue statement, it is different than a (for) statement. they differ in execution.
When naming variables, what is camel case?
When the words following the first word having a captial first letter: alphaQuadron
truncating
When you are ____ in integer division, any fractional part of an integer division result is discarded.
Initialization
When you first store something in a variables memory location.
declaring
When you specify the type and name of a variable to be used in an application, you are ____ a 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.
The _ statement executes until its loop-continuation condition becomes false.
While
while(insert argument here) { insert code here }
While loop
The Import Statement
Why didn't we import the System or String classes explicitly in earlier programs? All classes of the java.lang package are imported automatically into all programs It's as if all programs contain the following line: import java.lang.*; The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported
Dog Example
Will see the syntax of creating objects (with unique instance variables) and then calling methods from the class later The computer will read this and decide which bark to use Just think of it like you name something (object) and give it variables and then it takes the information and outputs something (method)
Nesting Conditional Constructs
Within a code block, additional flow control structures can be nested. For example an if statement could be nested within the code block of another if statement, or a switch statement within the case of another switch statement. Note that stylistically, nesting results in further indentation so that flow can be followed easily.
Reserved words
Words that have predefined meanings that cannot be changed
int i = 10; do{ i = i + 5; System.out.print(i); } while (i > 5);
Write an endless do loop where i=10
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
Increment and Decrement
Write four different program statements that increment the value of an integer variable total. Count ++ Count = Count + 1 Count = ++ Count Count += 1
What output is produced by the following?
X: 25 Y: 65 Z: 30050
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 standard Java arrays be multi-dimensional?
Yes, standard Java arrays can be multi-dimensional; each set of square brackets represents a dimension.
You can examine the value of an expression by using the debugger's ____ command.
set
You can modify the value of a variable by using the debugger's ____ command.
Java Reserved Words
You cannot use use reserved words for your own names (Java identifiers)
Refactor - extract method
You have a code fragment that can be grouped together: turn the fragment into a method with a self-explanatory name.
Refactor - split loop
You have a loop doing two things - duplicate the loop. for(Tree tree : trees) // do x // do y Will be separated into two loops, one doing x and the other doing y.
Book-Title
You should use _____ capitalization for a JButton's name.
"
\"
output JTextField
a JTextField used to display calculation results. The editable property of an output JTextField is set to false with setEditable.
What does /* suggest
a comment
Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long If you define a subclass of Person, like Student, and add a single constructor with this signature Student(String name, long id), that contains no code whatsoever, your program will only compile if the superclass (Person) contains: 1. an explicit constructor of whatever type 2. a setName() method to initialize the name field 3. an implicit constructor along with a working constructor 4. a default or no-arg constructor
a default or no-arg constructor
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
A local variable disappears when...
a method invocation ends.
println
a method that prints characters to the screen and moves to the next line
a method that prints characters to the screen and remains on the same line
Formal parameters of primitive data types provide ____ between actual parameters and formal parameters.
a one-way link
int
a primitive data type, integer
Run-time errors (Error Type 2/3)
a problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally
Logical or semantic errors (Error Type 3/3)
a program may run, but produce incorrect results, perhaps using an incorrect formula
Virus
a program that can enter a computer and perhaps destroy information
A ________ is used to terminate all java
a semi colon ;
Java standard class library (Java API)
a set of predefined classes and methods that other programmers have already written for us System, out, println and String are not Java reseved words, they are part of the API
Object reference
a value that denotes the location of the object in memory
What is the sentinel value?
a value to be typed in to stop a loop
short hand a = a + 1;
a++;
short hand a = a - 1;
a--;
String comparing a to b
a.compareTo("b");
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements replaces the last object in the collection with element?
a.set(3, element);
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
What does ++c do? and what is it called? And --c?
adds 1 to c then prints out result. Prefix increment subtracts 1 from c then prints out result. Prefix decrement
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
Abstract Classes & Interfaces
abstract class - class that is never intended to be instantiated as an object. Its purpose is to serve as a base class that provides a set of methods that together form an API. classes that inherit the abstract class can override its base behavior as necessary. Because the derived classes can be instantiated, they are referred to as concrete classes. This combination of an abstract base class and one or more concrete derived classes is widely used in industry and is known as the "Template" design pattern. class is identified as being abstract by pre-pending the keyword "abstract" to the class definition. package domain; public abstract class LibraryItem { } abstract keyword prohibits a LibraryItem from being instantiated with the "new" keyword. When a class is denoted as abstract, it typically means that one or more of its methods are also abstract, which implies they have no implementation. method is declared to be abstract by using the "abstract" keyword: public abstract boolean validate(); there's no {...} following the signature; rather, a semicolon is present. method must not have an implementation following its signature, the enclosing class must be declared to be abstract. implementation of validate() in one of the concrete derived classes: Book. package domain; public class Book extends LibrarayItem { public boolean validate() { if (id <= 0) return false; if (title == null || title.equals("")) return false; if (author == null || author.equals("")) return false; if (pages <= 0) return false; return true; } } another technique for declaring "abstract" interfaces by way of the "interface" keyword: package domain; public interface IValidator { public boolean validate(); } interface construct is used to capture zero or more method signatures without specifying their implementation details. methods enclosed within an interface definition must be "abstract" in the sense that they must not provide an implementation (i.e., {...}), but the abstract keyword is not necessary. interfaces are implemented in classes with the "implements" keyword. User and Login are not defined as abstract since implementations are provided for the validate() method. package domain; public abstract class LibraryItem implements IValidator { public abstract boolean validate(); } uniform interface for validating objects. package domain; public class User implements IValidator { public boolean validate() { } } package domain; public class Login implements IValidator { public boolean validate() { } } while Java does not support multiple class inheritance , it does support the implementation of multiple interfaces in a single class. To serialize Login objects across a secure network Login class needs to implement the Serializable interface. package domain; public class Login implements IValidator, Serializable {...} Serializable does not contain any methods, known as a Marker Interface. Marker interfaces, used to "mark" classes (and hence their objects) as "one of those," but without any additional methods. In summary, interface constructs are used to separate interface abstractions from implementation details.
values[i] = 0;
access element of array at position i (count starts from 0)
Constructor Definition
accessSpecifier ClassName(parameterType paramterName, ...) { constuctor body }
Instance Field Declaration
accessSpecifier class ClassName { accessSpecifer fieldType fieldName; }
Class Definition
accessSpecifier class ClassName { constructors methods fields }
Method Definition
accessSpecifier returnType methodName(parameterType parameterName, . . .) { method body }
this.field
accesses an instance variable in the current class
if your method has been declared with a throws clause, don't forget to:
actually throw the exception in the body of your method using the throw statement.
+
add operator
GridLayout
all components are placed in a table like structure and are the same size.
Associations
allow classes (and their objects) to form relationships with one another. These relationships facilitate object collaboration. two types of associations: "Has a" relationships: Abstracts/models the concept of containment (e.g., a Customer has an Account; or in other words, the Customer contains an Account). "Uses a" relationships: Abstracts/models the concept of using (e.g., a Workflow manager uses various services to accomplish a task [to get some work done]). "has a" relationship with another class if it has a data member of that particular type. package domain; public class User { private Account account = new Account(); } abstracting a Login class that contains the user's credentials (username, password) and associating it with the User by declaring Login data member: package domain; public class User { private Login login = new Login(); private Account account = new Account(); } Once you declare a data member as an object type, you have essentially created a "has a" relationship between the two objects. "uses a" relationship, only difference between a "has a" and "uses a" relationship is where the declaration is made. "uses a" relationships are defined within method declarations (and not as data members of the enclosing class). So for instance, suppose a particular method needs to use a Date object to timestamp a message: package domain; public class Logger { public generateLogMessage(String message) { Date date = new Date(); } } The above method instantiates a Date object locally within the scope of the method, not as a data member (at the class/object level). "uses a" relationship. So we can summarize "has a" and "uses a" relationships as follows: "Has a" relationships are realized as object declarations located at the class level (i.e., as data members). "Uses a" relationships are realized as object declarations located within the scope of a method.
Type casting
allows one data type to be explicitly converted to another
concatenation operator
allows strings to be combined in Java
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = 2 * j; if (j % 2 == 1) alpha[j - 1] = alpha[j] + j; } 1. alpha = {0, 2, 4, 6, 8} 2. alpha = {0, 2, 9, 6, 8} 3. alpha = {3, 2, 9, 6, 8} 4. alpha = {0, 3, 4, 7, 8}
alpha = {3, 2, 9, 6, 8}
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 5; if (j % 2 == 1) alpha[j - 1] = alpha[j] + 2; }
alpha = {8, 6, 10, 8, 9}
Exception
an abnormal state or error that occurs during runtime and is signaled by the operating system
Logic error
an error such that a program runs, but unexpected results are produced. Also referred to as a design error
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.
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
numeric data types
another name for primitive data types; most commonly int and double
String concatenation
append a string or value to another string
How do you test a diagram as to whether it is structured?
apply the rules backwards to reduce it to the simplest activity diagram.
The first element in the array created by the statement int[] ar = { 1, 2, 3 }; is :
ar[0]
The last element in the array created by the statement int[] ar = { 1, 2, 3 }; is :
ar[2]
Arrays
are NOT collections. Do NOT: 1. support iterators 2. grow in size at runtime 3. are not threadsafe Primitive types of a fixed size.
Objects...
are instances (instantiations) of classes, as objects are created, the properties that are defined in the class template are copied to each object instance and assigned values. Thus, each object has its own copy of the class properties
double[] values = new double[10]; double[] moreValues = {32, 54, 67.5};
array declaration and initialization
Array Element Access
arrayReference[index]
Assertion code
assert boolean_expression; assert boolean_expression : displayable_expression;
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
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
What is the syntax of a sequence control flow example?
base = rate * hours; taxes = base * taxRate; net = base - taxes; count++; count--;
Iterable Interface
base interface for all interfaces of the Java collection framework (excluding Map). Iterable defines exactly one method, namely: Iterator iterator(); This allows you to get an Iterator for iterating over the elements of a collection. Since all other collection interfaces extend Iterable (either directly or indirectly), they all inherit the above method; that is, they all provide an iterator for iterating over their elements. For example, the Collection interface directly extends Iterable, and hence, if you have a Collection, you can get an iterator to iterate over its elements: Collection<Book> coll = getOverdueBooks(); Iterator<Book> iter = coll.iterator(); while (iter.hasNext()) { Book book = iter.next(); } Because the need to iterate over all items in a collection is a common practice, the method iterator() is placed in the base interface Iterable, and then through inheritance, it's made available to all collections that extend Collection (because Collection extends Iterable). The extension of Iterable by Collection (and then List, Set, and Queue) is known as interface inheritance.
b
bb
Objects
belong to classes
{ 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*.
An open brace is always followed by a close
brace }
Never put a semi-colon before an open
brace{
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
Use an Addition assignment operator to make c=5 when c=2
c += 3
Make c not equal to b
c!=b
Use a division assignment operator to make c=4 when c=8
c/=2
this.method()
calls an instance method in the current class.
What is a local variable?
can be used only in the method that declares it from point of declaration to end of method
A method that has the signature void m(int[] ar) : A. can change the values in the array ar B. cannot change the values in the array ar C. can only change copies of each of the elements in the array ar D. None of these
can change the values in the array ar
Application defined classes
classes that you create for your specific application Login -username : String -password : String +setUsername : (username : String) +getUsername () : String +setPassword : (password : String) +getPassword () : String +validate() : boolean +equals(Login Login) : boolean two private data members: username and password; the minus sign means the properties are hidden in the class, cannot access them outside of class. When a class does not explicitly provide a constructor, Java implicitly provides a default constructor (one that takes no arguments). The default constructor is available for use even though it's not shown.
if a method might throw multiple exceptions you declare them all in the throws clause separated by ______
commas
//
comment
if (string1.equals(string2))...
compares equality of 2 strings
Conditional operator
condition?truepath:falsepath; (hours<12 ? "AM" : "PM";)
arithmetic expression
consists of operands and operators combined in a manner familiar from algebra
When you write an explicit ____ for a class, you no longer receive the automatically written version.
constructor
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
Postincrement
counter++
Postdecrement
counter--
Example of three references and two object
d and c are aliases, because they both reference the same book
Semantic rules:
determine the meaning of instructions in a programming language.
HashSet
data is stored in a table with an associated hash code. Has code is used as an index. Contain NO duplicates, elements kept in order.
primitive
data such as numbers and characters, NOT objects
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
method toString()
default behavior is to return the object's fully qualified name followed by the object's hash code. book1.toString(); //returns: Book@1ea2df3 book2.toString(); //returns: Book@1ea2df3 this information is typically not useful, it's common to override toString().
semantics
define the rules for interpreting the meaning of statements
Depend (ANT)
determines which classfiles are out of date with respect to their source.
Given the following method header, which of the method calls would cause an error? public void displayValues(int x, int y)
displayValue(a,b); // where a is a short and b is a long
/=
divide and assign operator
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 initialize primitive variables
double thisIsDouble; int thisEnter; thisIsADouble=0.0; thisEnter=0;
declare and initial double array, points, with length N
double[] points = new double [N];
Transaction processing (JDBC)
e.g. Funds transfer commit() rollback() savepoint..
Math.exp(x)
e^x
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements assigns the first object in the collection to the variable element?
element = a.get(0);
Arrays.toString(values) = [4,7,9...]
elements separated by commas with brackets
_______________—the specification of attributes and behavior as a single entity—allows us to build on our understanding of the natural world as we create software.
encapsulation
for (typeName variable: array/collection) { sum = sum + variable; }
enhanced for loop for arrays; adds each element of array to sum (declared before loop)
Enum
enumerated type of class. - list of constants. - use when need predefined list of values that do not represent values of textual data
Your classes should generally have both an _______ method and a _____ method.
equals && toString
\\
escape character for backslash
Exception Handling
events (e.g., errors) that disrupt the normal flow of execution. Examples of software exceptions: - Dividing by zero. - Using an unassigned object reference (that points to null) to invoke a method. - Failure to open/read/write/close a file. - Failure to open/read/write/close a socket connection. - Database errors. when a program executes, described as a call stack, ordered list of the active methods called up to the current point in time. stack starts with the main entry point and documents the active methods that are currently under call. once an exception occurs, it must be handled, or the program aborts. the JVM marches through the call stack looking for the nearest handler for the exception. If one is found, control is transferred. Otherwise, the program terminates.
In Java, the strange events that might cause a program to fail are called
exceptions
Defining Exceptions
exceptions are classes that extend the class Exception either directly or indirectly. For example, just a few of the many exceptions defined by the Java API. public class ClassNotFoundException extends Exception {...} public class IOException extends Exception {...} public class NullPointerException extends Exception {...} public class NumberFormatException extends Exception {...} The Exception class, most of its behavior is inherited from a base class named Throwable, which defines a message (String) property and a corresponding accessor, getMessage(). defining a custom exception that denotes a failed login: public class LoginFailedException extends Exception { public LoginFailedException() { super(); } public LoginFailedException(String msg) { super(msg); } } when defining your own exceptions, provide at least two constructors, default constructor and a constructor that takes a message string as a parameter. In both cases, the base constructor of Exception is invoked using the keyword super.
A ____________ relationship exists between two classes when one class contains fields that are instances of the other class.
has-A
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
To prevent subclasses from overriding an inherited method, the superclass can mark the method as:
final
Constant definition
final typeName variableName = expression;
optional 3rd block of code in a try/catch that executes NO MATTER WHAT:
finally{ }
primitive data types
first category of Java variables such as numbers, characters, and Booleans
-32 bits Range: -big to big -Must put an f at the end of the value EX: 98.6f; <--- f won't print
float
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;
What is the format for a, for, statement?
for (initialization;loopContinuationCondition;increment) statement (Initialization=declared variable and value) (loopContinuationCondition=i<5) (Statement=(println)
for loop (use i and N)
for (int i = 0; i < N; i++) { }
How do you make loops?
for (int i; i < 10; i++) { //Program }
What is the syntax of a looping control flow example?
for (int i=1; i<10; i++) { ... } while (x < y) { ... } do { ... } while (x<y)
Loop count to 10
for(count = 0; count<11: count++);
Close Window (GUI)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Hamcrest
framework to help write JUnit test cases. assertThat("HelloClass", is(equalTo(Greeter.greeting())))
When you define a subclass, like Student, and don't supply a constructor, then its superclass must: 1. have no constructors defined 2. have no constructors defined or have an explicit default (no-arg) constructor defined. 3. have an explicit copy constructor defined 4. have an explicit default (no-arg) constructor defined 5. have an explicit working constructor defined
have no constructors defined or have an explicit default (no-arg) constructor defined.
public static double cubeVolume (double sideLength)
header for method
Declare a variable
int n;
How could you define an integer named num and initialize it to 394?
int num = 394;
/t
horizontal tab; causes the curson to skip over to the next tab stop
How do you make if...else statements?
if (arg) { } else { } if (arg) { } if (arg) { } else if (arg) { } else { } For example if (e < 10) { //What happens if e < 10 } else { //What happens otherwise } Switch statements are better for if...else if...else.
The if Statement
if (condition) statement; else statement;
if else structure
if (thisEnter > 10) system.out.println("yep>10"); else system.out.println("nope<10"); and
if statement (many commands)
if (true) { }
if / else
if (true) { } else { }
What is the syntax of a decision control flow example?
if (x == y) { ... } else { ... } switch (index) { case 0: {...} case 1: {...} default: {...} }
if (condition) { statements1 } else { statements2 }
if statement (else not required in all cases)
Importing a Class from a Package
import packageName.ClassName;
import java.util.Scanner
imports Scanner library
Graphics context
in java, an object associated with a component where the images for that component are drawn
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 --; }
Name the 6 numeric data types
int, double, short, long, byte, and float
++/--
increment/decrement; add 1 to/subtract 1 from the variable
\n
indicates a newline character
\t
indicates a tab character
What does the keyword, Extends, do?
indicates that the class before the keyword is an enhanced type of the class following the keyword meaning that the methods and data from the class before the keyword are added on to the methods of the class after the keyword.
What is the format for a, while, statement?
initialization; while (loopContinuationCondition) { Statement increment; } ex: pg 91
-32 bits Range: -2,147,483,648 to 2,147,483,647 No rules
int
int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the data type of the array above? 1. num 2. int 3. char 4. list
int
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } What is the return type of the method above?
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;
You can create an array of three integers by writing :
int ar[] = new int[3];
Declare & Initialize a variable
int n = 5;
this()
invokes the constructor.
The ____________ relationship occurs when members of one class form a subset of another class, like the Animal, Mammal, Rodent example we discussed in the online lessons. 1. encapsulation 2. composition 3. is-A 4. has-A
is-A
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"
Keyboard integer input
keyboard.nextInt();
Where should the default statement be placed within a switch statement?
last
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
LinkedList: peek methods
list.peek(); //peeks head list.peekLast(); // peeks last element
API documentation
lists the classes and methods of the Java library
&&
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
run()
main method for an individual thread
Helper methods should be
marked as private
static
means only one copy exists of the field or method and it belongs to the class not an instance. Its shared between all instances of the class.
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():
The two main kinds of methods:
methods that return a value / void methods
adding a throws clause to your method definition simply means that the method _______ throw an exception if something goes wrong,
might
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } What is the name of the method above?
minimum
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is a valid call to the method above?
minimum(5, 4);
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is a valid call to the method above?
minimum(5, 4);
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is a valid call to the method above? 1. minimum(int x, int y); 2. minimum(int 5, int 4); 3. minimum(5, 4); 4. public static int minimum(5, 4);
minimum(5, 4);
when writting multiple catch clauses you should always start with ______
more specific subclass exceptions and end with more general superclass exception catches (because if you start with a superclass exception catch you wont know what the specific exception was.
ArrayList: 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();
Initialize a variable
n = 5;
Identifier
name of a variable, method or class
Length method
name.length()
final int VOLUME = 8
names constant integer
You are ____ required to write a constructor method for a class.
never
Keyword: new
new - creates Class objects and a constructor as shown below: Book book1 = new Book(); Book book2 = new Book("SomeTitle", "SomeAuthor", false); Constructors are invoked with the "new" keyword as shown below: Book book1 = new Book(); Book book2 = new Book(1); Book book3 = new Book(1, "Gone with the Wind", "Margaret Mitchell"); Using a constructor that allows you to initialize the object with passed-in parameters. Using the default constructor, followed by the invocation of set(...) methods.
New
new is a Java reserved word that triggers all kinds of actions. goes back to the heap (free memory space), reserves a chunk of the memory for the real value (address) Java actually invokes a special method called constructor, provided by programmer, which does the proper initialization new is the only thing that produces a reference type
______\n______ is the escape sequence for
new line
Thread Life Cycle
new process > WAITING > RUNNING > BLOCKED - waiting starts and runs or times out - runs unless blocked until unblocked or until complete
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()
Is the break statement on a switch needed for the last statement/default?
no
Primitive data types
numbers, characters, and Booleans. combined in expression with operators
Method call
object.methodName(parameters);
Integer.parseInt or Double.parseDouble
obtains the integer value of a string containing the digits
Method overloading
occurs when a class contains more than one method with the same name. Within a class, methods can have the same name if there's difference: The number of parameters. And/or the type parameters. And/or order of parameters. The determination of which overloaded method to invoke is a compile-time decision; hence, it is sometimes referred to as static binding. Library library = new Library(); Book book = new Book(); library.add(book); User user = new User(); library.add(user); Notice that the statement library.add (book) is clearly targeting the add (Book) method because of the parameter data type, Book. Similarly, the statement library.add(user) is clearly targeting the add(User) method because of the parameter data type, User. Since these decisions can be determined at compile time, the binding is said to be static.
Private
only accessible if in same 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
Service Threads
or daemon threads - Contain never ending loop - Receive and handle service requests - Terminates only when program terminates. So detects when all non-daemons finished then kills daemons and programs terminate.
to swap values of integers you need a...
place holder
What does c++ do? and what is it called? and c--?
prints result then adds 1. Postfix increment prints result then subtracts 1. Postfix decrement
Prints to the current line(single function)
Prints x on the same line
print(x)
displays the sequence of method calls that led to the statement that generated the exception.
printStackTrace()
Prints a formatted string
printf
Prints to a new line and flushes the buffer.
println
Prints x on the same line, then moves the cursor to the next line
println(x)
Which modifier is used to specify that a method cannot be used outside a class?
private
java.lang.Thread
provides infrastructure for multithreaded programs. can extend thread but issue with multiple class inheritance so extend runnable instead.
Clock -hr: int -min: int -sec: int +Clock() +Clock(int, int, int) +setTime(int, int, int): void +getHours(): int +getMinutes(): int +getSeconds(): int +printTime(): void +incrementSeconds(): int +incrementMinutes(): int +incrementHours(): boolean +equals(Clock): boolean +makeCopy(Clock): void +getCopy(): Clock Which of the following would be a default constructor for the class Clock shown in the figure above? 1. public Clock(0, 0, 0) { setTime(); } 2. private Clock(10){ setTime(); } 3. public Clock(0) { setTime(0); } 4. public Clock(){ setTime(0, 0, 0); }
public Clock(){ setTime(0, 0, 0); }
How to define a class?
public class "class name" (no extension)
Constructor syntax
public class Book { // properties private String title = null; private String author = null; private boolean isCheckedout = false; // constructors public Book() { } public Book(String title, String author, boolean isCheckedout) { this.title = title; this.author = author; this.isCheckedout = isCheckedout; } } Two constructors: Book(), which is known as the default constructor Book(String title, String author, boolean isCheckedout) Default constructor - typically used to initialize properties to their "null" values, unless it is done when they are declared, then there is no need to have the first constructor. The 2nd constructor above, takes the passed parameters and assigns them to the class's properties (i.e., data members) using the keyword "this".
Basic definition of class for Book (library program)
public class Book { // properties private String title = null; private String author = null; private boolean isCheckedOut = false; // behavior public void checkOut () { isCheckedOut = true; } public void checkIn () { isCheckedOut = false; } }
Example of Event Listener and Event Handler
public class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println(e); } } // Listens for button action, if action occurs then will print the action.
first line of program, HelloWorld
public class HelloWorld
Syntax to define a class
public class SomeClassName { // class properties and behaviors (methods) go here } keyword "public" is an access modifier, keyword "class" identifies the construct (i.e., the item) as a class definition, class name may contain alpha numeric characters, underscore, and $ (last two are rarely used). By convention, class names always start with an upper case letter, using CamelCase if there are more than one word.
Enum: Instantiate Enum for days of the week
public enum Day{ Monday(0),Tuesday(1), Wednesday(2), Thursday(3),Friday(4),Saturday(5),Sunday(6); private int value; private Day(int v){value = v;} public int getValue(){return this.value;} } //values() returns array of all constants defined in enum // valueOf() returns Enum with name matching to String passed to valueOf // Day.name() returns string name of enum
Basic Enum class
public enum Level { HIGH, MEDIUM, LOW } //Assign it Level level = Level.HIGH;
Build a return method
public return
Constants declaration
public static final NAME = value;
How do you make a main method?
public static main(String[] args) { //Your program goes here! }
Class lock (synchronization)
public static synchronized void displayMessage(JumbledMessage jm) throws InterruptedException { for (int i = 0; i < jm.message.length(); i++) { System.out.print(jm.message.charAt(i)); Thread.currentThread().sleep(50); } System.out.println();}
main loop
public static void main (String[] args)
Standard Starting, to start code block?
public static void main(String[] args) { //code goes here }
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); } }
Scanner in = new Scanner(new File("input.txt");
reads input from a file (also declared in same line)
java SentinelDemo < numbers.txt
redirects input
==,!=,>,<,>=,<=
relational operators; equal, not equal, greater than, less than, greater than/equal to, less than/equal to
Inheritance gives your programs the ability to express _______________ between classes. 1. encapsulation 2. relationships 3. composition 4. dependencies
relationships
Set Interface
represents a collection of objects with no duplicates. By default, duplicates are identified by their equals(Object) method whose default behavior is defined in the root class Object. In other words, if equals(Object) is not overridden, object references will be used to determine if list entries are equal. If this behavior is not desired, equals(Object) needs to be overridden in the class for which objects are added to the set. A portion of the Set API is shown below. <<interface>> set +add(E) : boolean +addAll(Collection) : boolean +clear() : void +contains(Object) : boolean +containAll(Collection) : boolean +isEmpty() : boolean +remove(Object) : boolean +size() : int suppose the Library system has a business rule that prevents users from checking out more than one copy of a given book. During the checkout process, the user's books could be added to a Set collection where duplicate books are not added to the set. private Set booksCheckedOut = new HashSet(); public boolean checkout(Book book) { return booksCheckedOut.add(book); } The above method returns true if the book is not already in the set; otherwise, it returns false. If false is returned, the user would be notified that the duplicate book could not be checked out. Implementations of the Set interface include HashSet and TreeSet. The order of elements in a Set depends on the underlying implementation, and thus, will vary across implementations. If order is important, the interface SortedList should be used.
Queue Interface
represents an ordered collection based on some known order: e.g., first in first out (FIFO), last in first out (LIFO, a.k.a. a stack), priority. A subset of the Queue API is shown below (not including the methods inherited from interface Collection). <<interface>> Queue +element() : E +offer(E) : boolean +peek() : E +poll() : E +remove() : E order of the queue is determined by the implementing class. Classes that implement the Queue interface include LinkedList and PriorityQueue. As an example, suppose the Library system solicits user suggestions, and these suggestions need to be processed in a FIFO basis. private Queue suggestions = new LinkedList(); public void addSuggestion(Suggestion suggestion) { suggestions.add(suggestion); } The above method adds the new Suggestion to the Queue. Because the implementing class is a LinkedList, each suggestion is added to the end of the queue.
To use an ArrayList in your program, you must import: 1. the java.collections package 2. the java.awt package 3. Nothing; the class is automatically available, just like regular arrays. 4. the java.util package 5. the java.lang package
the java.util package
List Interface
represents an ordered sequence of objects. That is, elements are added to the list in a particular order, and the list maintains that order. suppose we have a List, booksCheckedIn, which contains all the books that are checked-in on a given day. Then, if we add books to the list as they are checked-in, the list will maintain the order in which they were checked-in. private List booksCheckedIn = new ArrayList(); public void checkin(Book book) { booksCheckedIn.add(book); } Implementations of the List interface include ArrayList, LinkedList, Stack, and Vector. List collections do not check for duplicate entries, so if an object is added multiple times, it will appear in the list multiple times (i.e., have multiple entries). Therefore, if it's important for a given object to appear only once in the collection, the Set interface should be used as explained below.
Declaring Exceptions
required that if a method throws an exception without catching it, the exception must be declared in the method signature to notify users. method that authenticates logins, throws an exception named LoginFailedException without catching it: public bool authenticate(Login login) throws LoginFailedException {...} Any exception that occurs in a method must either be handled (caught) by that method or be declared in its signature as "throws" (see above). method throws (and does not handle) multiple exception types, instead of listing all the exceptions in the method signature, the base exception class Exception can be listed: public bool authenticate(Login login) throws Exception {...} declaration covers all possible exception types, and thus prevents you from having to list the individual exceptions when multiple exceptions can be thrown.
Bounded generic types
restrict the actual type parameter allowed and can be specified by saying which class the allowed types extend. - effect = permits subtypes of the class. can have: - object of subtype B where object of its supertype A is expected.
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
Which of the following is NOT a modifier?
return
The return Statement
return expression;
return volume;
return statement that returns the result of a method and terminates the method call
/r
return; causes the cursor to go to the beginning of the current line, not the next line
str.charAt(pos)
returns the character (char) at position pos (int) in the given string
str.length()
returns the number of characters in the given string (int)
str.indexOf(text)
returns the position (int) of the first occurrence of string (text) in string str (output -1 if not found)
str.substring(start, end)
returns the string starting at position (start) and ending at position (end-1) in the given string
Syntax to define a method (behavior (function in C++))
returntype methodName(optional_list_of_arguments) { ...} Names of properties (variables) and methods should start with a lower case letter, using camelCase if multiple words.
If a class implements the Runnable interface, what methods must the class contain?
run()
This method is the engine of a threaded class.
run()
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
;
semicolon; marks the end of a complete programming statement
notify() (Thread Communication)
sends wake up call to a single blocked thread. Cannot specify which thread to wake.
notifyAll() (Thread Communication)
sends wake up call to all blocked threads - if called when thread does not have lock = Illegal MonitorStateExpectation
Objects
sent messages
.
separates package names / adds folders
Mutator methods typically begin with the word "____".
set
Package
set of classes with a shared scope, typically providing a single coherent 'service' e.g. FilmFinder package
Program
set of classes, one with a 'main' method (.java)
What is the method signature of public void setDate(int month, int day);?
setDate(int, int);
JTextArea method _, when called with an empty string, can be used to delete all the text in a JTextArea.
setText
Clock -hr: int -min: int -sec: int +Clock() +Clock(int, int, int) +setTime(int, int, int): void +getHours(): int +getMinutes(): int +getSeconds(): int +printTime(): void +incrementSeconds(): int +incrementMinutes(): int +incrementHours(): boolean +equals(Clock): boolean +makeCopy(Clock): void +getCopy(): Clock According to the UML class diagram above, which method is public and doesn't return anything? 1. getCopy() 2. setTime(int, int, int) 3. incrementHours() 4. equals(Clock)
setTime(int, int, int)
Naming standard for mutator method?
setXYZ();
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
//comment
short comments
Math.sin(x)
sine of x (x in radians)
programming vs natural languages
size, rigidity, literalness
Class Constructors
special methods that are called when a class is created. Must have the same name as the enclosing class, and are declared with no return value (the implied return type of the constructor is the enclosing class type). public Book() {...} public Book(int id) {...} public Book(int id, String title) {...} public Book(int id, String title, String author) {...} public Book(int id, String title, String author, int pages) {...} Constructors can be overloaded. Once you define at least one constructor (whether default or not), the implicit, hidden default constructor is not provided for you. used to initialize the data members of the newly created object either by assigning default values or by using the passed-in parameters. Constructors can also invoke other constructors either in the same class or in a base class. public Book(int id) { super(id); } Above uses "super" keyword to invoke a constructor in the base class LibraryItem. Constructors are invoked with the "new" keyword
Public Interface
specifies what you can do with its objects
In the type-safe version of the ArrayList class, you specify the type of each element by: 1. None of these; an ArrayList can hold any object type 2. specifying a generic type parameter when defining the ArrayList variable 3. using the special type-safe version of the subscript operator 4. passing a Class parameter as the first argument to the constructor 5. using the setType() method once the ArrayList is constructed
specifying a generic type parameter when defining the ArrayList variable
Math.sqrt(x)
square root of x
Calling a thread's _____ method causes its _____ method to be called
start() & run()
To run a thread what method must be callled?
start() method
Character.isDigit(ch)
statement (boolean), ch (char); allows you to check if ch is a digit or not
Character.isLetter(ch); Character.isUpperCase(ch); Character.isLowerCase(ch); Character.isWhiteSpace(ch);
statement (boolean), ch (char); allows you to check if ch is a letter/uppercase/lowercase/whitespace
while (condition) { statements }
statements = body of while loop; braces not needed for a single statement
Object references
stored in Object variables and denotes the memory location of an Object
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)
Given the method heading public void strange(int a, int b) and the declaration int[] alpha = new int[10]; int[] beta = new int[10];
strange(alpha[0], alpha[1]);
/** Computes the volume of a cube. @param sideLength the side length of the cube @return the volume */
structure for commenting before methods (javadoc)
throws FileNotFoundException
terminates main if FileNotFoundException occurs
for (initialization; condition; update) { statements }
terminating loop
Mocks
test objects that know how they are meant to be used.
Stubs
test objects whose methods return fixed values and support specific test cases only.
Fakes
test objects with working methods but have limited functionality.
Dummies
tests objects that are never used but exist only to satisfy syntactic requirements.
Compile-time or syntax errors (Error Type 1/3)
the compiler will find syntax errors and other basic problems
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.
Origin
the point (0,0) in a coordinate system
syntax
the rules for combining words into sentences
vocabulary
the set of all of the words and symbols in a given language
To determine the number of valid elements in an ArrayList, use:
the size() method
Dynamic binding
the subclass' behaviour will occur even though the client does not know it is using the subclass object.
A parameter is a local variable initialized to....
the value of the corresponding argument. (Known as Call-by-value)
Keyword: this
this - used to disambiguate the overloaded use of variable names; in particular, "this" can be used to reference a data member (defined in the class) when that name is identical to a passed parameter. assigns the input parameter, title, to the data member, title: private String title = ""; public void setTitle(String title) { this.title = title; } inside the method setTitle(String title), the passed parameter, title, hides the data member, title, defined in the class. To access to the title data member, the keyword "this" is used to indicate a data member of the object is being referenced (and not a local variable inside the method).
set input variables
thisEnter = myScanner.next.Int();
If some code in your method's body might throw an exception, add the ______ keyword after the closing parenthesis of the method followed by the name or names of the exception
thows
Exceptions
undesireable events outside the 'normal' behaviour of a program. - recoverable (not always) - handled in method where occur or propagated to calling program
Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long 1. toString() 2. None of them 3. getName(), setName(), name 4. name, getName(), setName(), getID() 5. getName(), setName(), studentID, getID() 6. studentID, name, getName(), setName(), getID()
toString()
Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Assume that pete is a Person object variable that refers to a Person object. Which method is used to print this output: pete is Person@addbf1 1. getClass() 2. getAddress() 3. getName(), getID() 4. getID() 5. getName() 6. None of them 7. toString()
toString()
Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Which of these fields or methods are inherited by the Person class? 1. toString() 2. getName(), setName(), studentID, getID() 3. studentID, name, getName(), setName(), getID() 4. name, getName(), setName(), getID() 5. getName(), setName(), name 6. None of them
toString()
Boolean
true or false
boolean
true or false
to "catch" a exception you must surround it with a ____ & _______
try & catch
Try catch exception block
try {... normal code} catch(exception-class object) {... exception-handling code}
Variable definition
typeName variableName = value;
double blah = (int) (blah + 3)
typecast; change variable type
Method Overriding
when a method in a base class is repeated (redefined) in a derived class signature of both methods must match identically override its behavior in the LibraryItem to output the item's id and title as shown below: public class LibraryItem { ... public String toString() { return "LibraryItem, id=" + id + ", title: " + title; } } can invoke toString() to get a meaningful description of the object. Also true if the object is a Book, Audio, or Periodical because they inherit LibraryItem. Object obj = new Book(1, "Catch-22", "Joseph Heller", 485); String s = obj.toString(); actual instance is a Book and Book "is a" LibraryItem which overrides toString(), the LibraryItem's toString() method is called. Example of polymorphic dynamic binding; dynamic because it's not known until runtime which toString() method is invoked; it depends on whether the method is overridden, and if so, where. Can override toString in each of the more specialized classes: Book, Audio, and Periodical: public class Book extends LibraryItem { public String toString() { return super.toString() + ", Author, =" + author; } } super.toString() in the above return statement; its purpose is to invoke the toString() method in the base class LibraryItem. So the Book's overridden toString() method calls the LibraryItem's toString() method and then appends to it the author information that's contained in the Book. This time, since Book has overridden toString(), which overrides LibraryItem.toString(), which overrides Object.toString(), it's Book.toString() that gets called, and not the ones declared in Object or LibraryItem: Object obj = new Book(1, "Catch-22", "Joseph Heller"); String s = obj.toString(); another example of method overriding, consider the method equals(Object obj) defined by the Object class. to compare the state of two objects, overriding equals(Object obj) as shown below for LibraryItem: public class LibraryItem { public boolean equals(Object obj) { if (this == obj) return true; if ( ! (obj instanceof LibraryItem)) return false; LibraryItem item = (LibraryItem)obj; if ( this.id != item.id ) return false; if ( ! this.title.equals(item.title)) return false; return true; } } @override annotation - applied to methods that are intended to override behavior defined in a base class. annotation forces the compiler to check that the annotated method truly overrides a base class method. package domain; public class LibraryItem { @Override public String equals(Object obj) { ... } @Override public String toString() { ... } }
variable declaration statement
when a program declares the type of a variable
syntax errors
when a syntax rule is violated
Importing packages
when classes are in defined in different packages. In order for ClassA, in packageA, to have visibility to ClassB, in packageB, one of three things must happen; either: - the fully qualified name of ClassB must be used, - fully qualified name of ClassB be must be imported with an import statement, - entire contents of packageB must be imported with an import statement. first technique is to use the FQN of the class. The FQN of ClassB is packageb.ClassB. to declare: package packagea; public class ClassA { packageb.ClassB b = new packageb.ClassB(); } better technique is to use an "import" statement: package packagea; import packageb.ClassB; public class A { ClassB b = new ClassB(); } import statements must appear after the package statement, and before the data type (class, interface) definition more efficient technique is to import all the data types from a given package using the * notation: import packageb.*; if multiple packages have classes with the same name, use long way (FQN) of importing package: package1.ClassXYZ xyz = new package1.ClassXYZ()
logic errors
when the computer is unable to express an answer accruately
When are the &, |, and ^ operators also bitwise operators?
when they're applied to integral operands
The while Statement
while (condition) statement;
while
while (true) { }
keywords
words in java that cannot be used as user-defined symbols
PrintWriter out = new PrintWriter("output.txt");
writes output to a file "output.txt"
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is NOT visible in method two?
x (variable in block three)
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int z = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is NOT visible in method two? 1. x (variable in main block) 2. w (before method two) 3. rate (before main) 4. one (method name)
x (variable in main block)
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;
Math.pow(x,y)
x^y (x>0, or x=0 and y>0, or x<0 and y is an integer)
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is NOT visible in block three? 1. t (before main) 2. z (before main) 3. local variables of method two 4. main
z (before main)
Block statement
{ statement; statement; }
What does a contain after the following loop? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; for (int i = pos; i < size - 1; i++) a[i + 1] = a[i]; size--;
{1, 1, 1, 0, 0, 0}
What does a contain after the following loop? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; for (int i = pos; i < size - 1; i++) a[i] = a[i + 1]; size--;
{3, 7, 7, 0, 0, 0}