JAVA FINAL 2

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Benefits of Refactoring

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

Java bytecode

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

Is delete,next,main,exit or null keyword in java?

No.

Does Java have multiple inheritance?*

No. Instead deal with interfaces.

Formal parameters of primitive data types provide ____ between actual parameters and formal parameters.

a one-way link

What value will z have if we execute the following assignment statement? int z = 50 / 10.00;

a run-time error arises because z is an int and 50 / 10.00 is not

Method body

area within the brackets of a method

The Swing package

is complementary to the AWT

CH13: The ListSelectionListener interface is in this package.

javax.swing.event

count-controlled loop

loop body is executed a fixed number of times

Which of the following assignment statements is illegal? (Choose all that apply.) 1) float f = -34; 2) int t = 23; 3) short s = 10; 4) int t = (int)false; 5) int t = 4.5;

int t = (int)false; int t = 4.5;

object

an instance of a class

&&

and operator, control statement executed when all the statements are true

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

What is a base class?

the parent of a child class

computer science

the study of algorithms including their formal and mathematical properties, hardware realizations, linguistic realizations, and applications

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

throw

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

Consider the following statement: System.out.println("1 big bad wolf\t8 the 3 little pigs\n4 dinner\r2night"); This statement will output ________ lines of text

2

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

JFileChooser

Can you use continue in a switch?

No

Can you use long in a switch statement?

No

Can you make a constructor final?

No, constructor can't be final.

Can local variables use the static modifier?

No, local variables can only use the final modifier.

Can you use this() and super() both in a constructor?

No. Because super() or this() must be the first statement.

When implementing an interface's method that throws an exception what must the implemented exception throw?

The same exception or a subclass or no throw clause at all.

What must be the return type of a method overriding a subclass of another method from a superclass.

The same or a subclass of it. if the method was returning object the subclass method could return String.

update statement

The way the index of a loop changes value.

Can we execute a program without main() method?

Yes, one of the way is static block

setBackground

1. Use ___ to specify the content pane's background color.

Assignment

=

bounds property

The property that specifies both the location and size of a component.

setBounds

The location and size of a JLabel can be specified with _____.

A block is enclosed inside ________.

braces

single responsibility

class dose well define job

64 bit real number

double

A class' constructor usually defines

how an object is initialized

32 bit integer

int

procedure

performs an action but doesn't return anything;

Variable Declaration

stating the name of the variable coupled with its data type

Which of the following is a valid identifier? (Choose all that apply.) 1) $343 2) class 3) 9X 4) 8+9 5) radius

$343 radius

Bitwise And operator

&

An int variable can hold ________. (Choose all that apply.) 1) 'x' 2) 120 3) 120.0 4) "x" 5) "120"

'x' 120

Multiplication operator

*

declaring

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

Can we overload main() method?

Yes, You can have many main() methods in a class by overloading the main method.

GUI

graphical user interface

What are Predefined variables or implicit objects?

- simplified code in JSP expressions . They are request, response, out, session, application, config, pageContext, and page.

subclass

- inherits from parent class

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

...

Which memory capacity is the largest?

12,000,000 megabytes

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

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

Print

10. The debugger command ________ allows you to "peek into the computer" and look at the value of a variable.

Append

A method that adds text to a JTextArea component.

Are arrays used only for primitives?

No

byte

8 bits

Java Virtual Machine (JVM)

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

statement

A unit of code that performs an action and ends with a semicolon.

Define the keyword "abstract"

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

Public

Accessible by all.

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.

equality operators

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

What happens if their is no main method?

Runtime Error.

git init

Initialise an empty repository

What can't a method not do when it is final?

It cannot be overloaded.

________is Architecture-Neutral.

Java

What does String Buffer extend?

Object

break mode

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

exception thrower

method that may directly or indirectly throw an exception

variable

points to a object in the heap

protected

protected members can only be accessed by own class, class's sub class or classes from same package

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

While

What is object cloning?

The object cloning is used to create the exact copy of an object.

Functional decomposition is

The process of breaking a problem down into smaller pieces.

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.

if statement

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

How do you find the length of a String?

Use the .length() method.

relational operator

Used in boolean expressions that evaluate to true or false. Combinations of <. > or =

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

printStackTrace

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

private

event handler

processes the events and determines what to do

statements

A line of java code.

GUI

Graphical User Interface

class name

The identifier used as the name of a class.

Consider the following enumeration enum Speed { FAST, MEDIUM, SLOW };

The name of the Speed enumeration whose ordinal value is zero is FAST

Every statement in Java ends with ________.

a semicolon (;)

JTextField.LEFT

Used with setHorizontalAlignment to left align the text in a JTextField.

For loop

for( insert argument here) { insert code here }

an instance is another way of saying ____?

object

CH13: You can use this method to make a text field read-only.

setEditable

protocol stack

the Internet protocol hierarchy that has 5 layers (physical, data link, network, transport, application); also referred to as TCP/IP

Subtraction operator

-

The Random class has a method nextFloat( ) which returns a random float value between

0 and 1

What does element indexing start at?

0.

variable

An identifier that represents a location in memory.

-25 % 5 is ________.

0

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

Boolean equals

==

String.equals

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

String literal

A sequence of characters within double quotes.

What is a stream (in the context of the new Java 8 Collection API)?

A sequence of elements supporting sequential and parallel aggregate operations.

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.

What is the function of the dot operator?

Both, It allows one to access the data within an object when given a reference to the object and It allows one to invoke a method within an object when given a reference to the object are correct

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.

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

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

git commit

Commits staged files to Repo.

What does the method .equals do from the String class?

Compares the equality of two strings.

What does the method .equals do from the class object?

Compares two object area memories.

If two classes are not in the same class tree and an instanceof operator compares them what will be the output?

Compilation Error

What does Javac do?

Compiles the program.

What is the difference between constructor and method?

Constructor will be automatically invoked when an object is created whereas method has to be called explicitly. Constructor doesn't have return types and its name must be the same as the Class' When constructor is invoked, it may invoke the constructors of the super classes.(call stack)

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

stop

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

format

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

Java is a strongly typed language. What is meant by "strongly typed"?

Every variable has a single type associated with it throughout its existence in the program, and the variable can only store values of that type

What does the substring method written like this return - stringName.subString(1,5)?

Everything in that string starting from index one and up to 5-1 or 4.

What is final method?

Final methods can't be overriden.

________ is the physical aspect of the computer that can be seen.

Hardware

Types of Maps

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

How does the garbage collector know when to return memory to the heap?

If there is a pointer to the memory

Double

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

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

ImageIcon

Under what conditions can a local class access variables in the enclosing scope?

In addition, a local class has access to local variables. However, a local class can only access local variables that are declared final. When a local class accesses a local variable or parameter of the enclosing block, it captures that variable or parameter.

An action

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

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

variable declaration

It associates a type and an identifier (or name) with the variable

What is super in java?

It is a keyword that refers to the immediate parent class object.

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

JOptionPane.ERROR_MESSAGE

The ________ method displays a message dialog box.

JOptionPane.showMessageDialog(null, "Welcome to Java!", "Example 1.2 Output", JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(null, "Welcome to Java!");

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

JRadioButtonMenuItem

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

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.

JSE API

Java Standard Edition Application Programming Interface Libraries

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.

Define the keyword "void"

Method that does not return.

Define the keyword "return"

Method that returns.

What are the two things classes have?

Methods and Variables.

Event Handlers

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

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.

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)

Danger of using GIT

Only one repository.

When can super() be called.

Only the FIRST line of the constructor.

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.

JLabel

The component that displays text or an image that the user cannot modify.

What is the purpose of the Java garbage collection?

The garbage collection is used to discard any not used data.

Say you write a program that makes use of the Random class, but you fail to include an import statement for java.util.Random (or java.util.*). What will happen when you attempt to compile and run your program.

The program won't compile-you'll receive a syntax error about the missing class.

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.

inheritance (in Java)

The relationship between a more general superclass and a more specialized subclass

arithmetic operators

These operators are used for performing calculations.

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.

% (remainder operator)

This operator yields the remainder after division.

postcondition assertion

checks a condition that must be true after method execution

abstact base class

class that can not be initialized but has class inhert from it

variable assignment

sets where the varaible is pointing

CH11: The following is an explicit call to the superclass's default constructor.

super();

CH12: These are exceptions that inherit from the Error class or the RuntimeException class.

unchected exceptions

final keyword

used to denote a variable whose value is contant - can also be used in method declaration to assert that the method cannot be overridden by subclasses

What is a mutator?

ways to set variables in class

Compiler

2. The __________ converts a .java file to a .class file.

What does the NEW keyword do?

Allocates new space in memory.

Boolean

true or false

short

16 bit, useful if memory an issue

interface

a collection of abstract methods

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

this.field

accesses an instance variable in the current class

ACK

acknowledgement message that contains the sequence number of a correctly received packet; this lets the sender know the packet was received

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

action event

ArrayList

dynamic data structure items can be added or removed

IDE

integrated development environment; a programming environment that includes an editor, compiler, and debugger

64 bit integer

long

Basic Enum class

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

Main Method

public static void main(String args[])

What is casting?

- Casting is used to convert the value of one type to another.

GIT

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

separates package names / adds folders

.

.java

1. A source code file has the ____ extension.

Methods that retrieve values are called ____ methods. 1. accessor 2. class 3. mutator 4. static

1. accessor

How many constructors can a class have? 1. 2 2. Any number 3. 1 4. 0

2. Any number

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.

Comment

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

What file is created after a program is created?

A .class file.

input JTextField

A JTextField used to get user input.

What is a pipeline?

A Pipeline is built up from stages which can pass data on to subsequent stages

comment

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

what can be put in main to access a and staticAccess? public class A{ static int a = 13; static void staticAccess(){} public static void main(String args[]){ //Line 1 // Line 2 } }

A.a and A.staticAccess You can use the class name to call a static member.

Note that the Unicode for character A is 65. The expression "A" + 1 evaluates to ________.

A1

Java is similar in syntax to what other high level language?

C++

________ is the brain of a computer.

CPU

Integer.parseInt

Returns the integer equivalent of a String.

binary

base-two numeral system; usually using 1s and 0s

What is this()?

calls a constructor in the same class?

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

getSelectedIndex

Write an if then statement where i=10

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

Visibility modifiers include

public, private, protected

Which of the following is NOT a modifier?

return

16 bit integer

short

CH13: This is text that appears in a small box when the user holds the mouse cursor over a component.

tool tip

What does it mean to cast a variable?

treat an object as if it has a different class.

protected

variables/methods available to any class that extends the original

What is x after the following statements? int x = 1; int y = 2; x *= y + 1;

x is 3

What is the printout of the following code: double x = 5.5; int y = (int)x; System.out.println("x is " + x + " and y is " + y);

x is 5.5 and y is 5

How can I delete a cookie with JSP?

- Say that I have a cookie called "foo, " that I set a while ago & I want it to go away. I simply: <% Cookie killCookie = new Cookie("foo", null); KillCookie. setPath("/"); killCookie. setMaxAge(0); response. addCookie(killCookie); %>

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

...

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

...

Division operator

/

Suppose x is 1. What is x after x -= 1?

0

double-selection statement

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

event source

GUI object where the event occurs

Hashcode (GIT)

Uniquely identify each commit.

Is constructor inherited?

No, constructor is not inherited.

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.

insertion sort

sort in which we assumed preceding records have been sorted, and the number is simply inserted into its proper place

SuperClass

the parent or supertype of a class

Can we override the overloaded method?

Yes.

compiler

a program that translates code in a high-level language to machine instructions (such as bytecode for java)

class

a programmer-defined data type; the user can create this data type and make objects of this type

Polymorphism

ability of an object to take many forms

Private Keyword

an access modifier that only allows access to that member from the class in which it resides

Map

an interface that maps keys to values - a map object can store the key value pairs

If two variables contain aliases of the same object then

answers the object may be modified using either alias and the object will become an "orphan" if both variables are set to null are correct

The instruction: System.out.println("Hello World"); might best be commented as

// used to demonstrate an output message

KeyPressed

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

One byte has ________ bits.

8

byte

8 bit, useful if memory an issue

setHorizontalAlignment

8. Use ____ to align the text displayed inside a Jlabel.

True and False

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

empty string ("")

A string that does not contain any characters.

MAC

medium access control: data link protocol sub-layer that determine how to arbitrate ownership of a shared communication line when multiple nodes want to send messages at the same time

The word println is a(n)

method

Dangers of threads

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

private

private members can only be accessed by other members of their own class

java.lang.Thread

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

What must the access modifier of a method that is implementing an interface be?

public - since all interface methods are automatically public methods that override it have to have the same or higher visibility rank.

Methods in interfaces are automatically what?

public and abstract.

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

setText

What is specialization?

as opposed to generalization - specialization refers to the hierarchy of a superclass and subclass in which the superclass is always more inclusive than the subclass - the farther down the hierarchical chain, the more

What is garbage collection?

attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program.

Which of the following would be a good variable name for the current value of a stock? 1) curstoval 2) theCurrentValueOfThisStockIs 3) currentStockVal 4) csv 5) current

currentStockVal

operation

deployment and maintenance

object-oriented programming

designing a program by discovering objects, their properties, and their relationships

Do loop

do{ code here } while ( argument here);

Write an endless do loop where i=10

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

Boolean not

!

What is the difference between & and &&?

& evaluates both sides. If the first one is false the second statement will be evaluated. && works differently. When the first expression is false it will not execute the second one. This is also known a short cut.

What is a Java Bean?

- A Java Bean is a software component that has been designed to be reusable in a variety of different environments.

What is the life cycle of a servlet?

- Each Servlet has the same life cycle: a) A server loads and initializes the servlet by init () method. b) The servlet handles zero or more client's requests through service() method. c) The server removes the servlet through destroy() method.

What is a cloneable interface and how many methods does it contain?

- It is not having any method because it is a TAGGED or MARKER interface.

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)

Pass by value

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

What is the difference between process and thread?

- Process is a program in execution whereas thread is a separate path of execution in a program.

What is Servlet chaining?

- Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet's output is piped to the next servlet's input. This process continues until the last servlet is reached. Its output is then sent back to the client.

Local Repository

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

What is the difference between Reader/Writer and InputStream/Output Stream?

- The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented.

Is it possible to communicate from an applet to servlet and how many ways and how?

- Yes, there are three ways to communicate from an applet to servlet and they are: a) HTTP Communication(Text-based and object-based) b) Socket Communication c) RMI Communication

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.

base class

- class that other classes inherit from

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

Specialization

- creating new subclass from existing class for more specialized version of parent

data hiding

- hides internal object details

super classs

- parrent class

final

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

data access class

...

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

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

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

What is the result of 45 / 4?

11

What is output with the statement System.out.println(""+x+y); if x and y are int values where x=10 and y=5?

15

/

2. The ________ operator performs division.

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)

What is the value of (double)5/2?

2.5

What is the printout of System.out.println('z' - 'a')?

25

setTitle

3. Use ____ to set the text that appears on a JFrame's title bar.

A(n) ____ variable is known only within the boundaries of the method. 1. instance 2. double 3. local 4. method

3. local

int

32 bit

If a, b, and c are int variables with a = 5, b = 7, c = 12, then the statement int z = (a * b - c) / a; will result in z equal to

4

Compiler

4. Syntax errors are found by the ____.

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

Greater than

>

Greater than or equal to

>=

single precision

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

end-of-line comment

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

________ translates high-level language program into machine language program.

A compiler

JButton component

A component that, when clicked, commands the application to perform an action.

print

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

What is this automatically? 45e7

A double

Header

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

control

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

static variable

A variable defined in a class that has only one value for the whole class, and which can be accessed and changed by any method of that class.

Counter

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

Constant

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

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

Explicit cast

Action of a programmer in order to convert a variable to a more limited type.

When an object, such as a String, is passed as an argument, it is

Actually a reference to the object that is passed

What is difference between aggregation and composition?

Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator (aggregation) but bike has an engine (compostion).

ASCII

American Standard Code for Information Interchange, which encodes 128 characters from 8-bits (binary)

JPS

An HTML page in which Java is invoked.

What is an accessor?

An accessor is a method that returns the value of a property of a dto - referred to as a 'getter'

By default what is this considered - 12?

An int.

Loop

Another general name for a repetition statement.

What happens if you attempt to use a variable before it has been initialized?

Answers A syntax error may be generated by the compiler and A runtime error may occur during execution are correct

JTextArea method _ adds text to a JTextArea.

Append

API

Application Programming Interface; a code library for building programs

Consider a Rational class designed to represent rational numbers as a pair of int's, along with methods reduce (to reduce the rational to simplest form), gcd (to find the greatest common divisor of two int's), as well as methods for addition, subtraction, multiplication, and division. Why should the reduce and gcd methods be declared to be private.

Because they will only be called from methods inside of Rational

UML Diagrams - list the behavior diagrams

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

Decimal, Text

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

Refactoring

Cleans code whilst preserving behaviour.

declaration

Code that specifies the name and type of a variable.

compound boolean expressions

Combination of two conditionals that evaluate to true or false.

final or user-defined constant

Constant, cannot be changed.

Final

Constants are declared with keyword ____.

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

Counter

how to store an object that you construct by storing it in a variable

Date birthday=new Date

Counter-controlled repetition is also called _.

Definite repetition

What happens when you divide 0 by 0?

Exception

How can exceptions be handled in Java?

Exceptions can either be thrown or handled using a try catch block.

comment (//)

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

HTTP

Hypertext Transfer Protocol; the protocol that defines communication between web browsers and web servers

CH12: FileNotFoundException inherits from ________.

IOException

Classpath

Indicates where you can find another self-written classes

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

Infinite

What happens when you divide a double or a float by 0?

Infinity

What is Inheritance?

Inheritance is a mechanism in which one object acquires all the properties and behaviour of another object of another class. It represents IS-A relationship. It is used for Code Resusability and Method Overriding.

bytecode

Instructions for the Java virtual machine

If a byte is multiplied by a short and set to a value what must that value be?

Int

The ________ method parses a string s to an int value.

Integer.parseInt(s);

is true regarding the mod operator, %

It can be performed on any numeric values, and the result always is numeric

________ is a software that interprets Java bytecode.

Java virtual machine

Which of the following is a constant, according to Java naming conventions? (Choose all that apply.) 1) MAX_VALUE 2) Test 3) read 4) ReadInt 5) COUNT

MAX_VALUE COUNT

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

Merge

Can You use float in a switch statement?

No

Can a local variable be static?

No

Is it legal to use .super in static methods?

No - .this and .super cannot be used or a compilation error will happen.

What is covariant return type?

Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type.

Define "Null"

Null means nothing. It's a place holder.

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)

________ is a program that runs on a computer to manage and control a computer's activities.

Operating system

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

Overloading

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

Overriding

Head pointer (GIT)

Points to the current branch.

System.out.println("Hello")

Prints Hello to console on a new line.

Inheritance*

Process where one object acquires the properties of another.

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.

Final

Retains the same value throughout the program

execute (SQL command)

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

operator precedence

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

setEditable

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

Design patterns

Smart solutions for complex problems, which are given to us in the form of abstract descriptions.

debugger

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

isSelected

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

BorderLayout

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

jdb

Starts the Java debugger when typed at the Command Prompt.

UML Diagrams - list the structure diagrams

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

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

git add

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

@Test(timeout = T)

Test fails if runs longer than T milliseconds.

Suppose you define a Java class as follows: public class Test{ } In order to compile this program, the source code should be stored in a file named

Test.java

name

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

initialization value

The beginning value of a variable.

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.

short-cut evalulation

The process in an "if statment" that allows it to skip the rest of the stated program, should it come to the conclusion prior to the end of the program.

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

setText

The text on a JLabel is specified with _____.

Type casting

The type of a variable into another type.

What does the word before the instanceof operator have to be and what does the word after?

The word before has to be an object. The word after has to be a superclass.

CH12: All exception classes inherit from this class.

Throwable

Define the keyword "catch"

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

________ is an operating system.

Windows XP

How is an instance block wrote?

With two brackets outside of the main method.

What are Wrapper classes?

Wrapper classes are objects of primitives. Every primitive has a wrapper class.

Declares arrays

[]

Which character below is not allowed in an identifier? 1) $ 2) _ 3) 0 (zero) 4) q 5) ^

^

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

a Dimension object

What is a mutator?

a mutator is a method that changes the value of a field in a class - often called a 'setter'

A containment hierarchy is

a nested collection of relationships among containers

Mistyping "println" as "printn" will result in

a syntax error

What are the objects needed in order to create a Java GUI (graphical user interface)? 1) components 2) events 3) listeners 4) all of these 5) only classes from AWT and/or Swing are needed

all of these

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

machine language

binary instructions that are decoded and executed by the control unit

true or false

boolean

Suppose x is a char variable with a value 'b'. What is the printout of the statement System.out.println(++x)?

c

Consider having three String variables a, b, and c. The statement c = a + b; also can be achieved by saying

c = a.concat(b);

Layout managers are associated with

containers

Depend (ANT)

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

final

entity can not be changed

To prevent subclasses from overriding an inherited method, the superclass can mark the method as:

final

32 bit real number

float

A classification hierarchy represents an organization based on _____________ and _____________.

generalization and specialization

A ____________ relationship exists between two classes when one class contains fields that are instances of the other class.

has-A

Memory Address Register (MAR)

holds the address of the cell to be fetched or stored

What is the standard convention for un-named variables?

i

this()

invokes the constructor.

What is super()?

it calls the superclass constructor.

List

list is an interface that arrayList and other list inherit from

exception handling

mechanism used to improve a program's robustness

object reference

memory location of an object

You are ____ required to write a constructor method for a class.

never

event listener

object that includes a method that gets executed in response to generated events

The relationship between a class and an object is best described as

objects are instances of classes

event

occurs when the user interacts with a GUI object

Inheritance

organization of relevant classes into an hierarchy of parent and child classes; inherit some common base of data members and method from the parent class; maintainability, readability, extendability

The main method for a Java program is defined by

public static main(String[ ] args)

design

requirements specification turned into a detailed design of the program; result is a set of classes that fulfill the requirements

unchecked exceptions

runtime exceptions; unchecked at compile time and detected only at runtime

notify() (Thread Communication)

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

Mutator methods typically begin with the word "____".

set

cohesive

single responsibility class dose well define job

What are the two categories of nested classes?

static and none static

To add number to sum, you write (Note: Java is case-sensitive) (Choose all that apply.) 1) number += sum; 2) number = sum + number; 3) sum = Number + sum; 4) sum += number; 5) sum = sum + number;

sum += number; sum = sum + number;

Autoboxing is

the automatic conversion of a wrapper object to/from its corresponding primitive type

encapsulation

the hiding of implementation details and providing methods for data access

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

thrown

Every letter in a Java keyword is in lowercase.

true

address

unique identifier for a cell, this is how memory is divided

Integer

unsigned int, 0 -> 2^31 -1

override

when a child class has the same method name as the parent class, the child's method body will be implemented

Bitwise Or operator

|

25 % 1 is ________.

0

Consider the double value likelihood = 0.013885. What would be output if DecimalFormat dformatter = DecimalFormat("0.00##"); and you execute System.out.println(df.format(likelihood)); ?

0.0139

Binary numbers are composed entirely of

0s and 1s

Mismanaged threads result in

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

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

Valid Identifier

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

applet

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

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.

Boolean not equal to

!=

used to surround perimeters

()

How many ways can an argument be passed to a subroutine and explain them?

- An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.

What is an event and what are the models available for event handling?

- An event is an event object that describes a state of change in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two types of models for handling events and they are: a) event-inheritance model and b) event-delegation model

What is the use of bin and lib in JDK?

- Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.

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

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.

What is an Object and how do you allocate memory to it?

- Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.

How many ways can we track client and what are they?

- The servlet API provides two ways to track client state and they are: a) Using Session tracking and b) Using Cookies.

What are the types of JDBC Driver Models and explain them?

- There are two types of JDBC Driver Models and they are: a) Two tier model and b) Three tier model. Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is required to communicate with the particular database management system that is being accessed. SQL statements are sent to the database and the results are given to user. This model is referred to as client/server configuration where user is the client and the machine that has the database is called as the server. Three tier model: A middle tier is introduced in this model. The functions of this model are: a) Collection of SQL statements from the client and handing it over to the database, b) Receiving results from database to the client and c) Maintaining control over accessing and updating of the above.

What are the different servers available for developing and deploying Servlets?

- a) Java Web Server b) JRun g) Apache Server h) Netscape Information Server i) Web Logic

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

a class that extends a class

- inherits methods another class

Predecrement

--counter

Redundant

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

Suppose i is an int type variable. Which of the following statements display the character whose Unicode is stored in variable i? 1) System.out.println(i); 2) System.out.println((char)i); 3) System.out.println((int)i); 4) System.out.println(i + " ");

3) System.out.println((char)i);

Which of the following assignment statements is incorrect? (Choose all that apply.) 1) i = j = k = 1; 2) i = 1; j = 1; k = 1; 3) i = 1 = j = 1 = k = 1; 4) i == j == k == 1;

3) i = 1 = j = 1 = k = 1; 4) i == j == k == 1;

Define the keyword "public"

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

If null is on the left of the instanceof operator what will the answer always be?

False

2

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

format

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

Can a class be private?

No

Will System.out.println((char)4) display 4?

No

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

Task (ANT)

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

Nesting

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

Volatility is a property of

RAM

Random Access Memory

RAM; 3 characteristics: 1 - memory divided into cells and each cell has an address. 2 - All accesses to memory are at a specific address; must get complete cell. 3 - Time it takes to fetch/store a cell is the same for all cells.

Batch processing (JDBC)

Reduce overhead by executing a large number at once.

What does a for loop with two semicolons do(for(;;))?

Runs infinitly

What happens when their is no main?

Runtime Error

What is scope?

Scope refers to the lifetime and accessibility of a variable. How large the scope is depends on where a variable is declared. For example, if a variable is declared at the top of a class then it will accessible to all of the class methods. If it's declared in a method then it can only be used in that method.

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.

Von Neumann architecture

Structure and organization of virtually all modern computers are based off this design. Consists of 3 major characteristics. 1 - Four major subsystems called memory, input/output, arithmetic/logic unit, and control unit. 2 - stored program concept. 3 - sequential execution of instructions

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

What is the main difference between Java platform and other platforms?

The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms.It has two components: Runtime Environment, API(Application Programming Interface)

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.

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.

assignment operator

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

JTextField.CENTER

Used with setHorizontalAlignment to center align the text in a JTextField.

Is this valid code? boolean b = false; while(b){ System.out.println("Hey"); }

Yes

Class

a class is a template in which state and behavior are defined for the instances of that class (objects)

while loop vs do while

a do while runs through at least once while a while loop may never run

A URL (Universal Resource Locator) specifies the address of

a document or other type of file on the Internet

An API is

an Application Programming Interface

What is the heap?

an area of memory allocated for objects by the JVM

Why do computers use zeros and ones?

because digital devices have two stable states and it is natural to use one state for 0 and the other for 1.

What is casting a variable?

casting is to override the compiler by declaring your variable as a certain (Type) - this can only be used to make an object higher in a class hierarchy a more specific subclass (i.e. (Integer)Number or (ArrayList)Collection)

Transaction processing (JDBC)

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

Encapsulation

effective information hiding -programmers do not have to concern themselves with details of program components

Enum

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

To declare a constant MAX_LENGTH inside a method with value 99.98, you write

final double MAX_LENGTH = 99.98;

According to Java naming convention, which of the following names can be variables? (Choose all that apply.) 1) FindArea 2) findArea 3) totalLength 4) TOTAL_LENGTH 5) class

findArea totalLength

zero-indexing

first element begins at zero as opposed to one

flops

floating-point operations per second, this is used to see how many arithmetic operations a computer can do in a second (testing speed)

The main difference between a frame and a panel is

frames can have a title bar; panels cannot

Hamcrest

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

memory

functional unit of a computer that stores and retrieves the instructions and data being executed

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

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

getMessage

switch statement

implements selection control flow

How is the import keyword used?

import keyword is used to import from other files in order to use outside classes.

object

instance of exactly one class, and belongs to that class

Which library package would you import to use the class Random?

java.util

How do you run a program using commands.

javac ClassName.java java ClassName

LAN

local area network; network that is located in a geographically contiguous area such as a room; It is composed of personal computers and servers all connected with coaxial or fiber optic cables. Characteristics: bus, star, ring topology. Message broadcast on shared channel and all nodes receive.

A variable whose scope is restricted to the method where it was declared is known as a(n)

local variable

Which of these data types requires the most amount of memory? 1) long 2) int 3) short 4) byte

long

When executing a program, the processor reads each program instruction from

main memory

run()

main method for an individual thread

encapsulate

makes class variable private and give access with public methods

control statement

manipulate the sequence/order of execution of program statements; selection and repetition

ASCII

maps characters to a number; human and machine readable

The speed of the CPU is measured in ________.

megahertz gigahertz

It is important to dissect a problem into manageable pieces before trying to solve the problem because

most problems are too complex to be solved as a single, large activity

CH13: This is the JList component's default selection mode.

multiple interval selection mode

Why is it a good idea to split your application into layers?

n tier design allows for further separation of concerns among parts/layers of our appplication - this provides the ability to reuse parts of the application in other programs by having loosely coupled classes/layers

Method signature

name and parameters

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.

The main method header is written as:

public static void main(String[ ] args)

overriding a method

redefining a method in a subclass

instantiation

when instantiating a class, constructing an object of that class

@Test(expected = X.class)

Test is expected to throw exception X.

Java Runtime Environment (JRE)

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

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.

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

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

repetition statement

a loop; control a block of code to be executed for a fixed number of times or until a certain condition is met

parameter

a reference or value that is passed to a method or subrouting

Java is an example of

both high-level language and fourth generation language

You specify the shape of an oval in a Java applet by defining the oval's

bounding box

ethernet

broadband technology, originally designed to operate at 10 Mbps using coaxial cable; uses the bus topology for LAN

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

bubble sort

check exception

exception that compiler sees and need to be caught

checked exception

exception that is check at compile time

runtime exception

exception the happen during the running of the program

exception propagator

exception thrower that does NOT include a matching catch block; passes on the exception to another method

exception catcher

exception thrower that includes a matching catch block for the thrown exception

unchecked exception

exceptions that are not caught by the compiler subclass of runtime

analysis

feasibility study; result is a requirements specification

control unit

fetches from memory the next instruction to be executed, decodes it, and executes it by issuing appropriate command to ALU, memory, or I/O

What is the only modifier that a local variable can be?

final

If a method does not have a return statement, then

it must be a void method

||

or operator, control statement is executed when at least one condition is true

What does the term overloading mean?

overloading a method is to declare two or more methods of the same name with different parameters

CH11: Abstract methods must be ________.

overridden

What does overriding mean?

overriding is to create a unique implementation of a method inherited from a supertype or interface

Which modifier is used to specify that a method cannot be used outside a class?

private

Program

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

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

boolean

type with possible values of true of false

Disadvantages of Centralised Servers

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

Checkout

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

What will be the result of the following assignment statement? Assume b = 5 and c = 10. int a = b * (-c + 2) / 2;

-20

-24 % -5 is ________.

-4

-24 % 5 is ________.

-4

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 last index of the string TEXT?

3. The first letter starts with index 0.

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.

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)

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

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

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

argument

Any values the method needs to carry out its task, and are supplied in the method call.

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

Editable

Jar

For the amount of code that contains thousands of classes is in keeping proof, they store them in compressed archives.

What happens when you divide 0.0 by 0.0 or 0?

NaN(Not a Number)

static

Not belonging to a class or individual objects.

nested or embedded

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

editable property

The property that specifies the appearance and behavior of a JTextField (whether the user can enter text.)

What is overloading?

When a method has the same name but different signature. EX: void m1() int m1(int a) void m1(int a, int b)

static method

a method with no implicit parameter (a method that is not invoked on an object)

protocol

a mutually agreed upon set of rules, conventions, and agreements for the efficient and orderly exchange of information

what is a try/catch?

a try/catch block is used to catch exceptions - if the code in the try block throws an exception the rest of the try block is skipped and the catch block is run

A JPanel can be added to a JFrame to form a GUI. In order to place other GUI components such as JLabels and Buttons into the JFrame, which of the following messages is passed to the JPanel? 1) insert 2) include 3) get 4) getContentPane 5) add

add

white space

any sequence of only space, tab, and newline characters

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

appear on the very first statement

Java ________ can run from a Web browser.

applets

main class

application class; contains the main method, start of the program

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]

control flow invariant

control must flow must flow invariably to a case

Which phase of the fetch-decode-execute cycle might use a circuit in the arithmetic-logic unit?

execute

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.

switch statement

take a variable selects appropriate case for value

Variable Assignment

to assign a value (using the assignment operator - " = ") to a variable name

What is RMI and steps involved in developing an RMI object?

- Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the interfaces and their implementations with the java compiler d) Compile the server implementation with RMI compiler e) Run the RMI registry f) Run the application

Software Patterns

- Reusable solution to common problem. - Description/Template

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.

What is synchronization?

- Synchronization is the mechanism that ensures that only one thread is accessing the resources at a time.

Who is loading the init() method of servlet?

- Web server

What is deadlock?

- When two threads are waiting each other and can't precede the program is said to be deadlock.

What is the difference between applications and applets?

- a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface.

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

Enumeration

A data type that is described by using a list of ordered values.

OR operator (||)

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

++ (unary increment operator)

Adds one to an integer variable.

Assertions

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

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.

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.

size property

Property that specifies the width and height, in pixels, of a component.

Executable

Pseudocode usually only describes ____ lines of code.

What does the method .getClass do from the class object?

Returns class name of an object.

{}

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

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;

This type of method method performs a task and sends a value back to the code that called it.

Value-returning

HashMap

a dynamic data structure filled with key value mappings - datatypes of the entries are specified in the declaration - keys are a Set - no duplicates

If a program compiles fine, but it produces incorrect result, then the program suffers ________.

a logic error

An error in a program that results in the program outputting $100 instead of the correct answer, $250 is

a logical error

assembly language

a low level programming language that implements symbolic representation of the numeric machine codes.

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

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

What is arr1,arr2 and arr3? int[] arr,arr2[][],arr3;

arr is an array. arr2 is a triple array. arr3 is a triple array.

assertion

checks for a condition that must be true

overload a method

defining methods with the exact same name put with different sets of arguments/parameters -method will have a different body

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

_______________—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

loop

sequence of instructions that is executed repeatedly

I/O buffer

small amount of memory that the I/O controller has

selection sort

smallest (or largest) value is found and transferred to the output area

A Java program is best classified as

software

computability

something that can be done by symbol manipulation algorithms,; Turing machines define the limits of these

How is the import keyword used?

the import keyword is used to let the compiler know that the class is going to use an external package

What does the public keyword mean?

the public access modifier means that all classes have access to that element

Exceptions

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

What is an accessor?

ways to get variables from class

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)

To assign a value 1 to variable x, you write

x = 1;

If x is an int and y is a float, all of the following are legal except which assignment statement? 1) y = x; 2) x = y; 3) y = (float) x; 4) x = (int) y; 5) all of these are legal

x = y;

What is x after the following statements? int x = 1; x *= x + 1;

x is 2

left operand

An expression that appears on the left side of a *binary operator*.

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)

Why we cannot override static method?

It is because the static method is the part of class and it is bound with class whereas instance method is bound with object and static gets memory in class area and instance gets memory in heap.

nested statement

A statement that is placed inside another control statement.

What happens if their is no default in a switch statement?

Nothing happens.

What is difference between object oriented programming language and object based programming language?

Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc.

Which class is the superclass for every class.

Object class.

Escape Sequence

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

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

The message displayed by the dialog

primative types or built in type

Type of sequence of letters or digits specified by int, boolean, or double.

setText

Use _____ to set the text on the face of a JButton.

Thread safe variables

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

If an instance variable creates an object when will it be ran?

When the class is needed in main for the first time

truncating

When you are ____ in integer division, any fractional part of an integer division result is discarded.

GridLayout

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

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

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

list selection event

constructor

method with no return type; same name as class; default data members and values for instances of the class

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

op code

operation code; unique unsigned integer code assigned to each machine language operation recognized by hardware

extraction phase

remove the root node to the output list then reconstruction step is executed

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

Is it possible to call servlet with parameters in the URL?

- Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).

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

Advantages of exceptions

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

Queues

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

What modifiers may be used with top-level class?

- public, abstract and final can be used for top-level class.

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

________ is a device to connect a computer to a local area network (LAN).

NIC

identifier

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

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)

What is the object type of a polymorphic object instance and what does it have to be?

It is the initialization of the instance. The stuff after the equals sign. It has to be a child of the reference type.

What is a constructor?

is a bit of code that allows you to create objects from a class. You call the constructor by using the keyword new , followed by the name of the class, followed by any necessary parameters. For example, if you have a Dog class, you can create new objects of this type by saying new Dog()

Is the Java language pass by value or pass by reference?

java is passed by value.

What are the only things you can use in switch statements?

byte, short, int, char, string and enum

What are all the primitives?

byte,short,int,long,float,double,char,boolean.

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)

What if I write static public void instead of public static void?

Program compiles and runs properly.

background property

Property that specifies the background color of a content pane component.

What is a well defined class?

Public interface (clearly defined responsibility --single-responsibility principle--Cohesion: the defined responsibilities of the class are meaningful - they make sense -- Delegation: if a task falls outside the responsibility of that class, the task is delegated to another class) Private Implementation (Encapsulation: data-hiding - fields are private (only accessed by getters and setters) and methods not a part of the user interface are private)

setText

Sets the text property of the JTextArea component.

exchange sort

exchange or transposition which systematically interchanges pairs of elements that are out of order until no more such pairs exist

Abstraction

identification of properties and behavior of objects relevant to solving the problem at hand

selection statement

if-else statements; chooses which step to do based on the parameters in the statements

What does the term generic mean?

They allow "a type or method to operate on objects of various types while providing compile-time type safety."[1] This feature specifies the type of objects stored in a Java Collection. List<String> v = new ArrayList<>();

register

storage cell that holds the operands of an arithmetic operation and when the operation is complete holds its result

local variable

variable defined within a method that cannot be accessed outside of that method

syntax

rules that define how to form instructions in a particular programming language; grammer

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

...

divide and assign operator

/=

The extension name of a Java bytecode file is

.class

What is a package?

A folder where your classes are stored

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]

How do you make an object call a method and then cast?

Call the method and put parenthesis with the class type next to it. Ex: (B)aa.m1();

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

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.

What is an object?

an instance of a class

Things an object can do are called?

methods

While loop

while(insert argument here) { insert code here }

What value will z have if we execute the following assignment statement? float z = 5 / 10;

z will equal 0.0

If you want to output a double so that at least 1 digit appears to the left side of the decimal point and exactly 1 digit appears to the right side of the decimal point, which pattern would you give a DecimalFormat variable when you instantiate it?

"0.0"

Suppose that String name = "Frank Zappa". What will the instruction name.toUpperCase( ).replace('A', 'I'); return?

"FRINK ZIPPI"

Take remainder and assign operator

%=

"And" operator

&&

Which of the following is the correct expression of character 4?

'4'

If the String major = "Computer Science", what is returned by major.charAt(1)?

'o'

Multiply and assign operator

*=

add operator

+

Increment by one

++

Add and assign operator

+=

What are JSP Directives?

- A JSP directive affects the overall structure of the servlet class. It usually has the following form:<%@ directive attribute="value" %> However, you can also combine multiple attribute settings for a single directive, as follows:<%@ directive attribute1="value1? attribute 2="value2? . . . attributeN ="valueN" %> There are two main types of directive: page, which lets to do things like import classes, customize the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the time the JSP file is translated into a servlet

What is a stream and what are the types of Streams and classes of the Streams?

- A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are: Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.

What is the difference between superclass and subclass?

- A super class is a class that is inherited whereas sub class is a class that does the inheriting.

Interfaces (implement)

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

What is an I/O filter?

- An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

What is an abstract class?

- An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.

What is adapter class?

- An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested. For example, the MouseMotionAdapter class has two methods, mouseDragged()and mouseMoved(). The signatures of these empty are exactly as defined in the MouseMotionListener interface. If you are interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged() .

What is an applet?

- Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.

What is the difference between Array and vector?

- Array is a set of related data type and static whereas vector is a growable array of objects and dynamic.

What is the difference between Assignment and Initialization?

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

What is BDK?

- BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set of Beans and it can be used to test Beans without writing a code.

Atomic Swing Components

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

What are Class, Constructor and Primitive data types?

- Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.

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

What is meant by controls and what are different types of controls in AWT?

- Controls are components that allow a user to interact with your application and the AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.

What are cookies and how will you use them?

- Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user. a) Create a cookie with the Cookie constructor: public Cookie(String name, String value) b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse. addCookie(Cookie cookie) c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest: public Cookie[ ] HttpServletRequest. getCookie().

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.

What is daemon thread and which method is used to create the daemon thread?

- Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon() method is used to create a daemon thread.

What is Internet address?

- Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number.

What is meant by Inheritance and what are its advantages?

- Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.

What are inner class and anonymous class?

- Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.

What is interface and its use?

- Interface is similar to a class which may contain method's signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a)Declaring methods that one or more classes are expected to implement b)Capturing similarities between unrelated classes without forcing a class relationship. c)Determining an object's programming interface without revealing the actual body of the class.

What is Domain Naming Service(DNS)?

- It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters.

What is JDBC?

- JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.

What type of driver did you use in project?

- JDBC-ODBC Bridge driver (is a driver that uses native(C language) libraries and makes calls to an existing ODBC driver to access a database engine).

What are JSP ACTIONS?

- JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include: jsp:include - Include a file at the time the page is requested. jsp:useBean - Find or instantiate a JavaBean. jsp:setProperty - Set the property of a JavaBean. jsp:getProperty - Insert the property of a JavaBean into the output. jsp:forward - Forward the requester to a newpage. Jsp: plugin - Generate browser-specific code that makes an OBJECT or EMBED

What is JSP?

- JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The advantages are: a) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process. b) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it.

What are JSP scripting elements?

- JSP scripting elements lets to insert Java code into the servlet that will be generated from the current JSP page. There are three forms: a) Expressions of the form <%= expression %> that are evaluated and inserted into the output, b) Scriptlets of the form<% code %>that are inserted into the servlet's service method, and c) Declarations of the form <%! Code %>that are inserted into the body of the servlet class, outside of any existing methods.

What is a Jar file?

- Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. The package java. util. zip contains classes that read and write jar 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!

Applying Encapsulation*

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

What is method overloading and method overriding?

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

What are methods and how are they defined?

- Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method's signature is a combination of the first three parts mentioned above.

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

What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?

- Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.

Sets

- No Duplicates - Usually unordered

Are there any global variables in Java, which can be accessed by other part of your program?

- No, it is not the main method in which you define variables. Global variables is not possible because concept of encapsulation is eliminated here.

What is OOPs?

- Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.

Abstraction (extend)

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

What is serialization and deserialization?

- Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

What is Server-Side Includes (SSI)?

- Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an . shtml extension.

What is servlet?

- Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.

Why should we go for inter-servlet communication?

- Servlets running together in the same server communicate with each other in several ways. The three major reasons to use interservlet communication are: a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object) b) Servlet reuse - allows the servlet to reuse the public methods of another servlet. c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)

What is session tracking and how do you track a user session in servlets?

- Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are: a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password. b) Hidden form fields - fields are added to an HTML form that are not displayed in the client's browser. When the form containing the fields is submitted, the fields are sent back to the server. c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change. d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser. e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session. maxresidents property.

What is the difference between set and list?

- Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.

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.

What are the types of statements in JDBC?

- Statement: to be used createStatement() method for executing single SQL statement PreparedStatement — To be used preparedStatement() method for executing same SQL statement over and over. CallableStatement — To be used prepareCall() method for multiple SQL statements over and over.

What is stored procedure?

- Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.

What is the difference between TCP/IP and UDP?

- TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. It is like a phone call. UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination. It is like a postal mail.

What are the advantages of the model over the event-inheritance model?

- The event-delegation model has two advantages over the event-inheritance model. They are: a)It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component's design and its use. b)It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to be repeatedly process unhandled events as is the case of the event-inheritance.

What is the difference between exception and error?

- The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.

How do servlets handle multiple simultaneous requests?

- The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost() and service()) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

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.

What is the class and interface in java to create thread and which is the most advantageous method?

- Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because thread class implements Runnable.

What are the states associated in the thread?

- Thread contains ready, running, waiting and dead states.

How to create and call stored procedures?

- To create stored procedures: Create procedure procedurename (specify in, out and in out parameters) BEGIN Any multiple SQL statement; END; To call stored procedures: CallableStatement csmt = con. prepareCall("{call procedure name(?,?)}"); csmt. registerOutParameter(column no. , data type); csmt. setInt(column no. , column name) csmt. execute();

What are Transient and Volatile Modifiers?

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

What is URL?

- URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http - protocol name, address - IP address or host name, 80 - port number and index.html - file path.

What is UNICODE?

- Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.

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.

What are Vector, Hashtable, LinkedList and Enumeration?

- Vector : The Vector class provides the capability to implement a growable array of objects. Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the object's keys. Hash codes are integer values that identify objects. LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations. Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements() and nextElement(). HasMoreElemnts() tests if this enumeration has more elements and nextElement method returns successive elements of the series.

Central Repository

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

What is Garbage Collection and how to call it explicitly?

- When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.

When will you synchronize a piece of your code?

- When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.

What is the difference between an argument and a parameter?

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

What is connection pooling?

- With servlets, opening a database connection is a major bottleneck because we are creating and tearing down a new connection for every page request and the time taken to create connection will be more. Creating a connection pool is an ideal approach for a complicated servlet. With a connection pool, we can duplicate only the resources we need to duplicate rather than the entire servlet. A connection pool can also intelligently manage the size of the pool and make sure each connection remains valid. A number of connection pool packages are currently available. Some like DbConnectionBroker are freely available from Java Exchange Works by creating an object that dispenses connections and connection Ids on request. The ConnectionPool class maintains a Hastable, using Connection objects as keys and Boolean values as stored values. The Boolean value indicates whether a connection is in use or not. A program calls getConnection() method of the ConnectionPool for getting Connection object it can use; it calls returnConnection() to give the connection back to the pool.

What are wrapper classes?

- Wrapper classes are classes that allow primitive types to be accessed as objects.

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

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

What is the difference between abstract class and interface?

- a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods.Interface methods are by default public and abstract.Interfaces can have constants, which are always implicitly public,static, and final.Interfaces can extend one or more other interfaces

What is difference between overloading and overriding?

- a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.

What is the difference between Integer and int?

- a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.

What are drivers available?

- a) JDBC-ODBC Bridge driver b) Native API Partly-Java driver c) JDBC-Net Pure Java driver d) Native-Protocol Pure Java driver

What is the difference between JDBC and ODBC?

- a) OBDC is for Microsoft and JDBC is for Java applications. b) ODBC can't be directly used with Java because it uses a C interface. c) ODBC makes use of pointers which have been removed totally from Java. d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required. e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms. f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC.

What is the difference between String and String Buffer?

- a) String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings.

What is the difference between doPost and doGet methods?

- a) doGet() method is used to get information, while doPost() method is used for posting information. b) doGet() requests can't send large amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length. c) A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.

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.

Unchecked exception

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

What is final, finalize() and finally?

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

What is finalize() method?

- finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.

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

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

What is the lifecycle of an applet?

- init() method - Can be called when an applet is first loaded start() method - Can be called each time an applet is started. paint() method - Can be called when the applet is minimized or maximized. stop() method - Can be used when the browser moves off the applet's page. destroy() method - Can be called when the browser is finished with the applet.

What is a reflection package?

- java. lang. reflect package has the ability to analyze itself in runtime.

Maps

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

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

Lists

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

What are different types of access modifiers?

- public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can't be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package.

why is it a good idea to split into layers ?

- read it easer and debug easier

Explain the methods, rebind() and lookup() in Naming class?

- rebind() of the Naming class(found in java. rmi) is used to update the RMI registry on the server machine. Naming. rebind("AddSever", AddServerImpl); lookup() of the Naming class accepts one argument, the rmi URL and returns a reference to an object of type AddServerImpl.

How can I set a cookie in JSP?

- response. setHeader("Set-Cookie", "cookie string"); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) - to the bean, and in jsp-file:<% bean. setResponse (response); %>

What is source and listener?

- source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way. listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.

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.

What is the difference between this() and super()?

- this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.

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

Decrement by one

--

Which of the following lines is not a Java comment? (Choose all that apply.) 1) /** comments */ 2) // comments 3) -- comments 4) /* comments */ 5) ** comments **

-- comments ** comments **

subtract and assign operator

-=

What is the difference between an interface and an abstract class?

-All methods in an interface are implicitly abstract. Abstract classes don't have to have abstract methods but interfaces do. -Interface variables are also final and abstract class variables don't have to be final. -An abstract class implements an interface and does not have to provide implementation for the interface methods.

Object-oriented programming

-Identify and define objects and solve problems by manipulating objects -look at everything as objects that already have a set of directions

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

...

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

...

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

...

What are 5 method of the class object.

.equals, .toString, .clone, .finalize, .getClass

The extension name of a Java source code file is

.java

comment

//

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

If you want to store into the String name the value "George Bush", you would do which statement?

1) String name = "George Bush"; 2) String name = new String("George Bush"); 3) String name = "George" + " " + "Bush"; 4) String name = new String("George" + " " + "Bush");

Which of the following are correct ways to declare variables? (Choose all that apply.) 1) int length; int width; 2) int length, width; 3) int length; width; 4) int length, int width;

1) int length; int width; 2) int length, width;

Which of the following are correct names for variables according to Java naming conventions? (Choose all that apply.) 1) radius 2) Radius 3) RADIUS 4) findArea 5) FindArea

1) radius 4) findArea

Once we have implemented the solution, we are not done with the problem because

1) the solution may not be the best (most efficient) 2) the solution may have errors and need testing and fixing before we are done 3)the solution may, at a later date, need revising to handle new specifications 4) the solution may, at a later date, need revising because of new programming language features

What is difference between static (class) method and instance method?

1)Object is not required to call static method. Object is required to call instance methods. 2)Non-static (instance) members cannot be accessed in static context (static method, static block and static nested class) directly. static and non-static variables both can be accessed in instance methods.

Which array initializations are illegal? 1// int[] arr = new int[]; 2//int []arr = new int[5]; 3// int[][] arr = [1][4]; 4// int arr[][] =new int [][2]; 5// int arr[][] = new int[2][]; 6//int arr = new int[2]; 7//int[][] arr = new[5]{1,2,3};

1,3,4,6,7

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

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.

How many constructors can a class have? 1. Any number 2. 2 3. 1 4. 0

1. Any number

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

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

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

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)

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.

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.

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

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

___________________ 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

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

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

At

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

What is output with the statement System.out.println(x+y); if x and y are int values where x=10 and y=5?

15

What will be returned from the following method? public static double methodA() { double a = 8.5 + 9.5; return a; }

18.0

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

The ________ method displays an input dialog for reading a string. (Choose all that apply.) 1) String string = JOptionPane.showMessageDialog(null, "Enter a string", "Input Demo", JOptionPane.QUESTION_MESSAGE); 2) String string = JOptionPane.showInputDialog(null, "Enter a string", "Input Demo", JOptionPane.QUESTION_MESSAGE); 3) String string = JOptionPane.showInputDialog("Enter a string", "Input Demo", JOptionPane.QUESTION_MESSAGE); 4) String string = JOptionPane.showInputDialog(null, "Enter a string"); 5) String string = JOptionPane.showInputDialog("Enter a string");

2) String string = JOptionPane.showInputDialog(null, "Enter a string", "Input Demo", JOptionPane.QUESTION_MESSAGE); 4) String string = JOptionPane.showInputDialog(null, "Enter a string"); 5) String string = JOptionPane.showInputDialog("Enter a string");

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

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

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.

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.

Suppose x is 1. What is x after x += 2?

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

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.

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.

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.

Which of the following is the array subscripting operator in Java? 1. . 2. {} 3. [] 4. new

3. []

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

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

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

Which of the following expression results in a value 1? 1) 2 % 1 2) 15 % 4 3) 25 % 5 4) 37 % 6

37 % 6

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

What is the length of TEXT?

4

Which of the following is not syntactically legal in Java? 1) public class Foo 2) System.out.println("Hi"); 3) { } 4) s t a t i c main(String[ ] args) 5) only System.out.println("Hi"); is legally valid, all of the rest are illegal

4) s t a t i c main(String[ ] args)

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.

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.

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

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.

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 }

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}

cache memory

5 to 10 times faster than RAM, but smaller. When a computer uses something it'll use it again very soon -> move the data from regular RAM to cache

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

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

6 bits can be used to represent ________ distinct items or

64

long

64 bit

Note that the Unicode for character A is 65. The expression 'A' + 1 evaluates to ________.

66

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.

The expression (int)(76.0252175 * 100) / 100 evaluates to ________.

76

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.

What will be displayed by this command: System.out.println(Math.pow(3, 3-1));

9

int

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

The Unicode of 'a' is 97. What is the Unicode for 'c'?

99

Less than

<

Which of the following characters does not need to have an associated "closing" character in a Java program? 1) { 2) ( 3) [ 4) < 5) all of these require closing characters

<

Less than or equal to

<=

Type parameter

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

________ is the Java assignment operator.

=

What is the difference between = and ==?

== is used for comparison and = is used for assignment.

Transfer of control

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

When a method tests an argument and returns a true or false value, it should return

A boolean value

state button

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

newline

A character that is inserted in code when you press Enter.

What does it mean for a method to take in an interface as a parameter.

A class that implements that interface must be passed.

JOptionPane

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

full-line comment

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

If class B has method m1 and class A doesn't, what happens? A a = new B(); a.m1();

A compilation error. If class A has the method and class B doesn't the method will be called from class A, if class B overrides that method, class B's method will be called. Their will be a compilation error if A doesn't have that method.

JTextField component

A component that can accept user input from the keyboard or display output to the user.

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.

use of constructors in new instances

A constructor is a special method whose purpose is to construct and initialize objects

Switch Statement

A control flow statement that takes an argument and compares it to the cases supplied to it - runs the code under a case if the arguments are equal - will run all the code underlying one case if a 'break' or 'return' is not encountered.

What does it mean when an object is passed by value?

A copy is made and that copy is passed. When something is passed by value any changes to that value doesn't affect the actual object.

double

A datatype that can *represent numbers with decimal points*.

When dividing what must the variable be put into?

A double because division automatically sets it to a double.

By default what is this considered - 12.21?

A double.

source code file

A file with a .java extension. These files are editable by the programmer, but are not executable.

What is blank final variable?

A final variable, not initalized at the time of declaration, is known as blank final variable.

What does the finally keyword do?

A finally code block can be placed after a try catch block. The code in the finally block will always run whether or not an exception is thrown.

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.

What does the term generic mean?

A generic type is a parameterized type - a type

block

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

variable

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

Package

A logical collection of associated classes, which in its own directory, subdirectory be saved.

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.

AND operator (&&)

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

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.

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.

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.

setText

A method that sets the text property of a component, such as a JLabel, JTextField or JButton.

Instance Variable

A non static field - a variable that applies only to the instance of the class in which it is instantiated.

floating-point number

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

What is platform?

A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.

pixel

A point on your computer screen. ____ is short for "picture element".

algorithm

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

String

A sequence of characters that represents text information.

algorithm

A sequence of steps that is unambiguous, executable, and terminating. a well ordered collection of unambiguous and effectively computable operations that when executed produces a result and halts in a finite amount of time

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.

SERVLET

A small program that runs on the server. Is mainly used to generate HTML pages.

While Statement

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

application

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

What is static method?

A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class. static method can access static data member and can change the value of it.

book-title capitalization

A style that capitalizes the first letter of each significant word in the text (for example, Calculate the Total).

white space

A tab, space or newline is called a(n) _____.

Print

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

constant

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

Turing machine

A very simple model of a computing agent proposed by Alan Turing that is used in theoretical computer science to explore computability of problems

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.

Three

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

Can we treat all types of exceptions the same?

All exceptions can be caught by using the Exception or Throwable type.

dot separator

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

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.

declaration

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

exception

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

checked exception

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

right operand

An expression that appears on the right side of a binary operator.

operand

An expression that is combined with an operator (and possibly other expressions) to perform a task (such as multiplication).

What is a field?

An instance variable

binary operator

An operator that requires two operands.

unary operator

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

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

Any number

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

Why method overloading is not possible by changing the return type in java?

Becauseof ambiguity.

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

Both are false.

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

Both expressions are true.

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

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

Method m1 has a declaration of void m1() and m2 has a method declaration of public static void m2(). m2 wants to call m2, how does m2 do that?

By making an instance of the class m1 is in and using that, or by changing its method declaration so it is not static.

How can objects be ready for garbage collection(name three ways)?

By setting an object to null, setting an object to another object or setting it to a NEW object.

How can a method send a primitive value back to the caller?

By using the return statement

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;

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.

CLOB

Character Large OBject

semicolon (;)

Character used to terminate each statement in an application.

What are the different types of exception in Java?

Checked and unchecked exceptions. Checked exceptions are caught by the compiler while run time exceptions are ignored by the compiler and don't show up until run time.

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

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.

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

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.

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

What is a constant?

Constants are variables that cannot be changed.

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.

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

clear

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

How do you declare a String Builder/ String Buffer

Declaration: StringBuilder S2 = new StringBuilder("Test String") or by using the default constructor.

Statement (JDBC)

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

In a @return tag statement the description

Describes the return value

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

Dynamic

What is the stack? What kinds of variables are created there?

Each Java virtual machine thread has a private Java virtual machine stack, created at the same time as the thread. A Java virtual machine stack stores frames. A Java virtual machine stack is analogous to the stack of a conventional language such as C: it holds local variables and partial results, and plays a part in method invocation and return. Because the Java virtual machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated.

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

Events

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

What does the substring method written like this return - stringName.subString(1)?

Everything from index 1 and up(Inclusive)

Predefined Java classes

Example of 2: Object class & String class

What does the substring method written like this return - stringName.subString(6,5)?

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.

What will be printed if null was on the left side of the instance of operator?

False

Staging area

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

What is final class?

Final class can't be inherited.

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

Finally block

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.

What does the method .toString do from the class object?

Gives a string representation of an object. This is usually overridden and if not will print the area memory.

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.

Types of sets

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

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

JTextField

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

What is composition?

Holding the reference of the other class within some other class is known as composition.

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.

case sensitive

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

What is method overloading?

If a class have multiple methods by same name but different parameters, it is known as Method Overloading. It increases the readability of the program.

What is method overriding?

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to provide the specific implementation of the method.

The body of a while statement executes _____.

If it's condition is true

Church-Turing Thesis

If there exists an algorithm to do a symbol manipulation task, then there exists a Turing machine to do that task

What is final variable?

If you make any variable as final, you cannot change the value of final variable(It will be constant).

base or radix

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

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

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.

What is static block?

Is used to initialize the static data member. It is excuted before main method at the time of classloading.

What is the advantage of putting an image in a JLabel instance?

It becomes part of the component and is laid out automatically

What happens when a class final?

It cannot be extended?

In the following list, which statement is not true regarding Java as a programming language? 1) It is a relatively recent language, having been introduced in 1995 2) It is a language whose programs do not require translating into machine language before they are executed 3) It is an object-oriented programming language 4) It is a language that embraces the idea of writing programs to be executed using the World Wide Web 5) all of these are true

It is a language whose programs do not require translating into machine language before they are executed

If I don't provide any arguments on the command line, then the String array of Main method will be empty or null?

It is empty. But not null.

What is the package with no name?

It is the package that is created by default if a class is not put in a package.

What does the method .finalize do from the class object?

It is used to make something ready for garbage collection.

What is overriding?

It is when a subclass uses the same name and same signature as a method in the parent class.

What is the function of a frame's pack method?

It sets the size appropriately for display

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

JCheckBox Text

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

JMenuItem

Which of the following GUI components is used to accept input into a JFrame? 1) JLabel 2) JPanel 3) JInput 4) JTextField 5) JInputField

JTextField

Why main method is static?

JVM creats object first then call main() method that will lead to the problem of extra memory allocation.

What is difference between JDK,JRE and JVM?

JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed. JRE stands for Java Runtime Environment. It is the implementation of JVM and physically exists. JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.

________is an object-oriented programming language.

Java C++

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.

What is the JVM?

Java Virtual Machine.

Java compiler translates Java source code into ________.

Java bytecode

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

What is JIT compiler?

Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

Benefits of Encapsulation*

Maintainability, Flexibility and Extensibility.

How do you make a constant.

Make a variable with final and static modifiers.

In order to preserve encapsulation of an object, we would do all of the following except for which one?

Make the class final

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

kilobyte

Maximum memory size is 2^10 memory bytes

megabyte

Maximum memory size is 2^20 memory bytes

Difference between method Overloading and Overriding.

Method Overloading Method Overriding 1) Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its super class. 2) method overlaoding is occurs within the class. Method overriding occurs in two classes that have IS-A relationship. 3) In this case, parameter must be different. In this case, parameter must be same.

This part of a method is a collection of statements that are performed when the method is executed.

Method body

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

Can a byte be set to an int variable?

No

Can a local variable be protected?

No

Can a short be passed to the append method in String Builder?

No

Can a static method be overridden without the static modifier and vise versa?

No

Can an abstract method be final?

No

Can an abstract method be static?

No

Can their be any duplicate cases in a switch statement?

No

Does the StringBuilder class override the equals method in object?

No

If a class has a private constructor can their be an instance of that class(object) outside of the class?

No

If a superclass implements an interface and a subclass implements the same interface is their a compilation error?

No

Is it legal to use .this in static methods?

No - .this and .super cannot be used or a compilation error will happen.

Can a class be protected(Given it is not an inner class)?

No - Inner classes can be private or protected regular classes cannot.

Is it legal to have the same method with the same parameters but a different return type?

No - The parameters have to be different.

Can you initialize an array like this - int arr2[] = {1,2,3,4}

No - You need the new keyword

Can you override Strings methods if yes why?

No because String is a final class.

Will this compile and if not why? Short ss = new Short(9);

No, 9 is automatically an int and their is no int constructor for short.

Is it possible for an interface to be an object type in a polymorphic object?

No, interfaces can't be instantiated.

Is this valid code? while(false){ System.out.println("Hey"); }

No, it will cause a compilation error because of unreachable code. If their is a boolean that is false and it is put inside the parenthesis it fine.

Can you call a non static method in main without using an instance of the class?

No, main is static and therefore cannot call non static variables or methods.

Can local variables use access modifiers?

No, since local variables are local they will not be seen outside of the class.

Is it legal for a non-static method to be called in a static one?

No, static methods and variables cannot be called in non static methods and vice versa.

Can you set a float to 1.0?

No, that would automatically make it a double.

Can you statically import a package?

No, you can only import classes statically.

Can we override static method?

No, you can't override the static method because they are the part of class not object.

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

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

hexidecimal

Number utilizing base 16

heap sort

O(nlog2n) comparisons; consists of two phases, the construction and extraction phase

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

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.

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)

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)

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)

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)

Which properties are true of String objects? 1) Their lengths never change 2) The shortest string has zero length 3) Individual characters within a String may be changed using the replace method 4) The index of the first character in a string is one 5) Only Their lengths never change and The shortest string has zero length are true

Only Their lengths never change and The shortest string has zero length are true

Define the keyword "private"

Only able to be modified inside the class.

The lifetime of a method's local variable is

Only while the method is executing

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.

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

Operator && __.

Performs short-circuit evaluation

FlowLayout

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

Why Java does not support pointers?

Pointer is a variable that refers to the memory address. They are not used in java because they are unsafe(unsecured) and complex to understand.

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.

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;

What if the static modifier is removed from the signature of the main method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

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

font property

Property specifying font name (Times New Roman), style (Bold) and size (12) of any text.

Commit

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

How do you make an object cast first and then call a method?

Put the class in parenthesis next to the method and surround that in parenthesis. Ex: class B extends A{} A aa = new B(); ((B)aa.m1())

What does array.asList do?

Puts an array as an array list.

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

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.

executeQuery (SQL command)

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

What does the method .compareTo do from the class String?

Returns a integer when comparing to strings. Ex: String s = new String("sam"); String s1 = new String("Sam"); s.compareTo(s1); ------- Returns 32 because S and s are 32 unicode codes away.

What does the substring method written like this return - stringName.subString(3,3)?

Returns nothing

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

What does the .indexOf() method return?

Returns the first occurrence of the char, or string. If a number is provided this is where the method starts looking for the specified string/char.

Static Variables and Threads

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

What do static imports import?

Static variables and static methods.

Following Java naming convention, which of the following would be the best name for a class about store customers? 1) StoreCustomer 2) Store Customer 3) storeCustomer 4) STORE_CUSTOMER 5) Store-Customer

StoreCustomer

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

Which of the following could be used to instantiate a new Student s1? 1) Student s1 = new Student( ); 2) s1 = new Student( ); 3) Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33); 4) new Student s1 = ("Jane Doe", "Computer Science", 3.333, 33); 5) new Student(s1);

Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33);

Properties rule (subtypes)

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

Java was developed by ________.

Sun Microsystems

Which of the following statements is correct to display Welcome to Java on the console? (Choose all that apply.) 1) System.out.println('Welcome to Java'); 2) System.out.println("Welcome to Java"); 3) System.println('Welcome to Java'); 4) System.out.print('Welcome to Java'); 5) System.out.print("Welcome to Java");

System.out.println("Welcome to Java"); System.out.print("Welcome to Java");

If you want to output the text "hi there", including the quote marks, which of the following could do that?

System.out.println("\"hi there\"");

Which of the following statement prints smith\exam1\test.txt?

System.out.println("smith\exam1\test.txt");

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

Assume that x is a double that stores 0.362491. To output this value as 36%, you could use the NumberFormat class with NumberFormat nf = NumberFormat.getPercentInstance( ); Which of the following statements then would output x as 36%?

System.out.println(nf.format(x));

Does constructor return any value?

Technically it returns the constructed object

Glass box

Testing code (can see code)

Black box

Testing to specifications (code unseen)

If you print THIS in system.out.println, what will print?

That classes toString.

What does it mean if a string is immutable?

That it cannot be changed once it is created.

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.

DecimalFormat

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

What is the purpose of default constructor?

The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class.

making your first object - The dot operator explained

The dot operator (,) give access to an object's state and behavior ( instance variables and methods). // make new object Dog d= new Dog(); //tell the dog to bark by using dot operator //om the variable d to call the bark() d.bark(); //set its size using the dot operator d.size=40;

Decimal points

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

Enumeration constants

The individual values ​​that can take a variable of data type enumeration.

extends keyword

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

What is the default value of the local variables?

The local variables are not initialized to any default value, neither primitives nor object references.

straight-line form

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

What happens when you call the .equals method for a StringBuilder?

The memory location is shown.

Variable

The name (an identifier) given to a container that holds values in a Java program

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)

What will be the initial value of an object reference which is defined as an instance variable?

The object references are all initialized to null in Java.

If you print an object what will be printed?

The objects toString method.

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.

Incrementing

The process of adding 1 to an integer.

Sequential

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

destructive

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

debugging

The process of locating and removing errors in an application.

nondestructive

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

Decrementing

The process of subtracting 1 from an integer.

compiling

The process that converts a source code file (.java) into a .class file.

horizontalAlignment property

The property that specifies how text is aligned within a JLabel is called:

JDBC

The set of classes which allows easy access to databases.

program control

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

functionality

The tasks or actions an application can execute.

JCheckBox text

The text that appears alongside a JCheckBox.

Sequence, selection and repetition

The three types of program control are _____.

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

What is an actual parameter?

The value passed into a method by a method call

EJB

They run on the server are not graphically oriented, but rather will perform tasks in database manipulation, network, ...

multiplication operator

This operator is an asterisk (*), used to ____ its two numeric operands.

Halting Problem

To determine if a collection of Turing machine instructions together with any initial tape contents will ever halt if started on that tape

initialization

To start, the first value given to a variable

TCP

Transport Control Protocol; the two programs at the source and destination node need to establish a connection; that is, they must first inform each other of the impending message exchange, and they must describe the "quality of service" they want to receive. TCP uses the ARQ algorithm

A JCheckBox is selected when the isSelected method returns __.

True

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.

Throwable

Used to define own exceptions.

showMessageDialog

Used to display a message dialog: JOptionPane.____.

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.

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

JTextField.RIGHT

Used with setHorizontalAlignment to right align the text in a JTextField.

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

How are Servlets and JSP Pages related?

When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.

What does it mean when something is passed by reference?

When something is passed by reference, changes made to it will be changed. You are passing the reference of the object and therefore changing it.

reserved words or keywords

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

In the StringMutation program shown in Listing 3.1, if phrase is initialized to "Einstein" what will Mutation #3 yield if Mutation #1: mutation1 = phrase.concat(".")?

XINSTXIN.

Are StringBuffer/StringBuilder final classes?

Yes

Can an abstract class extend a concrete one?

Yes

Can an abstract class have a constructor?

Yes

Can array use all of the methods that object can?

Yes

Can you compare a byte with a float by using ==?

Yes

Can you compare an int with a double by ==?

Yes

Can you forget some parts of a for loop?

Yes

Can you have an array of objects?

Yes

Can you use short in a switch statement?

Yes

Can you use underscores in primitives not including char or boolean?

Yes

Do you have to initialize a local variable?

Yes

Does every object have their own copies of instance variables and non static method?

Yes

If an array list is of type integer and you try to set it as an array with the method .asList that has a type of int will it compile?

Yes

Is the String class final?

Yes

Is the instance block executed before the constructor?

Yes

Can you assign an integer to a character?

Yes - Only if it is put as an integer like 5 not if it assigned a variable that stores an int.

Can an object have more than one type?

Yes - it can implement n-amount of interfaces as well as extend a class thereby taking on the type of many other classes

Can you have virtual functions in Java?

Yes, all functions in Java are virtual by default.

Can we intialize blank final variable?

Yes, only in constructor if it is non-static. If it is static blank final variable, it can be initialized only in the static block.

Is Empty .java file name a valid source file name?

Yes, save your java file by .java only, compile it by javac .java and run by java yourclassname

Can you declare the main method as final?

Yes, such as, public static final void main(String[] args){}.

Can you make your own types of exceptions? If so,how? If not why?

You can create a custom exception classes by inheriting the Exception class

print

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.

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.

What happens if you declare a class constructor to have a void return type?

You'll likely receive a syntax error

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.

output JTextField

a JTextField used to display calculation results. The editable property of an output JTextField is set to false with setEditable.

Single Responsibility Principle

a class should do one thing and do it well - which is to say it should be cohesive

Inheritance

a class the inherits gets all the methods and variable of the parent class

Cohesion

a cohesive class is one whose defined responsibilities are meaningful - an OrderFactory class shouldn't be used to create an order as well as parse dates. - it should do one thing and do it well, delegating task outside of its responsibility to other classes

As presented in the Software Failure, the root cause of the Mars Climate Orbiter problem was

a communication issue between subsystems

What is JavaDoc?

a documentation generator from Oracle that can create API documentation in HTML from java source code using annotations.

Mutator method

a method that modifies the object on which the method is invoked

Interface

a reference type that provides a template for a contract bw one class and another. composed of method signatures which define the public interface of the implementing class

constructor

a sequence of statements for initializing a newly instantiated object; the job of the constructor is to initialize the instance variables of an object

computer network

a set of independent computer systems connected by telecommunication links for the purpose of sharing information and resources

In Java a variable may contain

a value or a reference

instance variable

a variable defined in a class for which every object of the class has its own value

The software failure at the Denver International Airport's baggage handling system is a good example of 1) how a large system can be obsolete by the time it is developed 2) how designers sometimes have too much faith in the technology they are using 3) how failures are often a result of multiple variables caused by a system as a whole in actual operation 4) how the use of a centralized computer is really unrealistic in today's distributed processing 5) all of these

all of these

Consider a method defined with the header: public void doublefoo(double x). Which of the following method calls is legal? 1) doublefoo(0); 2) doublefoo(0.555); 3) doublefoo(0.1 + 0.2); 4) doublefoo(0.1, 0.2); 5) all of these are legal except for doublefoo(0.1, 0.2);

all of these are legal except for doublefoo(0.1, 0.2);

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.

Java.text's NumberFormat class includes methods that

allow you to format currency, allow you to format percentages, round their display during the formatting process, but not truncate their display during the formatting process

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}

abstract

an abstract class can not be instantiated. It can act as a parent class where the child class implements the abstaract methods of the abstract class

computing agent

an abstract entity that can carry out the steps of the algorithm. They 1) accept input, 2) Store information and retrieve from memory, 3) Take actions according to algorithm instructions, 4) Produce an output.

what is an array?

an array is a container object of fixed length that holds values of one type

logic gate

an electronic device that operates on a collection of binary inputs to produce a binary output.

boolean expression

an expression that evaluates to either true or false

instance

an object of a particular class

instance

an object; created from a class

software life cycle

analysis, design, coding, testing, operation

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.

binary search

array must already be sorted; O(log2n) comparisons; search starts in the middle of the array and searches the array by halves

two-dimensional array

array with an array at each element in the array

Assertion code

assert boolean_expression; assert boolean_expression : displayable_expression;

ARQ algorithm

automatic repeat request; basis for all data link control protocols in current use -> a message is sent from A to B, A holds on the the message until an ACK is sent back from B

What is the syntax of a sequence control flow example?

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

What does pass by reference mean?

by reference means the called functions' parameter will be the same as the callers' passed argument (not the value, but the identity - the variable itself)

A unique aspect of Java that allows code compiled on one machine to be executed on a machine of a different hardware platform is Java's

bytecodes

A single character

char

Which of the following assignment statements is correct? (Choose all that apply.) 1) char c = 'd'; 2) char c = 100; 3) char c = "d"; 4) char c = "100";

char c = 'd'; char c = 100;

Constructors have the same name as the ____. 1. data members 2. package 3. class 4. member methods

class

class derived from another class?

class inherits from class

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.

In a UML diagram for a class

classes are represented as rectangles there may be a section containing the name of the class there may be a section containing the attributes (data) of the class there may be a section containing the methods of the class

What is a local class?

classes that are defined in a block, which is a group of zero or more statements between balanced braces. You typically find local classes defined in the body of a method.

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.

Data Hiding

data hiding is the concept of maintaining private fields within a class - if they are not meant to be modified, don't provide a setter - if they aren't meant to be accessed don't provide a getter

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.

A Java variable is the name of a

data value stored in memory that can change its value but cannot change its type during the program's execution

variable

data value that can change

properties

data values(members) -variables -constants

primitive data type

determines the values a variable can contain; int, byte, short, long, double, float, char, boolean

What does encapsulation mean?

encapsulation is a term that refers to the separation of the public interface and private implementation of an object - the objects inner implementation should be hidden from the user. hide data by using the private keyword on fields and methods that users do not need to know about

An example of passing message to a String where the message has a String parameter would occur in which of the following messages? 1) length 2) substring 3) equals 4) toUpperCase 5) none of these, it is not possible to pass a String as a parameter in a message to a String

equals

exception

error condition that can occur during the normal course of program execution; exception is thrown

short circuit evaluation

evaluation in which the programmer puts the conditions more likely to cause the control statement to not execute first

delegation based event model

event handling implemented by two types of objects: event source and event listener objects

try-catch control statement

exception control statement; statements are executed in the try block, when an exception is thrown, catch block is executed and rest of try block ignored

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

exception handler

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.

Polymorphism

exhibiting different designs for the same behavior (ie method name) as a result of objects of different classes; not the same as overriding

cast

explicitly converting a value from one type to a different type

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

extends

In order to create a constant, you would use which of the following Java reserved words?

final

Which of the following are storage devices? (Choose all that apply.) 1) floppy disk 2) hard disk 3) flash stick 4) CD-ROM

floppy disk hard disk flash stick

event-driven programming

flow of execution is determined by events;

Consider a method defined with the header: public void foo(int a, int b). Which of the following method calls is legal? 1) foo(0, 0.1); 2) foo(0 / 1, 2 * 3); 3) foo(0); 4) foo( ); 5) foo(1 + 2, 3 * 0.1);

foo(0 / 1, 2 * 3);

What is the syntax of a looping control flow example?

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

Write an endless for loop where i=10

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

Close Window (GUI)

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

overloading a method

giving more than one meaning to a method name

Programming style is important, because ________. (Choose all that apply.) 1) a program may not compile if it has a bad style 2) good programming style can make a program run faster 3) good programming style makes a program more readable 4) good programming style helps reduce programming errors

good programming style makes a program more readable good programming style helps reduce programming errors

binary tree

graph with edges, connected nodes such that there is a root node and no node has more than two children nodes

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.

instruction register

holds a copy of the instruction fetched from the memory. It holds both the op code and the addresses

array

holds a fixed number of values of a given type

Which of the following is a legal Java identifier? 1) i 2) class 3) ilikeclass! 4) idon'tlikeclass 5) i-like-class

i

instance variables

identifiers used to descibe the attributes of an object.

Write an if then else statement where i=10

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

What is the syntax of a decision control flow example?

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

coding

implement the design into a program; result is a program

array element

individual value in an array

pseudocode

informal programming language with English-like constructs modeled to look like statements in a java-like language

Which of the following Applet methods is called automatically when the applet is first loaded? 1) Applet (the Applet's constructor) 2) init 3) start 4) getCodeBase 5) getImage

init

Suppose a Scanner object is created as follows: Scanner input = new Scanner(System.in); What method do you use to read an int value?

input.nextInt();

Things an object knows about itself are called ?

instance variables

instance data value

instances of the same class will possess the same set of data values

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

Write an endless while loop where i=10

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

To declare an int variable number with initial value 2, you write

int number = 2;

What is JavaDoc?

is a documentation generator from Oracle Corporation for generating API documentation in HTML format from Java source code. The HTML format is used to add the convenience of being able to hyperlink related documents together.

local variable

is a variable that is declared in the body of a method

Which JDK command is correct to run a Java application in ByteCode.class?

java ByteCode

Which library package would you import to use NumberFormat and DecimalFormat?

java.text

The JDK command to compile a class in the file Test.java is

javac Test.java

reconstruction step

last child is moved to root node, check and update the heap to satisfy the value-relationship constraint starting at the root

How is the ternary operator structured?

logical-expression? expr1:expr2; expr1 gets executed if logical-expression is true, if not expr2 gets executed. If it is being set to a variable the value of what expression gets executed gets put into that variable.

Consider a sequence of method invocations as follows: main calls m1, m1 calls m2, m2 calls m3 and then m2 calls m4, m3 calls m5. If m4 has just terminated, what method will resume execution?

m2

Computer can execute the code in ________.

machine language

terabyte

maximum memory size is 2^40 memory bytes

Instance data for a Java class

may be primitive types or objects

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.

What does pass by value mean?

means the called functions' parameter will be a copy of the callers' passed argument.

class method

method defined for a class

instance method

method defined for an object

Having multiple class methods of the same name where each method has a different number of or type of parameters is known as

method overloading

Accessor method

method that accesses an object and returns some information about it, without changing the object

The behavior of an object is defined by the object's

methods

overload

methods having the same name but different parameter types

behaviors

methods; action for the object to do

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

CH13: This is a key that activates a component just as if the user clicked it with the mouse.

mnemonic

In order for a computer to be accessible over a computer network, the computer needs its own

network address

Internet Protocol

network layer in the Internet; the IP uses 32-bit addresses to identify different nodes.

Which of the following reserved words in Java is used to create an instance of a class? 1) class 2) public 3) public or private, either could be used 4) import 5) new

new

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.

Thread Life Cycle

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

mass storage

nonvolatile storage, information can be saved between shutdowns. The storage of large amounts of data in a persisting and machine-readable fashion.

iterator

object that enables steping through a container

off-by-one error

one fewer iteration or one too many

Which of the following is a legal Java identifier? 1) 1ForAll 2) oneForAll 3) one/4/all 4) 1_4_all 5) 1forall

oneForAll

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.

If you want to draw a red circle inside of a green square in an applet where the paint method is passed a Graphics object called page, which of the following sets of commands might you use?

page.setColor(Color.green); page.fillRect(50, 50, 100, 100); page.setColor(Color.red); page.fillOval(60, 60, 80, 80);

the reserved words

public static void class

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

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

To define a class that will represent a car, which of the following definitions is most appropriate? 1) private class car 2) public class car 3) public class Car 4) public class CAR 5) private class Car

public class Car

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.

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

List all the access modifiers in order from most visible to least?

public, protected, default, private.

Variables in interfaces are declared what automatically?

public, static and final.

The ability to directly obtain a stored item by referencing its address is known as

random access

string

reference data type; array of characters; immutable; pass-by-value

interface

reference data type; includes only constants and abstract methods

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.

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.

notifyAll() (Thread Communication)

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

method

sequence of instructions that a class or an object follows to perform a task

SASD

sequential access storage device does not require that all units of data be identifiable via unique addresses; to find the data, we must search sequentially, asking "Is this what I'm looking for?"

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

sequential search

linear search

sequential search; n/2 comparisons; array is searched from the first position to the last position

initialize

set a variable to a well-defined value when it is created (primitive data types)

Method Parameters

set in a method declaration - specify the number and type of arguments to be passed into the method

instruction set

set of all operations that can be executed by a processor

Package

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

CH13: This method can be used to store an image in a JLabel or a JButton component.

setIcon

CH13: This method sets the intervals at which major tick marks are displayed on a JSlider component.

setMajorTickSpacing

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)

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

I/O controller

special-purpose computer whose responsibility is to handle the details of input/output and to compensate for any speed differences between I/O devices and other parts of the computer

parameter passing

specifying expressions to be arguments for a method when it is called

merge sort

splits the list into two equal halves and places them in separate arrays, each array is recursively sorted then merged back together to form the final sorted list

What does API stand for?

stands for Application Programming Interface and it's simply a way to get information and pass information to trusted partners.

In addition to their usage providing a mechanism to convert (to box) primitive data into objects, what else do the wrapper classes provide?

static constants

What is static variable?

static variable is used to refer the common property of all objects (that is not unique for each object) . static variable gets memory only once in class area at the time of class loading.

Heap

stores java object

A cast is required in which of the following situations? 1) using charAt to take an element of a String and store it in a char 2) storing an int in a float 3) storing a float in a double 4) storing a float in an int 5) all of these require casts

storing a float in an int

CH11: In an inheritance relationship, this is the specialized class.

subclass

arithmetic/Logic Unit (ALU)

subsystem that performs such mathematical and logical operations as addition, subtraction, and comparison for equality; registers, interconnections between components, and ALU circuitry

CH11: This key word refers to an object's superclass.

super

CH11: In an inheritance relationship, this is the general class.

superclass

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

boolean expression

test condition

Method Body

the code held bw the curly braces following the method

portability

the computer program is independent of the details of each particular computer's machine language because each compiler takes care of the translation

The System.currentTimeMillis() returns ________.

the current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time)

formal parameter

the data type and variable name of a reference or value that is defined in a method definition

What does it mean if one class is derived from another?

the derived class extends from its ancestor class - inherits state and behavior

what is a subclass?

the descendant of a superclass

What does it mean to be loosely coupled?

the implementation of one class is not dependent on that of another - well defined classes with only one responsibility are easier to test and are not dependent on the implementations of other classes - by programming to the behavior of interfaces, the implementation behind the interface is irrelevant as any class that implements that interface can interact with those that are programmed to the behavior of the interface

software

the intangible instructions and data that are necessary for operating a computer or another device

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

Method Signature

the method name and parameter list (cannot overload a method by changing the return type if all other properties of the method are equals)

implicit parameter

the object on which a method is invoked

scope

the part of a program in which a variable can be accessed

operating system

the program that controls the overall operation of the computer; it communicates with the users and carries out their requests

Protected Keyword

the protected keyword limits the access of a class member to only those classes which reside within the same package

To determine the number of valid elements in an ArrayList, use:

the size() method

What does the static keyword mean?

the static keyword is used to define a field or method that will not change across all instances of that class - it defines a class level element that can be accessed without instantiating an object of that class

Dynamic binding

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

throws keyword

the throws keyword is used to declare and throw exceptions as opposed to the throw keyword which is followed by a specific instance of an exception (throw new Exception();)

What is composition? How is it used?

the way in which you model objects that contain other objects . To use composition in Java, you use instance variables of one object to hold references to other objects

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

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

Try catch exception block

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

A Java character is stored in ________.

two bytes

testing

unit testing or integration testing; debugging

Define the keyword "implements"

used to implement an interface.

What is a lambda?

using anonymous classes Lambda expressions let you express instances of single-method classes more compactly

argument

value passed into an object

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)

What is shadowing?

when a local variable has the same name as another variable in the same scope thus hiding the non local variable

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

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

WAN

wide area network that connects devices that are not in close proximity but rather are across town, across the country, or across the ocean. Characteristics: Store-and-forward, packet-switched technology. Message transmitted by packets. Failure of a single node doesn't bring down the entire network.

The advantage(s) of the Random class' pseudo-random number generators, compared to the Math.random method, is that

you may create several random number generators you can generate random ints, floats, and ints within a range you can initialize and reinitialize Random generators

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 }

Math.pow(2, 3) returns ________.

8.0

JTextArea

Display textual data or accept large amounts of text input.

Take remainder operator

%

24 % 5 is ________.

4

Book-Title

You should use _____ capitalization for a JButton's name.

Assume that x, y, and z are all integers (int) equal to 50, 20, and 6 respectively. What is the result of x / y / z?

0

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

2, 3

Empty String

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

setIcon

4. Use ____ to specify the image to display on a JLabel.

Given: 1//int a = 7; 2//static int ab = 9; 3//final static int abc = 6; 4//static void m1(){ 5//ab = 9 + 3; 6//a = a + 9; 7//abc++; } Where is the compilation error?

At Line 6, this is because a non-static variable is being accessed in a static method.

CruiseControl

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

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

selected

Defines if a component has been selected. (property)

case sensitive

Distinguishes between uppercase and lowercase letters in code.

Define the keyword "static"

Does not change. Cannot make an instance of.

DNS

Domain Name System; converts from a symbolic host name such as Columbia.edu to its 32-bit IP address

The ________ method parses a string s to a double value.

Double.parseDouble(s);

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

What are Encapsulation, Inheritance and Polymorphism?

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

What happens when you divide and Int by 0?

Exception

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

Exclamation point

If Integer xx = 10 and Integer yy = 10, is this true or false? xx==yy?

False

What is the ONLY modifier local variables can use?

Final, anything else will be a compilation error.

What b before calling method m1() that returns an int? int b = m1();

It is one

What is the reference type of a polymorphic object instance?

It is the declaration of the instance. The stuff before the equals sign.

When instantiating a new instance of a class and you use final what does this mean?

It means you cannot allocate a new space in memory for that instance.

If a parent class has a constructor that takes parameters what must the child constructor do, if anything at all?

It must call that parents constructor with super().

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)

iterator()

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

________provides an integrated development environment (IDE) for rapidly developing Java programs. Editing, compiling, building, debugging, and online help are integrated in one graphical user interface.

Java IDE

________ consists of a set of separate programs for developing and testing Java programs, each of which is invoked from a command line.

Java JDK

posttest loop

loop body is executed at least once, then condition is tested

sentinel-controlled loop

loop body is executed until a certain condition is met

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

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;

How can you cast a polymorphic object?

To the object type or any of its subclasses.

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.

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

round off errors

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

keyPressed event

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

What does a finally block do?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

message dialog

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

class keyword

The keyword used to begin a class declaration.

actionPerformed

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

The expression "Java " + 1 + 2 + 3 evaluates to ________.

Java 123

________ contains predefined classes and interfaces for developing Java programs.

Java API

What is the JDK?

Java Development Kit.

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

Java Development Kit (JDK)

Java compiler and interpreter. includes JRE and JSE API

________is a technical definition of the language that includes the syntax and semantics of the Java programming language.

Java language specification

Java portability

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

Implicit cast

Java takes the value of a variable of the narrower type and stops this value in a variable with a different type with more storage options.

final

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

The line of Java code "// System.out.println("Hello");" will

do nothing

If you attempt to add an int, a byte, a long, and a double, the result will be a ________ value.

double

Subtype rules

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

8 bit integer

byte

multiline statement

A statement that is spread over multiple lines of code for readability.

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)

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}

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}

Defines a block of code

{}

"Or" operator

||

Bitwise Not operator

~

GridBagLayout

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

Preincrement

++counter

Event Adapters

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

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

abstract window toolkit

ABT

Define the keyword "protected"

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

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

Protected

Accessible if in same package.

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

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

What does API stand for?

An application-programming interface (API) is a set of programming instructions and standards for accessing a Web-based software application or Web tool

asterisk (*)

An arithmetic operator that performs multiplication.

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.

unchecked exception

An error that will not be resolved in the program.

What is a Collection?

an object that stores multiple elements in a single unit

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

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)

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

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

What is constructor?

Constructor is just like a method that is used to initialize the state of an object. It is invoked at the time of object creation.

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

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

The condition Exp1 ^ exp2 evaluates to true when ____.

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

What does the method .clone do from the class object?

It throws an exception which must be caught.

short s = (short)9; int i = 8; s+=i; Will this compile,if so what is the output?

It will compile because += and other operators like that do a cast. So s+=i; is s = (short)(s+i);

What happens if their is no break in a switch statement?

It will continue down the case statements until a break is found.

When an argument is passed to a method,

Its value is copied into the method's parameter variable

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

JColorChooser

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

JTextArea

________is interpreted.

Java

Which are valid array declarations? 1// arr[] int; 2// arr[] arr1; 3//arr[][5] arr2; 4//arr[][] arr4 = new arr[][];

Line 2, array declarations are not initialized yet.

Event Listeners (Observer?)

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

How many types of memory areas are allocated by JVM?

Many types: Class(Method) Area, Heap, Stack, Program Counter Register, Native Method Stack

The ________ method returns a raised to the power of b.

Math.pow(a, b)

Since you cannot take the square root of a negative number, you might use which of the following instructions to find the square root of the variable x?

Math.sqrt(Math.abs(x));

gigabyte

Maximum memory size is 2^30 memory bytes

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

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.

Suite of tests

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

What gives Java its 'write once and run anywhere' nature?

The bytecode. Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform.

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.

What is classloader?

The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.

class declaration

The code that defines a class, beginning with the class keyword.

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

If a parent throws an exception what must its child constructor do?

Throw that exception or a subclass of it or don't throw anything at all.

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java in case of class.

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

what does a finally block do?

a finally block is run after a try catch even if the try block caught an exception - used to execute code even if an exception is thrown

What is an arrayList

a inherently ordered dynamic data structure that implements the List interface and extends AbstractList

What are the steps involved for making a connection with a database or how do you connect to a database?

a) Loading the driver : To load the driver, Class. forName() method is used. Class. forName("sun. jdbc. odbc. JdbcOdbcDriver"); When the driver is loaded, it registers itself with the java. sql. DriverManager class as an available database driver. b) Making a connection with database: To open a connection to a given database, DriverManager. getConnection() method is used. Connection con = DriverManager. getConnection ("jdbc:odbc:somedb", "user", "password"); c) Executing SQL statements : To execute a SQL query, java. sql. statements class is used. createStatement() method of Connection to obtain a new Statement object. Statement stmt = con. createStatement(); A query that returns data can be executed using the executeQuery() method of Statement. This method executes the statement and returns a java. sql. ResultSet that encapsulates the retrieved data: ResultSet rs = stmt. executeQuery("SELECT * FROM some table"); d) Process the results : ResultSet returns one row at a time. Next() method of ResultSet object can be called to move to the next row. The getString() and getObject() methods are used for retrieving column values: while(rs. next()) { String event = rs. getString("event"); Object count = (Integer) rs. getObject("count");

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.

The expressions that are passed to a method in an invocation are called

actual parameters

actual parameter

actual value or reference that is passed to a method or subroutine -> gary.transfer(200); 200 is the actual parameter

transistor

an electrical switch with no moving parts

Comments should

be insightful and explain what the instruction's intention is

CH11: Abstract classes cannot _______.

be instantiated

bit

binary digit; smallest unit of information, either 0 or 1; n bits has 2^n possible values

CH11: Fields in an interface are ________.

both final and static

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

call stack

this.method()

calls an instance method in the current class.

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

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

Of the following types, which one cannot store a numeric value? 1) int 2) byte 3) float 4) char 5) all of these can store numeric values

char

precondition assertion

checks for a condition that must be true before a method is executed

Write a class and write a tester for that class

class Dog { int size; String breed; String name; void bark() { System.out.println("ruff! Ruff!"); } } 2) write the tester (TestDrive) class class DogTestDrive { public static void main (String [] args) { Dog d=new Dog(); d.size=40; d.bark(); } }

Class

class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions, methods).

array

collection of data values of the same type; reference data type

orphaned data

data that isn't referenced anywhere

Using getCurrencyInstance( ) formats a variable, automatically inserting

decimal point for cents dollar sign percent sign

public

declares the function can be called outside of the class

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

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.

To use JOptionPane in your program, you may import it using:

import javax.swing.JOptionPane; import javax.swing.*;

quick sort

in-place, divide-and-conquer, massively recursive sort; array is split in two parts based on a pivot point (one with elements larger than the pivot, one with elements smaller than the pivot) and is recursively repeated

exception

indication that abnormal situation occurred

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.

The advantages of the DecimalFormat class compared with the NumberFormat class include

only precise control over the number of digits to be displayed and control over the presence of a leading zero

abstract method

only the method header but no body

boolean operator

operator that can be applied to boolean values: &&, ||, !

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

If a method has a public access modifier and a subclass overrides that method, what must its access modifier be?

public. If it where default it could be either public or protected.

What is a try/catch?

put in spots where uncheck exception may accure to catch the excception if it dose occur

Object

refers to a particular class

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.

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.

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

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)

truth table

table used in logic to compute the functional values of logical expressions; this table has input columns that list all combination of true/false values and the corresponding outputs for those

You cannot declare the same ____ name more than once within a block, even if a block contains other blocks.

variable

Method parameter

variable input to method

static

variable or function is shared between all instances

For overriding a method in an interface that throws an exception of type IOException what must that method declaration be? Lets say that method was void m1() throws IOException

void m1() void m1() throws IOException void m1() throws FileNotFoundException

What are aggregate operations?

where the values are grouped together as input on certain criteria to form a single value of more significant meaning

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)

To add a value 1 to variable x, you write (Choose all that apply.) 1) 1 + x = x; 2) x += 1; 3) x := 1; 4) x = x + 1; 5) x = 1 + x;

x += 1; x = x + 1; x = 1 + x;

To assign a double variable d to a float variable x, you write

x = (float)d;

Which of the following would return the last character of the String x? 1) x.charAt(0); 2) x.charAt(last); 3) x.charAt(length(x)); 4) x.charAt(x.length( )-1); 5) x.charAt(x.length( ));

x.charAt(x.length( )-1);

The String class' compareTo method

yields 0 if the two strings are identical

APPLET

A small application that is loaded with an HTML page from a Web server that runs on the client computer.

Components of a color

9. RGB values specify the ____.

block

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

logic error

An error that does not prevent your application from compiling successfully but does cause your application to produce erroneous results.

syntax error

An error that occurs when code violates the grammatical rules of a programming language.

________ are instructions to the computer.

Software Programs

javac command

The command that compiles a source code file (.java) into a . class file.

If class B has variable v and class A does to, what happens? A a = new B(); a.v();

The variable of the reference type will be called even if it overriden.

int value

The variable type that stores integer values.

Escape Character

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

Which of the following is true regarding Java syntax and semantics? 1) a Java compiler can determine if you have followed proper syntax but not proper semantics 2) a Java compiler can determine if you have followed proper semantics but not proper syntax 3) a Java compiler can determine if you have followed both proper syntax and semantics 4) a Java compiler cannot determine if you have followed either proper syntax or semantics 5) a Java compiler can determine if you have followed proper syntax and can determine if you have followed proper semantics if you follow the Java naming convention rules

a Java compiler can determine if you have followed proper syntax but not proper semantics

Iterator

an iterator is an object that visits each element in a collection once - order off iteration is not guaranteed (every type in the Collections Framework has an iterator)

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.

To improve readability and maintainability, you should declare ________ instead of using literal values such as 3.14159.

constants

When you write an explicit ____ for a class, you no longer receive the automatically written version.

constructor

Method

contains a collection of programming instructions that describe how to carry out a particular task; consists of a sequence of instructions that can access the internal data of an object

Memory Data Registrar (MDR)

contains the data value being fetched or stored

nested conditional

control statement within another control statement

Postincrement

counter++

Postdecrement

counter--

In Java, "instantiation" means

creating a new object of the class

Abstract keyword

denotes a class that cannot be instantiated and provides no implemntation for its member methods and fields - used to define certain behaviors and properties of subclasses

JOptionPane is a class that provides GUI

dialog boxes

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

time complexity

quantifies the amount of time taken by an algorithm to run; commonly expressed using big O notation

Collection

represents a group of objects

construction phase

satisfy the structural constraint (numbers places in heap); satisfy the value relationship constraint (start w/ last parent node)

What is scope?

scope is the concept of the access granted to a variable depending on where it is seen. class level variables can be 'seen' or accessed anywhere within their given class whereas variables declared in the body of a method cannot be accessed from other methods in the same class.

CH13: This method is inherited from JComponent and changes the appearance of a component's text.

setFont

CH13: You use this method to place a menu bar on a JFrame.

setJMenuBar

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

Given the following assignment statement, which of the following answers is true regarding the order that the operators will be applied based on operator precedence? a = (b + c) * d / e - f;

+, *, /, -

How do you pass data (including JavaBeans) to a JSP from a servlet?

- (1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either "include" or forward") can be called. This bean will disappear after processing this request has been completed. Servlet: request. setAttribute("theBean", myBean); RequestDispatcher rd = getServletContext(). getRequestDispatcher("thepage. jsp"); rd. forward(request, response); JSP PAGE:<jsp: useBean id="theBean" scope="request" class=". . . . . " />(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it. Servlet: HttpSession session = request. getSession(true); session. putValue("theBean", myBean); /* You can do a request dispatcher here, or just let the bean be visible on the next request */ JSP Page:<jsp:useBean id="theBean" scope="session" class=". . . " /> 3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it. Servlet: GetServletContext(). setAttribute("theBean", myBean); JSP PAGE:<jsp:useBean id="theBean" scope="application" class=". . . " />

What is a package?

- A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.

loosly coupled

- system is one in which each of its components has, or makes use of, little or no knowledge of the definitions of other separate components

What is the value of (double)(5/2)?

2.0

End of a statement

;

What level of access to the properties and methods of the enclosing class does a static nested class have?

A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

binary

A string of bits, Base 2.

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.

Merge Symbol

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

Counter-Controlled Repetition (Definite Repetition)

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

primitive type

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

Difference between while loop and do/while loop?

A while loop runs as long as its given condition is true - do/while loops at least once and the until the condition is false

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

BoxLayout

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

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.

How many constructors can a class have? 1. Any number 2. 0 3. 1 4. 2

Any number

All @param tags in a method's documentation comment must

Appear after the general description of the method

logical operator

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

What is the difference between an array and an array list?

Array lists can only store objects while arrays can store objects or primitives. Arrays have a fixed size while arraylists can change size.

Types of Queues

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

Types of Lists

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

What is a static nested class?

As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.

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

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

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

Attributes (ANT)

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

Working directory

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

What is the instanceof operator?

Checks if one objects is a instance of another.

print

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.

run

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

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.

Local variables (field)

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

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

Definite repetition

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

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

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

Diamonds

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.

The following code fragment reads in two numbers: (Choose all that apply.) Scanner input = new Scanner(System.in); int i = input.nextInt(); double d = input.nextDouble(); What are the correct ways to enter these two numbers?

Enter an integer, a space, a double value, and then the Enter key. Enter an integer, two spaces, a double value, and then the Enter key. Enter an integer, an Enter key, a double value, and then the Enter key.

When is an instance block executed?

Every Time an instance of the class it was created is made. Before the constructor.

Which of the following statements is correct? 1) Every line in a program must end with a semicolon. 2) Every statement in a program must end with a semicolon. 3) Every comment line must end with a semicolon. 4) Every method must end with a semicolon. 5) Every class must end with a semicolon.

Every statement in a program must end with a semicolon.

DASD

Every unit of information has a unique address but the time needed to access the information depends on its physical location and the current state of the device. Stands for direct access storage device.

what is an abstract base class?

an abstract base class differs from a base class in that it cannot be instantiated - only used to enforce certain fields and methods

class

template for instantiating objects; dictates what an object can or cannot do; defines the properties and behaviors for an object

break statement

terminates switch statement; causes execution to continue from the statement following the switch statement

pretest loop

test is done before the execution of the loop body

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.

For a computer to communicate over the Internet, it must use

the combined TCP/IP protocol

What is the default constructor?

the constructor the exist if none is created. the defualt constructor is empty

StringTokenizer is a class in the java.util library that can divide a String based on some delimiter String (a delimiter is a separator). If the instruction StringTokener st = new StringTokenizer(str, "&&"); is executed, where str is some String, then st divides up str into separate Strings whenever

two ampersands are found

An "alias" is when

two different reference variables refer to the same physical object

bubble sort

type of exchange sort; compare the first pair of elements(exchange if needed), compare the second pair, third, fourth, and so on until the end of the list; highest number guaranteed to be in the last place after first sort

Long

unsigned long

sort-in-place

use same same amount of memory space when sorted

What does the throws keyword mean?

used to create a exception object

Define the keyword "extends"

used to create a subclass for an existing class.

class data value

used to represent information shared by all instances or to represent collective information about instances

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

...

explicit parameter

a parameter of a method other than the object on which the method is invoked. The parameter explicitly fed to a method through the parenthesis.

interface (in Java)

a type with no instance variables, only abstract methods and constants

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

Which of the following expressions will yield 0.5? (Choose all that apply.) 1) 1 / 2 2) 1.0 / 2 3) (double) (1 / 2) 4) (double) 1 / 2 5) 1 / 2.0

1.0 / 2 (double) 1 / 2 1 / 2.0

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

char

16 bit unicode character

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 }

A color image is broken down into individual pixels (points), each of which is represented by

3 values denoting the intensity of red, green, and blue in the image

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

identifier

A series of characters consisting of letters, digits and underscores used to *name classes and GUI components*.

body

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

single-selection statement

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

git push

Publishes committed local files to remote repo.

stored program concept

instructions to be executed by the computer are represented as binary values and stored in memory

You can create an array of three integers by writing :

int ar[] = new int[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 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 does it take to create and use and object?

- 2 classes. 1 class for the type of object (Dog, ClarmClock,Television) and another class to test your new class -the tester class is where you put the pain method and in that main() method you create access object of your new class type. -the test has 1 job: try out the methods and vairables of your new object class type

double precision

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

What is the difference between a class and an object

A class is a blueprint for an object. tells the virtual machine how to make an object. you might use a button class to make dozens of different buttons, each button might have its own color, size, shape, label,

Explain a class for an alarm clock

Alarm object have an instance variable to hold the alarmTime, and two methods for getting and setting the alarmTime

CH13: To display a scroll bar with a JList component, you must _________.

add the JList component to a JScrollPane component

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

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

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

throws clause`

Describe how to work with objects and variables

to work with objects, you first construct them and specify their initial state. Then you apply the methods to objects

CH12: You can think of this code as being "protected" because the application will not halt if it throws an exception.

try block

CH13: A list selection listener must have this method.

valueChanged

boolean expression

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

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

NumberFormatException

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

Object

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

Protected

mantissa

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

how to pass an object to a method

System.out.println(new Date()):

termination condition

The condition that stops the loop.

instance of a class

When you construct an object from a class ex Dog jasmine=new Dog();

overflow error

When you try to strore a value whose magnitude is too big an int variable.

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

checked exceptions

What is a constructor

constructors always have the same name as the class name. The constructor for the Date class is called Date.. to construct a Date object, you combine the constructor with the "new" operator as follows: new Date() -this expression constructs a new object.

CH12: If your code does not handle an exception when it is thrown, it is dealth with by this.

default exception handler

CH11: This operator can be used to determine whether a reference variable references an object of a particular class.

instanceof

what is the objects state

its how the object reacts when you invoke those methods


Set pelajaran terkait

Databricks - Data Engineer Associate Practice Exam 2

View Set

International Management Module 2

View Set

ECON 3900 Practice Questions Chapter 11 "Aggregate Demand: Part II"

View Set

Literary Terms antithesis - cacophony

View Set

Chapter 8: communicating digital content

View Set

[1S-MIDTERMS] General Physics 1 - Module 1

View Set

First Astronomy Exam Smart Work Answers

View Set