JAVA FINAL 7

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

Call

...

byte

8 bits

int

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

What is the difference between = and ==?

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

applet

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

import

Enables the programmer to abbreviate the names of classes defined in a package.

Staging area

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

continue

Forces the abrupt end of the current loop iteration and begins another iteration.

Java Development Kit (JDK)

Java compiler and interpreter. includes JRE and JSE API

JTextField

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

CH12: FileNotFoundException inherits from ________.

IOException

InterruptedIOException is a subclass of?

IOException

JOptionPane.ERROR_MESSAGE

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

Church-Turing Thesis

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

Impliciete cast

Java neemt de waarde van een variabele van het beperktere type en stopt deze waarde in een ander variabele met een type met meer opslag mogelijkheden.

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

JCheckBox Text

Mocking

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

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

No

Can you override Strings methods if yes why?

No because String is a final class.

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.

Which class is the superclass for every class.

Object class.

Executable

Pseudocode usually only describes ____ lines of code.

assert

Tests the truth of a condition that the programmer believes is true.

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

That classes toString.

Instantiation

The act of creating a new instance of an object.

Class

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

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

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

keyPressed event

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

control unit

a subsystem of the processor that can 1. fetch next instructions 2. decode them 3. execute them

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

An ___ is a container object that holds a fixed number of values of a single type.

array

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

bert

Console Applications

character output to a computer screen in a DOS window

Machine Language

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

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

class

CH12: If your code does not handle an exception when it is thrown, it is dealth with by this.

default exception handler

Access Modifier

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

Class Definition

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

packages

how are classes grouped in java?

Standard Output Device

normally the monitor

logic gate

performs a logical operation on one or more logic inputs and produces a single logic output

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.

Inheritance

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

Syntax

the rules of the language

You cannot declare the same ____ name more than once within a block, even if a block contains other blocks.

variable

local variable

variable whose scope is a block

Object Oriented

you can define objects using the Class construct. Example: JAVA, C++

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

!bert!

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

"!" logical complement operator

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.

while

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

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.

Can we execute a program without main() method?

Yes, one of the way is static block

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

Yes.

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

Yes.

GIT

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

Local Repository

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

What are Predefined variables or implicit objects?

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

Java

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

Queues

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

Lists

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

data access class

...

Version control principles

1. The Lock 2. The Merge

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

Print

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

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

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

state button

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

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

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

What is this automatically? 45e7

A double

Infinite Loop

A logical error in which a repetition statement never terminates.

Refactor - encapsulate collection

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

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

byte

8 bit, useful if memory an issue

Stop

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

setHorizontalAlignment

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

Comment

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

Type parameter

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

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

A boolean value

Abstract method

Een method dat niet uitgevoerd kan worden.

Entry

Een object in een LinkedList

Attributes (ANT)

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

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

application

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

multiline statement

A statement that is spread over multiple lines of code for readability.

double-selection statement

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

Register

A storage cell that holds the outcome of an arithmetic operation

Merge Symbol

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

white space

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

Counter-Controlled Repetition (Definite Repetition)

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

statement

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

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.

Constant

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

constant

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

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

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

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

Public

Accessible by all.

Protected

Accessible if in same package.

Can we treat all types of exceptions the same?

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

"enum" type

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

exception

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

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.

syntax error

An error that occurs when code violates the grammatical rules of a programming language.

unchecked exception

An error that will not be resolved in the program.

left operand

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

variable

An identifier that represents a location in memory.

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)

Which access modifiers can be applied to constructors?

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

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

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.

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

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

selected

Defines if a component has been selected. (property)

Statement (JDBC)

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

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

Definite repetition

What happens when you divide 0 by 0?

Exception

If Integer xx = 10 and Integer yy = 10, is this true or false? xx==yy?

False

git init

Initialise an empty repository

What is static block?

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

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

It cannot be overloaded.

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

It throws an exception which must be caught.

Public

Kan door de buitenwereld worden aangeroepen.

Private

Kan niet door de buitenwereld worden aangeroepen

synchronized

Keeps two threads from interfering with one another.

final

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

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.

How many types of memory areas are allocated by JVM?

Many types: Class(Method) Area, Heap, Stack, Program Counter Register, Native Method Stack

gigabyte

Maximum memory size is 2^30 memory bytes

immutable

Means that once created, their values cannot be changed.

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

Merge

What does String Buffer extend?

Object

Can we override static method?

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

Does each source file need a public class in it?

No.

Does Java have multiple inheritance?*

No. Instead deal with interfaces.

font property

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

background property

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

size property

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

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

setEditable

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

Logical AND and Logical OR

Since && and || each have two operands, there are four possible combinations of conditions a and b

isSelected

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

statement

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution.

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.

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

Some String Methods

String name1 = new String("Steve Jobs"); int numChars = name1.length(); char c = name1.charAt(2); String name2 = name1.replace('e', 'x'); String name3 = name1.substring(1, 7); String name5 = name1.toLowerCase();

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

-- (unary decrement operator)

Subtracts one from an integer variable.

Properties rule (subtypes)

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

Example of the Dot Operator in Use

System.out.println revisited There is a class called System, which contains an object reference variable out as one of its instance variables The object referenced by out has a method called println

2

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

semicolon ( ; )

The character used to indicate the end of a Java statement.

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

binary

base 2 positional numbering system composed of 1s and 0s

What is object cloning?

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

"private" modifier

The private modifier specifies that the member can only be accessed in its own class.

short-cut evalulation

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

Architecturally Neutral

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

object reference

memory location of an object

Debugging

The process of finding and correcting errors in a program

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.

bounds property

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

icon property

The property that specifies the file name of the image displayed in a JLabel.

Things an object can do are called?

methods

Where is a software object's behavior exposed?

methods (Java) or functions (C++)

program control

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

setText

The text on a JLabel is specified with _____.

JCheckBox text

The text that appears alongside a JCheckBox.

Sequence, selection and repetition

The three types of program control are _____.

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.

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.

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

State

the values of the attributes of an object

von neumann architecture

theoretic model of computer design that structures the origin of all modern computers. four subsystems: memory, in/output, ALU, control unit.

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

writeObject

This method is used to write an object to the stream. Any object, including Strings and arrays, is written with this method. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.

notifyAll

This method wakes up ALL waiting threads; the scheduler decides which one will run

notify

This method wakes up a single thread which is waiting on the object's lock

multiplication operator

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

% (remainder operator)

This operator yields the remainder after division.

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.

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

public class Triangle extends Shape

code to make triangle subclass from Shape superclass

CH13: This is a key that activates a component just as if the user clicked it with the mouse.

mnemonic

Software

computer instructions or data. Anything that can be stored electronically

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

multiple interval selection mode

How do you find the length of a String?

Use the .length() method.

JDesktopPane

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

Indentifier

name of a program component such as a class, or variable

Variables

named computer memory locations that hold values that might vary

boolean operator

operator that can be applied to boolean values: &&, ||, !

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

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

package

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

parameter

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

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

private

Bytecode

programming statements that have been compiled in to binary ofrmat

Source Code

programming statements written in a high-level porgramming language

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

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

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

IS-A relationship

relationship to describe extends

HAS-A relationship

relationship to describe instance variables

syntax

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

JTextField.CENTER

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

Variables

Variables are memory locations use to store data. Methods maintained their own variables which are local to the methods

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

loop

sequence of instructions that is executed repeatedly

method

sequence of statements with a name. may have formal parameter and may return a value.

Program Statements

similar to English sentences; they carry out the tasks that programs perform

I/O buffer

small amount of memory inside the I/O controller

computability

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

cast

converting a value from one type to another explicitly

Postincrement

counter++

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.

CH11: This key word refers to an object's superclass.

super

CH11: In an inheritance relationship, this is the general class.

superclass

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

Java API

the application programming interface, a collectionof information about how to use every prewritten Java class

what is a subclass?

the descendant of a superclass

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

K&R Style

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

What is super()?

it calls the superclass constructor.

what is the objects state

its how the object reacts when you invoke those methods

Quick Check: Nested Statements

What output is produce by the following code fragment given the assumptions below?

round off errors

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

static method

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

What is a mutator?

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

Run-time errors (Error Type 2/3)

a problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally

Logical or semantic errors (Error Type 3/3)

a program may run, but produce incorrect results, perhaps using an incorrect formula

Computer program

a step by step set of instructions for a computer.

Procedural Programming

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

instance

an object of a particular class

JOptionPane

allows you to produce dialog boxes

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}

boolean expression

an expression that evaluates to either true or false

What is an object?

an instance of a class

object

an instance of a class

Boolean expression

any expression that evaluates to true or false

The last element in the array created by the statement int[] ar = { 1, 2, 3 }; is :

ar[2]

address

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

Long

unsigned long

String Concatenation

The string concatenation operator (the plus symbol) is used to append one string to the end of another. In the case of a long string, you must use concatenation to break it across multiple lines.

boolean

type with possible values of true of false

What does Javac do?

Compiles the program.

JLabel

Component that displays a text or an image that the user cannot modify

BoxLayout

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

Can a local variable be protected?

No

Can you have an array of objects?

Yes

Can you use short in a switch statement?

Yes

Do you have to initialize a local variable?

Yes

Is the String class final?

Yes

Compiler

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

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

Yes

single precision

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

Compiler

4. Syntax errors are found by the ____.

base or radix

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

Setter

Method om de waarde van een data-member in te stellen.

Another Example

Output A quote by Abraham Lincoln: Whatever you are, be a good one.

Java

oject oriented language

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.

Checkout

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

Generics

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

boolean

1 bit primitive that manipulates the two logic value T and F.

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

30

setIcon

4. Use ____ to specify the image to display on a JLabel.

Expression

A construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value.

bug

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

integer

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

method

An application segment containing statements that perform a task.

What is a field?

An instance variable

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)

run

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

git commit

Commits staged files to Repo.

final or user-defined constant

Constant, cannot be changed.

GUI

Graphical User Interface

Getter

Method om de waarde van een datamember op te halen.

Immutable

Niet te wijzigen

Operator && __.

Performs short-circuit evaluation

workflow

The activity of a portion of a software system.

Declare an array

int[] anArray;

Which of the following is NOT a modifier?

return

parameter passing

specifying expressions to be arguments for a method when it is called

Class

term that describes a group or collection of objects with common properties

instance variables and methods

what are members of a class?

Preincrement

++counter

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

int

32 bit

long

64 bit

By default what is this considered - 12.21?

A double.

String literal

A sequence of characters within double quotes.

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

Decimal, Text

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

Encapsulation

De buitenwereld heeft geen rechtstreekse controle over de inhoud.

class

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

JTextArea

Display textual data or accept large amounts of text input.

case sensitive

Distinguishes between uppercase and lowercase letters in code.

Data member

Eigenschap van een class

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

False

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

False

Dynamic binding

Het bepalen van de juiste versie gebeurd pas bij de uitvoering.

Type casting

Het type van een variabele omzetten in een andere type.

The body of a while statement executes _____.

If it's condition is true

void

Indicates that a method doesn't return a value.

Benefits of Encapsulation*

Maintainability, Flexibility and Extensibility.

How do you make a constant.

Make a variable with final and static modifiers.

Are arrays used only for primitives?

No

Integer.parseInt

Returns the integer equivalent of a String.

DecimalFormat

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

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;

The Dot Operator

The dot operator (.) gives you access to an object's instance variables (states) and methods (behaviors) It says: use the Dog object referenced by the variable myDog to invoke the bark() method Think of a Dog reference variable as a Dog remote control When you use the dot operator on an object reference variable, it is like pressing a button on the remote control for that object

What is the purpose of the Java garbage collection?

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

message dialog

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

class name

The identifier used as the name of a class.

A JCheckBox is selected when the isSelected method returns __.

True

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

True

primative types or built in type

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

White space

and combination of nonprinting characters

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

erto

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

for ( ; ; ) { //do something }

Character strings are represented by the class ___.

java.lang.String

Object-Oriented Programs

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

Internet Protocol

network layer in the Internet; the IP uses 32-bit addresses to identify different nodes.

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

never

New

new is a Java reserved word that triggers all kinds of actions. goes back to the heap (free memory space), reserves a chunk of the memory for the real value (address) Java actually invokes a special method called constructor, provided by programmer, which does the proper initialization new is the only thing that produces a reference type

The term "instance variable" is another name for...

non-static field - instance variables are specific to an object

Basic Enum class

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

List all the access modifiers in order from most visible to least?

public, protected, default, private.

Passing

sending arguments to a method

Mutator methods typically begin with the word "____".

set

Boolean

true or false

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.

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

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

final

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

What modifiers may be used with top-level class?

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

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.

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.

Predecrement

--counter

What is the primitive storage range of a byte?

-128 to 127

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.

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

...

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.

...

Element and index

...

What are 5 method of the class object.

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

short

16 bit, useful if memory an issue

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

2, 3

What is the length of TEXT?

4

end-of-line comment

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

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

String.valueOf

A method that converts a numeric value (such as an integer) into text.

identifier

A series of characters consisting of letters, digits and underscores used to *name classes and GUI components*.

nested statement

A statement that is placed inside another control statement.

What is an accessor?

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

event

An action that can trigger an event handler.

Where can an anonymous inner class be defined?

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

asterisk (*)

An arithmetic operator that performs multiplication.

StackTraceElement

An element in a stack trace, as returned by Throwable.getStackTrace(). Each element represents a single stack frame. All stack frames except for the one at the top of the stack represent a method invocation. The frame at the top of the stack represents the the execution point at which the stack trace was generated. Typically, this is the point at which the throwable corresponding to the stack trace was created.

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

CLOB

Character Large OBject

Generic collections

Collection waarbij de compiler controleert of de objecten die je in de collectie stopt van het juiste type zijn.

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

element

Each item in an array

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

Editable

Comparator class als inner class

Een Comparator class integreren in een andere class.

Hashtable

Een datastructuur waarbij sleutels worden geassocieerd met waardes die dan vervolgens worden gebruikt om het element in de tabel te plaatsen of op te zoeken.

Enumeration

Een datatype dat beschreven wordt adhv een geordende opsomming van waarden.

Generics

Een oplossing voor het probleem van typecasting bij Collections enMaps.

ArrayList

Een resizable array implementatie van de List interface.

What is final variable?

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

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

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

Double

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

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.

return

Ends execution of a method and possibly returns a value to the calling code.

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

ClassCastException

Error dat ontstaat bij verkeerde downcasting

Events

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

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

Exclamation point

comment (//)

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

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.

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

False

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

False

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

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

What is final class?

Final class can't be inherited.

What is final method?

Final methods can't be overriden.

What is the ONLY modifier local variables can use?

Final, anything else will be a compilation error.

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.

Dialog Box

GUI object resembling a window on which messages can placed

Windowed Application

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

Property

Gedrag van een class

Types of Maps

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

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

ImageIcon

volatile

Imposes strict rules on the use of a variable by more than one thread at a time.

Using Underscore Characters in Numeric Literals

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal.

boolean expression

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

Iteration

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

What b before calling method m1() that returns an int? int b = m1();

It is one

What is the keyword transient?

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

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

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

It will continue down the case statements until a break is found.

iterator()

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

When an argument is passed to a method,

Its value is copied into the method's parameter variable

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

JColorChooser

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

JFileChooser

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

JMenuItem

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

JTextArea

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

JTextArea

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

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

!bert

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 Java Bean?

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

JSE API

Java Standard Edition Application Programming Interface Libraries

What is the JVM?

Java Virtual Machine.

break

Jumps out of a loop or switch.

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.

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.

*decision*

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

initialization value

The beginning value of a variable.

{}

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

multiple instances

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

char

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

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.

class declaration

The code that defines a class, beginning with the class keyword.

Properties

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

Finalize

Method dat door de garbage collector wordt aangeroepen net voor het object wordt opgeruimd.

What are the two things classes have?

Methods and Variables.

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

What happens when you divide 0.0 by 0.0 or 0?

NaN(Not a Number)

identifier

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

extends keyword

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

class keyword

The keyword used to begin a class declaration.

String Concatenation Operator

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

Which of the following statements is NOT true?

The operator new must always be used to allocate space of a specific type, regardless of the type.

Conditional Statements

The order of statement execution is called the flow of control A conditional statement lets us choose which statement will be executed next The Java conditional statements are the: -if and if-else statement -switch statement

value of a variable

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

content pane

The portion of a JFrame that contains the GUI components.

Sequential

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

Functional decomposition is

The process of breaking a problem down into smaller pieces.

horizontalAlignment property

The property that specifies the text alignment in a JTextField (JTextField.LEFT, JTextField.CENTER, or JTextField.RIGHT).

text property

The property that specifies the text displayed by a JLabel.

.java file

The type of file in which programmers write the Java code for an application.

When designing a class what should you think about

Think about things the object does , and things the object does

Escape Character

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

ThreadGroup

This class represents a set of threads.

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

Value-returning

This type of method method performs a task and sends a value back to the code that called it. A. Local B. Void C. Complex D. Value-returning

Value-returning

argument

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

parameter

Variable passed to a method that provides more information for the method.

Static

Niet specifiek per object, maar gedeeld door alle instanties van de class.

Can You use float in a switch statement?

No

Can a byte be set to an int variable?

No

Can a class be private?

No

Can a local variable be static?

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

Can you use continue in a switch?

No

Can you use long in a switch statement?

No

Does the StringBuilder class override the equals method in object?

No

Is it legal to use .super in static methods?

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

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 a private method be overridden?

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

Can a member variable be declared synchronized?

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

Can you statically import a package?

No, you can only import classes statically.

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

No.

Can a constructor have a synchronized modifier?

No; they can never be synchronized.

A class in the Java API

What is an ArrayList?

Java libraries

What is the Java API?

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)

instance of a class

When you construct an object from a class ex Dog jasmine=new Dog();

declaring

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

overflow error

When you try to strore a value whose magnitude is too big an int variable.

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

While

How is an instance block wrote?

With two brackets outside of the main method.

reserved words or keywords

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

Main class

Wordt uitgevoerd bij het opstarten van de applicatie.

What are Wrapper classes?

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

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.

Can you declare the main method as final?

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

Can we override the overloaded method?

Yes.

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

Yes.

output JTextField

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

bit

a binary digit that is the smallest unit of information. 1 or 0.

truth table

a breakdown of logic functions by listing all possible values

Class

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

Single Responsibility Principle

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

true

a class that has even one abstract method must be marked as an abstract class

Mutator method

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

What is wrong with the following interface? public interface SomethingIsWrong { void aMethod(int aValue){ System.out.println("Hi Mom"); } }

aMethod() should not have a method body. Remove the {Sytem.out.println("Hi Mom");} to fix it.

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)

Polymorphism

an object can take on multiple types, therefore having the capacity to be referred to in multiple ways

initialize

assigning a value to a variable when it's created

binary

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

CH11: Abstract classes cannot _______.

be instantiated

CH11: Fields in an interface are ________.

both final and static

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

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

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

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

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

checked exceptions

Consider the following code snippet. arrayOfInts[j] > arrayOfInts[j+1] Which operators does the code contain?

comparative operator "greater than" > arithmetic operator "plus" +

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

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

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

do while end

Enum

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

import java.util import javax.swing

example java api package imports

indexOf() size()

find out where something is in ArrayList get number of elements in ArrayList

CH11: This operator can be used to determine whether a reference variable references an object of a particular class.

instanceof

Objects

instances of a class that are made up of attributes and methods

machine language

instructions that can be executed directly by the CPU

stored program concept

instructions to be executed by the computer are represented as binary values and stored in memory

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

local variable

is a variable that is declared in the body of a method

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

variables declared inside a method or method parameter

local variables

run()

main method for an individual thread

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.

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

Accessor method

method that accesses an object and returns some information about it, without changing the object

mutator method

method that changes the state of an object

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is a valid call to the method above?

minimum(5, 4);

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is a valid call to the method above?

minimum(5, 4);

What's wrong with the following program? public class SomethingIsWrong { public static void main(String[] args) { Rectangle myRect; myRect.width = 40; myRect.height = 50; System.out.println("myRect's area is " + myRect.area()); } }

myRect is declared, but it is not instantiated or initialized. area() is not a method of Rectangle. getArea() is the public method.

Thread Life Cycle

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

Program Comments

nonexecuting statements that are added to code for the purpose of documentation

mass storage

nonvolatile storage, information can be saved between shutdowns. The storage of large amounts of data in a persisting and machine-readable fashion.

an instance is another way of saying ____?

object

Private

only accessible if in same class.

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.

Copy Constructor

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

the entry point for your application

public static void main(String [] args)

Variables in interfaces are declared what automatically?

public, static and final.

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.

overriding a method

redefining a method in a subclass

Inheritance gives your programs the ability to express _______________ between classes. 1. encapsulation 2. relationships 3. composition 4. dependencies

relationships

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

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

Program

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

How does a program destroy an object that it creates?

set the value to null

Procedures

sets of operations performed by a computer program

I/O buffer

small amount of memory that the I/O controller has

I/O controller

special purpose computer that handles details of input and output and compensates for speed difference between I/O devices and other parts of the computer.

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

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

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: The following is an explicit call to the superclass's default constructor.

super();

subclass extends the superclass

superclass / subclass relationship in java

The ___ statement allows for any number of possible execution paths.

switch

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

Mocks

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

Attributes

the characters that define an object as part of a class

Method Body

the code held bw the curly braces following the method

Compile-time or syntax errors (Error Type 1/3)

the compiler will find syntax errors and other basic problems

portability

the computer program is independent of the details of each particular computer's machine language because each compiler takes care of the translation

implicit parameter

the object on which a method is invoked

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

throws clause`

Variable Assignment

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

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

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

tool tip

primitive data type

total of 8, include 4 integer types and 2 floating point types. int 4, byte 1, short 2, long 8, double 8, float 4, char 2, boolean 1 bit. A value that's not a reference to an object.

on the stack inside the frame corresponding to the method where the methods were declared

where do all local variables live?

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

while (true) { //do something }

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.

Low-Level Programming Language

written to correspond closely to a computer processor's circuitry, a programming language that a computer can interpret quickly but that bears little resemblance to human language.

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is NOT visible in method two?

x (variable in block three)

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int z = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is NOT visible in method two? 1. x (variable in main block) 2. w (before method two) 3. rate (before main) 4. one (method name)

x (variable in main block)

compound assignments

x+=1

What is the last value that is sent to standard out for x in the given code segment? int x=0; do{ x=x+2; System.out.println("x: " + x); }while(--x<5);

x: 6 The do while statement will increment x by 2 each time through the loop, and then, before it checks the while condition, it will first decrement it by 1.

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}

Program development Cycle

• Design a solution to a problem (design a program) • implement the solution (code the program ) • Test the solution (test the program) • Fix the solution (debug the program)

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

Atomic Swing Components

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

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

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

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

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

Pass by reference

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

Synchronization

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

What is the difference between process and thread?

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

Benefits of Refactoring

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

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

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

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

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.

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.

Benefits of Continuous Integration

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

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.

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

___________________ is one of the primary mechanisms that we use to understand the natural world around us. Starting as infants we begin to recognize the difference between categories like food, toys, pets, and people. As we mature, we learn to divide these general categories or classes into subcategories like siblings and parents, vegetables and dessert. 1. classification 2. encapsulation 3. specialization 4. generalization

1. classification

A(n) ____ method is a method that creates and initializes objects. 1. constructor 2. non-static 3. instance 4. accessor

1. constructor

You can use ____ arguments to initialize field values, but you can also use arguments for any other purpose. 1. constructor 2. field 3. data 4. object

1. constructor

The inside block, which is contained entirely within an outside block, is referred to as ____. 1. nested 2. out of scope 3. ambiguous 4. a reference

1. nested

Which of the following lines of code explicitly calls the toString() method, assuming that pete is an initialized Student object variable? 1. println(pete.toString()); 2. println("" + pete); 3. println(super.toString()); 4. println(pete)

1. println(pete.toString());

Picture elements

10. Pixels are ____.

char[][] array1 = new char[15][10]; What is the value of array1.length? 1. 15 2. 0 3. 2 4. 10

15

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

18.0

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

/

2. The ________ operator performs division.

Which of the following statements is NOT true? 1. Reference variables contain the address of the memory space where the data is stored. 2. The operator new must always be used to allocate space of a specific type, regardless of the type. 3. Reference variables do not directly contain the data. 4. A String variable is actually a reference variable of the type String.

2. The operator new must always be used to allocate space of a specific type, regardless of the type.

int[] x = new int[10]; x[0] = 34; x[1] = 88; println(x[0] + " " + x[1] + " " + x[10]); What is the output of the code fragment above? 1. 34 88 88 2. This program throws an exception. 3. 34 88 0 4. 0 34 88

2. This program throws an exception.

Javac

2. To compile an application, type the command ____ followed by the name of the file.

Primitive

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

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int x = 0; for (int e : a) x += a; 1. Sums all the elements in a. 2. Will not compile (syntax error) 3. Finds the largest value in e. 4. Counts each element in a.

2. Will not compile (syntax error)

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.

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.

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

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

In straight-line form

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

KeyPressed

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

Byte

8 bits. smallest unit of storage in memory

Components of a color

9. RGB values specify the ____.

reading a file

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

difference between Static and non Static

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

What file is created after a program is created?

A .class file.

comment

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

Transfer of control

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

double precision

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

Charachters

A char variable stores a single character (16 bits) Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' Example of declarations with initialization: char topGrade = 'A'; char terminator = ';', separator = ' '; Note the difference between a primitive character variable, which holds only one character (enclosed by single quotes), and a String object, which can hold multiple characters (enclosed by double quotes)

newline

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

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,

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.

BufferedReader

A class. Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

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.

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

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

JTextField component

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

JButton component

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

JLabel component

A component used to describe another component. This helps users understand a component's purpose.

DataSource

A factory for connections to the physical data source that this DataSource object represents.

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.

block

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

block

A group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.

statements

A line of java code.

Header

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

OR operator (||)

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

AND operator (&&)

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

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

A marker interface includes no methods or fields.

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 - replace error code with exception

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

getText

A method that accesses (or gets) the text property of a component such as a JLabel, JTextField or a JButton.

Append

A method that adds text to a JTextArea component.

Double.parseDouble

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

String.equals

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

accessor method

A method that gets the value of an instance variable without altering the state of the variable/object.

Constructor

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

setText

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

control

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

this

A self-reference — refers to the object in which the word this appears.

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

single-selection statement

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

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.

empty string ("")

A string that does not contain any characters.

book-title capitalization

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

Class

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

Object Reference

A value that denotes the location of an objection in memory. A variable whose type is a class contains a reference to an object of that class

True and False

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

Counter

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

Print

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

field

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

primitive type

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

keyword

A word that is reserved by Java. These words cannot be used as identifiers. Also called *reserved word*.

reserved word

A word that is reserved for use by Java and cannot be used to create your own identifiers. Also called *keyword*.

Algorithm

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

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

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.

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

Expliciete cast

Actie van een programmeur om een variabele te converteren naar een beperktere type.

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

Actually a reference to the object that is passed

When an object, such as a String, is passed as an argument, it is A. Passed by value like any other parameter value B. Actually a reference to the object that is passed C. Encrypted D. Necessary to know exactly how long the string is when writing the program

Actually a reference to the object that is passed

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

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

Three

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

What access control applies to interfaces?

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

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

Protected

Alleen toegankelijk binnen de class zelf en binnen de kinderen of kleine kleinkinderen van die class.

dot separator

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

ASCII

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

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

forward slash (/)

An arithmetic operator that indicates division.

Declaration with Initialization

An assignment statement changes the value of a variable The assignment operator is the = sign If you wrote keys = 80; The 88 would be overwritten You should assign a value to a variable that is consistent with the variable's declared type

The if-else Statement

An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both

declaration

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

logic error

An error that does not prevent your application from compiling successfully but does cause your application to produce erroneous results.

checked exception

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

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

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

Any number

argument

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

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.

Parameters

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

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

Assertions

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

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.

The last element in the array created by the statement int[] ar = { 1, 2, 3 }; is : A. ar[3] B. ar[2] C. ar(3) D. ar(2)

B. ar[2]

If you pass the first element of the array ar to the method x() like this, x(ar[0]); the element ar[0] : A. will be changed by the method x() B. cannot be changed by the method x() C. may be changed by the method x(), but not necessarily D. None of these

B. cannot be changed by the method x()

Thread safe

Beveiligd tegen ongewenste effecten van asynchrone bewerkingen.

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

Boolean logic

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

Consider the following declaration. Scanner cin = new Scanner(System.in); int[] beta = new int[3]; int j; Which of the following input statements correctly input values into beta? (i) beta[0] = cin.nextInt(); beta[1] = cin.nextInt(); beta[2] = cin.nextInt(); (ii) for (j = 0; j < 3; j++) beta[j] = cin.nextInt();

Both (i) and (ii)

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

Both are false.

Casting Conversion

Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value being converted double money = 84.69; int dollars =(int) money; // dollars = 84

Does Java support multiple inheritance?

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

You can create an array of three doubles by writing : A. double ar[] = 3; B. double ar[3]; C. double ar[] = { 1.1, 2.2, 3.3 }; D. double[] ar = double(3);

C. double ar[] = { 1.1, 2.2, 3.3 };

Which of the following methods returns an array ? A. int acpy(int n) { ... } B. int acpy(int[] n) { ... } C. int[] acpy(int n) { ... } D. None of these

C. int[] acpy(int n) { ... }

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

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

do

Causes the computer to repeat some statements over and over again (for instance, as long as the computer keeps getting unacceptable results).

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.

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.

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.

declaration

Code that specifies the name and type of a variable.

Checked collecties

Collecties waarvan at runtime gecontroleerd wordt of je er elementen van het juiste type in stopt.

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

signature

Combination of identifiers, return value, name and parameters of a method. Example: public int calculateMonth(String name)

compound boolean expressions

Combination of two conditionals that evaluate to true or false.

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

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

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)

GridBagLayout

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

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

Counter

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x++; System.out.println(x); 1. Sums the even elements in a. 2. Finds the largest value in a. 3. Counts the even elements in a. 4. Finds the smallest value in a.

Counts the even elements in a.

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x++; System.out.println(x); 1. Sums the even elements in a. 2. Counts the even elements in a. 3. Finds the smallest value in a. 4. Finds the largest value in a.

Counts the even elements in a.

Suppose we have these two array definitions in main(): String[] hospName = new String[100]; int[] hospCode = new int[100]; hospCode[I] stores the code for a specific hospital. hospName[J] stores the name of the hospital that has code J. Suppose the code 24 is stored at position 13 of hospCode. Which expression below references 24's corresponding name? A. hospName[13] B. hospCode[24] C. hospCode[hospName[13]] D. hospName[hospCode[13]] E. hospName[hospCode[24]]

D. hospName[hospCode[13]] General Feedback: What we want is the name for hospital with code 24. We could get that with hospName[24], but that's not one of the options. However, we know that hospCode[13] contains the value 24, so we can use that instead.

Which of the following would be a valid method call for the following method? public static void showProduct (int num1, double num2) { int product; product = num1 * (int)num2; System.out.println("The product is " + product); } A. showProduct(10.0, 4); B. showProduct(33.0, 55.0); C. showProduct(5.5, 4.0); D. showProduct(10, 4.5);

D. showProduct(10, 4.5);

Here is a loop that is supposed to sum each of the values in the array named ar : double sum = 0.0; for (int i=0; i < ar.length; i++) // ??? System.out.println(sum); What goes on the line containing ???? : A. i = sum + ar[i]; B. sum + ar[i]; C. sum = sum + i; D. sum += ar[i];

D. sum += ar[i];

Natural ordening

De logische volgorde waarin objecten van een bepaalde class worden gesorteerd.

Autoboxing

De primitieve waarde wordt automatisch omgezet naar de wrapper class.

Specialisatie

De subclasses bevatten gedetailleerder data members en methods dan de superclass.

Throwable

De superclass van de subclasses Exception en Error

Generalisatie

De superclass verzameld alle gemeenschappelijke data members en methodes van de verschillende subclasses.

Collection views

De terugkeer waarde van deze methods zijn een Set of een Collection, waarop een Iterator kan toegepast worden.

JDBC

De verzameling classes die een eenvoudige toegang tot databases mogelijk maakt.

Interface

De verzameling van alle niet-private data members en methods

clear

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

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.

stop

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

break mode

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

format

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

How do you declare a String Builder/ String Buffer

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

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

Object-oriented programming

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

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

Diamonds

Default constructor

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

Creating Objects: Reference Variable

Dog is the data type. That's what reference allows us to do. It makes it user friendly by letting us make our own data types. We tell the computer to set aside a chunk of space for the data type, Dog. The size of the chunk will be big enough to hold an address, because reference is indirect. No actual amount will go in like with primitive datatypes where we know the amount of storage being used. It will just leave space (a placeholder)

DNS

Domain Name System; converts from a symbolic host name such as Columbia.edu to its 32-bit IP address

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.

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

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

What does casting have to do with interfaces?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

throws

Indicates that a method or constructor may pass the buck when an exception is thrown.

short

Indicates that a value is a 16-bit whole number.

float

Indicates that a value is a 32-bit number with one or more digits after the decimal point.

int

Indicates that a value is a 32-bit whole number.

double

Indicates that a value is a 64-bit number with one or more digits after the decimal point.

long

Indicates that a value is a 64-bit whole number.

char

Indicates that a value is a character (a single letter, digit, punctuation symbol, and so on) stored in 16 bits of memory.

byte

Indicates that a value is an 8-bit whole number.

boolean

Indicates that a value is either true or false, in the Java sense.

static

Indicates that a variable or method belongs to a class, rather than to any object created from the class.

protected

Indicates that a variable or method can be used in subclasses from another package.

private

Indicates that a variable or method can be used only within a certain class.

final

Indicates that a variable's value cannot be changed, that a class's functionality cannot be extended, or that a method cannot be overridden.

public

Indicates that a variable, class, or method can be used by any other Java code.

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

Infinite

Annotation

Informatie voor de compiler zodat die de nodige controles kan uitvoeren.

Binary Numbers

Information is stored in memory in digital form using the binary number system A single binary digit (0 or 1) is called a bit A single bit can represent two possible states, like a light bulb that is either on (1) or off (0) Permutations of bits are used to store values Devices that store and move information are cheaper and more reliable if they have to represent only two states

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.

interface

Introduces an interface, which is like a class, but less specific. (Interfaces are used in place of the confusing multiple-inheritance feature that's in C++.)

case

Introduces one of several possible paths of execution in a switch statement.

catch

Introduces statements that are executed when something interrupts the flow of execution in a try clause.

else

Introduces statements that are executed when the condition in an if statement isn't true.

try

Introduces statements that are watched (during runtime) for things that can go wrong.

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.

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 reference type of a polymorphic object instance?

It is the declaration of the instance. The stuff before the equals sign.

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

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

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

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

JDK

Java Development Kit

What is the JDK?

Java Development Kit.

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

Java portability

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

strictfp

Limits the computer's ability to represent extra large or extra small numbers when the computer does intermediate calculations on float and double values.

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

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

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

List and RandomAccess are interfaces to ArrayList.

Event Listeners (Observer?)

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

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

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

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

Expressions that use logical operators can form complex conditions

Max +5, then less than sign, then the logical not and logical & operators Think of it like true always wins

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.

format

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

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

Method body

Copy constructor

Method die alle properties van een nieuw object initialiseert adhv waarden van de proporties van het parameter object.

Constructor

Method met identieke naam als de class, wordt uitgevoerd als een object geïnstantieerd wordt.

put

Method of Hashtable. Maps the specified key to the specified value in this hashtable.

remove

Method of Hashtable. Removes the key (and its corresponding value) from this hashtable.

containsKey

Method of Interface Map. Returns true if this map contains a mapping for the specified key.

start

Method of Thread. This method Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

enumerate

Method of ThreadGroup. Copies into the specified array every active thread in this thread group.

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

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

Can you compare a boolean to an int?

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

Can you make a constructor final?

No, constructor can't be final.

Is constructor inherited?

No, constructor is not inherited.

Can a constructor be declared static?

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

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

No, interfaces can't be instantiated.

Can local variables use the static modifier?

No, local variables can only use the final modifier.

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

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

static

Not belonging to a class or individual objects.

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

Nothing happens.

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.

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

NumberFormatException

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)

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.

execute (SQL command)

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

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

Returns class name of an object.

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.

implements

Reuses the functionality from a previously defined interface.

operator precedence

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

Suite of tests

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

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

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

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

Runs infinitly

What happens when their is no main?

Runtime Error

What happens if their is no main method?

Runtime Error.

Block Statements

Several statements can be grouped together into a block statement delimited by braces A block statement can be used wherever a statement is called for in the Java syntax rules The if clause, or the else clause, or both, could be governed by block statements

Design patterns

Slimme oplossingen voor complexe problemen, die ons onder de vorm van abstract beschrijvingen worden gegeven.

SDK

Software Development Kit or a set of tools useful to programmers

debugger

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

return

Some methods, when called, __ a value to the statement in the application that called the method. The returned value can then be used in that statement.

Data Conversion

Sometimes it is convenient to covert data from one type to another For example in a particular situation we may want to treat an integer as a floating point value These conversions do not change the type of a variable or the value that's stored in it - they only convert a value as part of a computation Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) In Java, data conversions can occur in three ways: -assignment conversion -promotion -casting

"static" modifier

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

White Space

Spaces, new lines, and tabs are called white space White space is used to separate words and symbols in a program Extra white space is ignored by the computer A valid Java program can be formatted many ways Programs should be formatted to enhance readability, using consistent indentation

method

Specifies the actions of an object.

mantissa

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

type

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

Signature rule (subtypes)

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

Does constructor return any value?

Technically it returns the constructed object

git add

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

switch

Tells the computer to follow one of many possible paths of execution (one of many possible cases), depending on the value of an expression.

@Test(timeout = T)

Test fails if runs longer than T milliseconds.

@Test(expected = X.class)

Test is expected to throw exception X.

Glass box

Testing code (can see code)

Black box

Testing to specifications (code unseen)

instanceof

Tests to see whether a certain object comes from a certain class.

if

Tests to see whether a condition is true. If it's true, the computer executes certain statements; otherwise, the computer executes other statements.

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.

Multiplies

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

The + Operator

The + operator is also used for arithmetic addition The function that it performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation If both operands are numeric, then it adds them The + operator is evaluated left to right, but parentheses can be used to force the order If both of its operands are strings, or if one is a string and one is a number, it performs string concatenation. But if both operands are numeric, it performs addition.

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)

The Math Class

The Math class is part of the java.lang package The Math class contains methods that perform various mathematical functions These include: absolute value square root exponentiation trigonometric functions The methods of the Math class are static methods (also called class methods) Static methods never use instance variable values Math class does not have any instance variables Nothing to be gained by making an object of Math class Static methods are invoked through the class name - no object of the Math class is needed value = Math.abs(90) + Math.sqrt(100);

OR

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

Copying Arrays

The System class has an arraycopy method that you can use to efficiently copy data from one array into another: public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.

Diamond (in the UML)

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

size

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

name

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

type

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

+=

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

==, <= and <

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

Title bar

The area at the top of a JFrame where its title appears.

boolean

The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

What does break do?

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

byte

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

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.

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.

Escape Sequence

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

javac command

The command that compiles a source code file (.java) into a . class file.

How Java Works

The compiled bytecode is not the machine language for traditional CPU and is platform-independent javac and java (two command-line tools) can be found in the directory of bin/ of Java Development Kit (JDK) you will install

JLabel

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

termination condition

The condition that stops the loop.

What does continue do?

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

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

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

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

double

The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

float

The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

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

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

The if Statement

The if statement has the following syntax: if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression (must evaluate to either true or false) If the condition is true, the statement is executed. If it is false, the statement is skipped. An if statement with its boolean condition: if (total == sum) system.out.println("total equals sum"); Another if statement with its boolean condition: if (total != sum) system.out.println("total does NOT equals sum");

What is the default value of the local variables?

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

Logical NOT

The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then !a is false; if a is false, then !a is true Logical expressions can be shown using a truth table. A truth table shows all possible true-false combinations of the terms.

long

The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.

straight-line form

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

Program Development

The mechanics of developing a program include several activities: -writing the program (source code) in a specific programming language (such as Java) using an editor -translating the program (through a compiler or an interpreter) into a form that the computer can execute -investigating and fixing various types of errors that can occur using a debugger Integrated development environments, such as Eclipse, can be used to help with all parts of this process

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

The memory location is shown.

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

The message displayed by the dialog

Setter methods

The methods that change a property's value are called setter methods setSize()

Variable

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

What is the keyword native?

The native keyword is applied to a method to indicate that the method is implemented in native code using JNI.

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

The new keyword is needed to establish memory allocation.

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.

Incrementing

The process of adding 1 to an integer.

destructive

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

editable property

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

Problem Solving

The purpose of writing a program is to solve a problem The key to designing a solution is breaking it down into manageable pieces An object-oriented approach lends itself to this kind of solution decomposition We will dissect our solutions into pieces called classes (.java files) We design separate parts (classes) and then integrate them

functionality

The tasks or actions an application can execute.

.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

return value

The value that comes back from a method after it is run. In the following method: public int calculateMonth(String name), the return value is an integer.

state

The values of all of the variables in an object at a given time.

State

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

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.

update statement

The way the index of a loop changes value.

Comments

There are two forms of comments, which should be included to explain the purpose of the program and describe processing steps They do not affect how a program works

Another way to generate a Random Number

There is another way to generate a random double number [0,1) double newRand = Math.random(); as opposed to import java.util.Random; Random generator = new Random(); float newRand = generator.nextFloat();

Is the following interface valid? public interface Marker { }

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

Is this valid? short s = 1000s;

There is no s postfix.

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

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

Context

This interface consists of a set of name-to-object bindings. It contains methods for examining and updating these bindings.

Enumeration

This interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series.

Runnable

This interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.

if statement

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

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

This will cause a runtime exception to be thrown.

What is the output of the following code segment? int value = 1; switch (value) { case 0: System.out.println("Dog"); case 1: System.out.println("Cat"); case 1: System.out.println("Fish"); default: System.out.println("Cow"); }

This will not compile because it includes a case statement with the same value twice.

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.

How can you cast a polymorphic object?

To the object type or any of its subclasses.

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

Classes contain methods that determine the behaviors of objects

Two common usages of methods: -change the values of the instance variables, e.g., making deposits to a bank account object should change its current balance -methods can behave differently based on the values of the instance variables, e.g., playing a "Darkstar" song object and a "My Way" song object should be somehow different...

Input Tokens

Unless specified otherwise, white space is used to separate the tokens (elements) of the input White space includes space characters, tabs, new line characters The next method of the Scanner class reads the next input token and returns it as a string Methods such as nextInt and nextDouble read data of particular types (int and double)

JInternalFrame

Use for Multiple Document Interface (MDI)

Observable

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

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

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

relational operator

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

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.

double

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

Escape Sequence

What if we wanted to print the quote character? The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\) System.out.println ("I said \"Hello\" to you.");

Garbage Collection

When an object no longer has valid references to it, it can no longer be accessed by the program The object is useless and therefore is called garbage Java performs automatic garbage collection periodically, returning and object's memory to the system for use In other languages the programmer is responsible for performing garbage collection

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.

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

When the class is needed in main for the first time

Dog Example

Will see the syntax of creating objects (with unique instance variables) and then calling methods from the class later The computer will read this and decide which bark to use Just think of it like you name something (object) and give it variables and then it takes the information and outputs something (method)

"this" keyword

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter. public class Point { public int x = 0; public int y = 0; //constructor public Point(int x, int y) { this.x = x; this.y = y; } } Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.

Increment and Decrement

Write four different program statements that increment the value of an integer variable total. Count ++ Count = Count + 1 Count = ++ Count Count += 1

What output is produced by the following?

X: 25 Y: 65 Z: 30050

Are StringBuffer/StringBuilder final classes?

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 we overload main() method?

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

Can a class be declared as final?

Yes, a class can be declared final; that is, the class cannot be sub-classed. This is done for security and design.

Can you have virtual functions in Java?

Yes, all functions in Java are virtual by default.

Is this valid? Object [] o = {"Song Book", 35.95, new Guitar(), 6};

Yes, it is fine to have subtypes as elements in an array of a supertype.

Are instance variables assigned a default value?

Yes, member or instance variables are always given a default value.

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

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

Yes.

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

Yes.

What is a compound assignment operator?

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

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

set

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

varargs construct

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

"new" operator

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

Refactor - split loop

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

Book-Title

You should use _____ capitalization for a JButton's name.

EJB

Ze draaien op de server, zijn niet grafisch georiënteerd, maar zullen eerder taken verrichten in database manipulatie, netwerkbeheer, ...

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.

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

a Dimension object

Java Virtual Machine (JVM)

a hypothetical computer on which Java runs

What is an arrayList

a inherently ordered dynamic data structure that implements the List interface and extends AbstractList

assembly language

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

protocol

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

class

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

High-Level Programming Language

a programming language that resembles human language to some degree.

parameter

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

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

Method

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

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

Literal String

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

computer network

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

instance variable

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

algorithm

a well ordered collection of unambiguous and effectively computable operations that when executed produces a result and halts in a finite amount of time

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

Consider the following code snippet. int i = 10; int n = i++%5; a) What are the values of i and n after the code is executed? b) What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))?

a) i=11, n=0 b) i=11, n=1

Consider the following class: public class IdentifyMyParts { public static int x = 7; public int y = 3; } a) What are the class variables? b) What are the instance variables? c) What is the output from the following code: IdentifyMyParts a = new IdentifyMyParts(); IdentifyMyParts b = new IdentifyMyParts(); a.y = 5; b.y = 6; a.x = 1; b.x = 2; System.out.println("a.y = " + a.y); System.out.println("b.y = " + b.y); System.out.println("a.x = " + a.x); System.out.println("b.x = " + b.x); System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x);

a) x b) y c) a.y = 5 b.y = 6 a.x = 2 b.x = 2 IdentifyMyParts.x = 2

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

Comment Out

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

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

action event

actual parameter

actual value or reference that is passed to a method or subroutine -> gary.transfer(200); 200 is the actual parameter

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

Private Keyword

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

argument

an actual parameter in a method call or one of the values combined by an operator

What is the heap?

an area of memory allocated for objects by the JVM

what is an array?

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

transistor

an electrical switch with no moving parts

logic gate

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

What is a Collection?

an object that stores multiple elements in a single unit

instance variable

any item of data that's associated with a particular object.

white space

any sequence of only space, tab, and newline characters

Object

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

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

appear on the very first statement

The term API stands for ___?

application programmer interface

The first element in the array created by the statement int[] ar = { 1, 2, 3 }; is :

ar[0]

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.

bit

binary digit; smallest unit of information, either 0 or 1; n bits has 2^n possible values

machine language

binary instructions that are decoded and executed by the control unit

constructor

block statement created when an object is declared

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

byte short long float double int char boolean

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.

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

call stack

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

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)

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

class

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.

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

Postdecrement

counter--

Clean Build

created when you delete a previously compuiled versions of a class before compiling again

Example of three references and two object

d and c are aliases, because they both reference the same book

object-oriented programming

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

declare and initialize primitive variables

double thisIsDouble; int thisEnter; thisIsADouble=0.0; thisEnter=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

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

Compile-Time-Error

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

class Object

every class in Java is either a direct or indirect subclass of what?

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

exception handler

Logic

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

Instance

existing object of a class

CallableStatement

extends PreparedStatement. The interface used to execute SQL stored procedures. The JDBC API provides a stored procedure SQL escape syntax that allows stored procedures to be called in a standard way for all RDBMSs. This escape syntax has one form that includes a result parameter and one that does not. If used, the result parameter must be registered as an OUT parameter. The other parameters can be used for input, output or both. Parameters are referred to sequentially, by number, with the first parameter being 1.

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

Where is a software object's state contained?

fields (Java) or variables (C++)

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

final

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

final

memory

function unit of a computer that stores and retrieves instructions and data

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

generalization and specialization

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

getSelectedIndex

overloading a method

giving more than one meaning to a method name

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

has-A

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.

encapsulation

hiding of implementation details

instruction register

holds a copy of the instruction fetched from the memory. It holds both the op code and the addresses

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

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

instance variables

identifiers used to descibe the attributes of an object.

if else structure

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

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

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

You can create an array of three integers by writing :

int ar[] = new int[3];

IDE

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

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

list selection event

boolean operator

logical operator. && || !=

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.

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

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

private

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.

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.

How can this interface be correctly implemented? public interface TestInterface { public boolean errorState(); }

public class ClassX implements TestInterface{ public boolean errorState() { return false; } } An object can act as any interface it implements. and public class ClassX implements TestInterface{ private boolean errorState() { return false; } } An object can also act as any of its superclasses.

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)

Application

stand-alone, executable program

javadoc Comments

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

Line Comments

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

What do real world objects contain?

state and behavior

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.

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)

Cache Memory

temporary storage area where frequently accessed data can be stored for rapid access. fast, expensive, small. First site of search.

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.

Stored Program concept

the computers ability to store program instructions as binary in main memory for execution. Created by von Neumann

Inheritance

the concepts that one class can take on the fields, methods and nested classes of another object by using the extends keyword

formal parameter

the data type and variable name of a reference or value that is defined in a method definition

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

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

Allman Style

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

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

address

the memory address of the values of which an operation will work

scope

the part of a program in which a variable can be accessed

set input variables

thisEnter = myScanner.next.Int();

Interactive Applications

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

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

throw

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

thrown

Executing

to carry out a statement

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

Try catch exception block

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

stack and heap

two main memory locations for Java

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

unchected exceptions

Exceptions

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

Integer

unsigned int, 0 -> 2^31 -1

Array Manipulations

useful operations provided by methods in the java.util.Arrays class, are: Searching an array for a specific value to get the index at which it is placed (the binarySearch method). Comparing two arrays to determine if they are equal or not (the equals method). Filling an array to place a specific value at each index (the fill method). Sorting an array into ascending order. This can be done either sequentially, using the sort method, or concurrently, using the parallelSort method introduced in Java SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array sorting.

CH13: A list selection listener must have this method.

valueChanged

What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] > value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 1, 3, 5, 7, 0, 0 } 2. { 1, 3, 5, 0, 0, 0 } 3. { 1, 3, 7, 5, 0, 0 } 4. { 5, 1, 3, 7, 0, 0 }

{ 1, 3, 5, 7, 0, 0 }

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

Redundant

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

Mismanaged threads result in

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

Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (size < capacity && value > 0) { a[size] = value; size++; 1. Reads one value and places it in the remaining three unused spaces in a. 2. Reads up to 3 values and places them in the array in the unused space. 3. Reads up to 3 values and inserts them in the array in the correct position. 4. Crashes at runtime because it tries to write beyond the array.

1. Reads one value and places it in the remaining three unused spaces in a.

ResultSet

A public interface. A table of data representing a database result set, which is usually generated by executing a statement that queries the database.

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.

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

Advantages of exceptions

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

Unchecked exception

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

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.

.java

1. A source code file has the ____ extension.

Event loop

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

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

variable

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

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.

algorithm

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

run

Method. When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's this method to be called in that separately executing thread.

Event Handlers

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

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.

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

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

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

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

Java Program Structure

In the Java programming language: -A program is made up of one or more classes defined in source files (with the .java extension) -A class contains one or more methods -A method contains program statements

transient

Indicates that, if and when an object is serialized, a variable's value doesn't need to be stored.

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.

Event-Driven Programing

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

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

object

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

pseudocode

An informal language that helps programmers develop algorithms.

By default what is this considered - 12?

An int.

Loop

Another general name for a repetition statement.

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

Becauseof ambiguity.

Final

Behoudt gedurende het hele programma dezelfde waarde

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

Both expressions are true.

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.

CruiseControl

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

int

By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.

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;

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.

semicolon (;)

Character used to terminate each statement in an application.

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

Class, Package, Sub class, and World.

InterruptedException

Class. Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.

Object-Oriented Programming

Classes are the building blocks of a Java program; a blueprint for which individual objects can be created Each class is an abstraction of similar objects in the real world E.g., dogs, songs, houses, etc Once a class is established, multiple objects can be created from the same class. Each object is an instance (a concrete entity) of a corresponding class E.g., a particular dog, a particular song, a particular house, etc

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

Connection interface (JDBC)

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

Final

Constants are declared with keyword ____.

What is a constant?

Constants are variables that cannot be changed.

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.

JTextArea

Control that allows the user to view multiline text.

Local variables (field)

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

Counter-controlled repetition is also called _.

Definite repetition

SortedSet

Een interface afgeleid van de Set interface dat geen dubbele waarden kan bevatten en altijd gesorteerd is in stijgende volgorde.

Collection

Een interface dat een reeks andere objecten groepeert.

Map

Een interface dat een reeks van objecten groepeert als key-value paren. Het kan geen dubbels bevatten.

Cloneable

Een interface met de method clone()

SERVLET

Een klein programmaatje dat op de server draait. Wordt vooral gebruikt om html-pagina's te genereren.

APPLET

Een kleine applicatie die samen met een HTML pagina geladen wordt vanaf een internet server en die op de cliënt computer wordt uitgevoerd.

Package

Een verzameling logisch bij elkaar horende classes, die in een eigen directory, subdirectory worden opgeslagen.

Bounded wildcard

Een wildcard waarop beperkingen opgelegd zijn: afgeleid van een bepaald type.

Synchrinized wrapper

Een wrapper class die een object thread safe maakt

Unmodifiable wrapper

Een wrapper class die er voor zorgt dat een object niet meer te wijzigen is.

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 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 does the substring method written like this return - stringName.subString(6,5)?

Exception

GUI

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

for

Gets the computer to repeat some statements over and over again (for instance, a certain number of times).

Quick Check: Booelan Expressions

Given the following declarations, what is the value of each of the listed boolean conditions?

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.

What happens when a class final?

It cannot be extended?

memory address register

It is 32 bits. Used in memory write and read operations and not accessible by the programmer.

What is super in java?

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

What is overriding?

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

Methods

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

hasMoreElements

Method of Enumeration. Tests if this enumeration contains more elements.

Serialize

involves saving the current state of an object to a stream, and restoring an equivalent object from that stream. The stream functions as a container for the object.

How do you run a program using commands.

javac ClassName.java java ClassName

CH13: The ListSelectionListener interface is in this package.

javax.swing.event

What is this()?

calls a constructor in the same 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)

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)

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)

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)

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

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

Overriding

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

declare a class

Public Class MemorizeThis {

Type of errors

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

declared scanner class

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

setText

Sets the text property of the JTextArea component.

cast

explicitly converting a value from one type to a different type

actual parameters

expression supplied by a formal parameter of a method by the caller. Value of the parameter.

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

extends

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

getMessage

Memory Address Register (MAR)

holds the address of the cell to be fetched or stored

Memory Data Register

holds the information to be transferred/copy of information received

super.method();

how to call a superclass method in a subclass

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

if then

IDE

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

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

interface

public and abstract

interface methods are implicitly what?

this()

invokes the constructor.

horizontalAlignment property

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

location property

The property that specifies where a component's upper-left corner appears on the JFrame.

"protected" modifier

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

inheritance (in Java)

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

Syntax

The rules of a language that define how we can combine symbols, reserved words, and identifiers to make a valid program -Identifiers cannot begin with a digit -Curly braces are used to begin and end classes and methods

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.

Semantics

The semantics of a program statement define what that statement means (its purpose or role in a program) A program that is syntactically correct is not necessarily logically (semantically) correct A program will always do what we tell it to do, not what we meant to tell it to do

short

The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

Primitive Types

There are eight Primitive data types in Java Four of them represent integers • byte, short, int, long Two of them represent floating point numbers • float, double One of them represents a single character • char And one of them represents boolean values • boolean

arithmetic operators

These operators are used for performing calculations.

Threads

These share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.

Vector

This class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a this can grow or shrink as needed to accommodate adding and removing items after the this has been created.

Object

This class is the root of the class hierarchy. Every class has this as a superclass. All objects, including arrays, implement the methods of this class.

Hashtable

This class maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects, the objects used as keys must implement the hashCode method and the equals method.

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.

FLOPS

floating point operations per second. measure of computer's performance at brute force applications

flops

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

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

assignment operator

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

Method overloading

Twee methods schrijven binnen een class met dezelfde naam, maar met een verschillend aantal parameters.

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

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

Yes.

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

Yes.

Can a constructor be declared private?

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

const

You can't use this word in a Java program. The word has no meaning. Because it's a keyword, you can't create a const variable.

goto

You can't use this word in a Java program. The word has no meaning. Because it's a keyword, you can't create a goto variable.

Refactor - extract method

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

Variable Declaration

stating the name of the variable coupled with its data type

register

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

mass storage

storage of large amount of data in machine readable form for access by a computer system

What does it mean if one class is derived from another?

the derived class extends from its ancestor class - inherits state and behavior

Polymorphism

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

Encapsulation

the hiding of data and methods within an object

encapsulation

the hiding of implementation details and providing methods for data access

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)

Getter methods

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

implicit parameter

the object on which a method is invoked. comes before the method. myAccount.getDeposit(). my account is the implicit parameter

What is a base class?

the parent of a child class

SuperClass

the parent or supertype of a class

Scope

the part of a program in which the variable is defined

Parsing

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

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

What does the public keyword mean?

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

To determine the number of valid elements in an ArrayList, use:

the size() method

literal

the source code representation of a fixed value

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

computer science

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

Dynamic binding

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

ObjectInputStream

this class deserializes primitive data and objects previously written using an ObjectOutputStream. ObjectOutputStream and this class can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. this class is used to recover those objects previously serialized. Other uses include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system.

formal parameter

variable in a method definition. initialized with an actual parameter when method is called.

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

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.

terabyte

maximum memory size is 2^40 memory bytes

static

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

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

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

clone

method of Object. Creates and returns a copy of this object( Class Object).

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

explicit parameter

parameter of a method OTHER THAN THE OBJECT ON WHICH METHOD IS INVOKED

Parameter(overloaded) constructor

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

syntax

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

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.

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

second string third string

notify() (Thread Communication)

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

notifyAll() (Thread Communication)

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

Parameter passing

specifying expressions to be actual parameter values for a method when it is called

Block Comments

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

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

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

Not changed

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

setText

7. A Jlabel component displays the text specified by ____.

abstract

Indicates that the details of a class, a method, or an interface are given elsewhere in the code.

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

Infinity

What is casting?

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

Disadvantages of Centralised Servers

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

Software Patterns

- Reusable solution to common problem. - Description/Template

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.

Nondestructive

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

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

double

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

instance

An object.

An action

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

Multidimensional arrays

String[][] names = { {"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"} };

Print to screen

System.out.println("Hello World!");

initialization

To start, the first value given to a variable

Hashcode (GIT)

Uniquely identify each commit.

print

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

Close Window (GUI)

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Packages

For purposes of accessing them, classes in the Java API are grouped into packages

Quick Check: The Random Class

Given a Random object reference named gen, what range of values are produced by the following expression?

What Java Can Do

Science and Technology -Popular machine learning libraries are written in Java: Mahout, Weka -Has been adopted in many distributed environments (Hadoop) Web development -Most web backend are developed using Java Mobile application development -Android development platform Graph user interface (GUI) design: menu, windows, ...

Java Class Libraries

A class library is a collection of classes to facilitate programmers when developing programs The Java standard class library is part of any Java development environment (available after installing JDK) The Java standard class library is sometimes referred to as the Java API (Application Programming Interface) Its classes are not part of the Java language per se, but we rely heavily on them Various classes we've already used (System, String) are part of the Java API

Constant

A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence As the name implies, it is constant and cannot be changed The compiler will issue an error if you try to change the value of a constant In Java, we use the final modifier to declare a constant final int NUM_SEASONS = 4; whenever you use the reference variable, NUM_SEASONS, it will equal 4 Constants are useful for three important reasons First, they give meaning to otherwise unclear literal values Example: MAX_LOAD means more than the literal 250 Second, they facilitate program maintenance If a constant is used in multiple places, its value need only be set in one place Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers

Language Levels

There are four programming language levels. Each type of CPU has its own specific machine language The other levels were created to make it easier for a human being to read and write programs

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

Object

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.

jump

up and down

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

...

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

...

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

JTextArea method _ adds text to a JTextArea.

Append

API

Application Programming Interface; a code library for building programs

Final class

Een class waarvan niet meer overgeërfd kan worden.

BorderLayout

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

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.

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

a one-way link

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.

compiler

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

Compiler/Interpreter

a program that translates code into machine language

class

a programmer defined data type. Blueprint from which individual objects are created. A class definition defines instance and class variable and methods. also specifies interfaces

Computer Porgram

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

Java standard class library (Java API)

a set of predefined classes and methods that other programmers have already written for us System, out, println and String are not Java reseved words, they are part of the API

Write Once Run Anywhere (WORA)

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

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

interface (in Java)

a type with no instance variables, only abstract methods and constants

Unicode

an international system of character representation

parameter

an item of info specific to a method when the method is called

instance

an object of a particular class. Created using the new operator followed by the class name

Create an array

anArray = new int[10];

Get the length of an array

anArray.length

Initialize an array

anArray[0] = 100; or int[] anArray = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };

primitive data type

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

Depend (ANT)

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

Transaction processing (JDBC)

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

Instance

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

Random Access Memory

electronic circuits in a computer that can store code and data of running programs

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

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

encapsulation

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 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 a package?

- A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.

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.

Event Adapters

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

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.

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

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

Pass by value

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

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

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

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.

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 wrapper classes?

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

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.

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 are the states associated in the thread?

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

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

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.

Who is loading the init() method of servlet?

- Web server

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.

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

Target (ANT)

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

Safely stop thread

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

Checked exception

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

java.lang.Runnable

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

Timer

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

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.

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

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

Instance variables

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

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

...

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

...

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

...

Black box Steps

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

TDD Mantra

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

Interface rules

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

Refactoring Techniques

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

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] < a[x]) x = i; System.out.println(x); 1. Finds the position of the smallest value in a. 2. Sums the elements in a. 3. Finds the position of the largest value in a. 4. Counts the elements in a.

1. Finds the position of the smallest value in a.

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

Subtype rules

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

What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x += a[i]; System.out.println(x); 1. Sums the even elements in a. 2. Finds the largest value in a. 3. Finds the smallest value in a. 4. Counts the even elements in a.

1. Sums the even elements in a.

Test Driven Development (TDD)

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

Valid Identifier

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

setBackground

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

Why should I bundle classes and interfaces into a package?

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

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

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

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the value at index 10 of the array above?

10

What is the output of the following Java code? int[] alpha = {2, 4, 6, 8, 10}; int j; for (j = 4; j >= 0; j--) System.out.print(alpha[j] + " "); System.out.println();

10 8 6 4 2

At

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

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

16 bit unicode character

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

Suppose that sales is a two-dimensional array of 10 rows and 7 columns wherein each component is of the type int , and sum and j are int variables. Which of the following correctly finds the sum of the elements of the fifth row of sales? 1. sum = 0; for(j = 0; j < 10; j++) sum = sum + sales[5][j]; 2. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[4][j]; 3. sum = 0; for(j = 0; j < 10; j++) sum = sum + sales[4][j]; 4. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[5][j];

2. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[4][j];

What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; for (j = 4; j >= 0; j--) { alpha[j] = j + 5; if (j <= 2) alpha[j + 1] = alpha[j] + 3; } 1. 8 2. 10 3. 9 4. 5

2. 10

char[][] array1 = new char[15][10]; What is the value of array1[3].length? 1. 15 2. 10 3. 2 4. 0

2. 10

What is the value of alpha[4] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 2; for (j = 1; j < 5; j++) alpha[j] = alpha[j - 1] + 3; 1. 11 2. 14 3. 5 4. 8

2. 14

char[][] array1 = new char[15][10]; How many dimensions are in the array above? 1. 3 2. 2 3. 1 4. 0

2. 2

public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } How many constructors are present in the class definition above? 1. 3 2. 2 3. 1 4. 0

2. 2

Assume that two arrays are parallel. Assume the first array contains a person's id number and the second contains his or her age. In which index of the second array would you find the age of the person in the third index of the first array? 1. 2 2. 3 3. 1 4. It cannot be determined from the information given.

2. 3

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

2. Any number

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

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

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

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 }

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, 9, 1, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] < a[x]) x = i; System.out.println(x); 1. 6 2. 1 3. 2 4. 4

3. 2

What is the value of alpha[2] after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) alpha[j] = 2 * j + 1; 1. 1 2. 4 3. 5 4. 6

3. 5

The arguments in a method call are often referred to as ____. 1. concept parameters 2. constants 3. actual parameters 4. argument lists

3. Actual parameters

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.

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)

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)

public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } What does the default constructor do in the class definition above? 1. Sets the value of x to 0 2. There is no default constructor. 3. Sets the value of x to 1 4. Sets the value of x to a

3. Sets the value of x to 1.

Empty String

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

What is the last index of the string TEXT?

3. The first letter starts with index 0.

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

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

3. local

Assigning ____ to a field means that no other classes can access the field's values. 1. key access 2. user rights 3. private access 4. protected access

3. private access

Person -name: String +setName(String name): void +getName(): String ^ Student -studentID: long +Student(String sname, long sid) +setID(): long To access the name instance variable from inside a method defined in the Student class, name must use the _____________ modifier. (We'll ignore the default package-private access if no modifier is used.) 1. Any of them 2. public 3. protected or public 4. protected 5. private 6. private or protected

3. protected

Which of the following words indicates an object's reference to itself? 1. public 2. that 3. this 4. protected

3. this

What is the value of alpha[4] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 2; for (j = 1; j < 5; j++) alpha[j] = alpha[j - 1] + 3; 1. 5 2. 11 3. 8 4. 14

4. 14

char[][] array1 = new char[15][10]; What is the value of array1.length? 1. 0 2. 10 3. 2 4. 15

4. 15

int[] array1 = {1, 3, 5, 7}; for (int i = 0; i < array1.length; i++) if (array1[i] > 5) System.out.println(i + " " + array1[i]); What is the output of the code fragment above? 1. 0 3 2. 7 3 3. 5 1 4. 3 7

4. 3 7

What is the value of alpha[2] after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) alpha[j] = 2 * j + 1; 1. 4 2. 6 3. 1 4. 5

4. 5

double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is in vals[2][1]? 1. 3.3 2. 3.5 3. 1.3 4. 5.3

4. 5.3

Consider the following statements. public class PersonalInfo { private String name; private int age; private double height; private double weight; public void set(String s, int a, double h, double w) { name = s; age = a; height = h; weight = w; } public String getName() { return name; } public int getAge() { return age; } public double getHeight() { return height; } public double getWeight() { return weight; } } Assume you have the following code fragment inside a method in a different class: PersonalInfo person1 = new PersonalInfo(); PersonalInfo person2 = new PersonalInfo(); String n; int a; double h, w; Which of the following statements are valid (both syntactically and semantically) in Java? (i) person2 = person1; (ii) n = person1.getName(); a = person1.getAge(); h = person1.getHeight(); w = person1.getWeight(); person2.set(n, a, h, w); 1. None of these 2. Only (ii) 3. Only (i) 4. Both (i) and (ii)

4. Both (i) and (ii)

Assume you have a Student object and a Student variable named bill that refers to your Student object. Which of these statements would be legal? bill.name = "Bill Gates"; // I bill.setName("Bill Gates"); // II println(bill.getName()); // III bill.studentID = 123L; // IV println(bill.getID()); // V 1. II, III, IV, VI 2. IV, V 3. All of them 4. II, III, V 1 5. None of them

4. II, III, V

Parentheses

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

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

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)

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}

Person -name: String +setName(String name): void +getName(): String ^ Student -studentID: long +Student(String sname, long sid) +setID(): long Which of these fields or methods are inherited (and accessible) by the Student class? 1. getName(), setName(), name 2. name, getName(), setName(), getID() 3. studentID, name, getName(), setName(), getID() 4. getName(), setName(), toString() 5. None of them 6. getName(), setName(), studentID, getID()

4. getName(), setName(), toString()

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the data type of the array above? 1. list 2. num 3. char 4. int

4. int

If a method in the superclass is declared protected, you may replace it in the subclass as long as the subclass method that you define: 1. has a different number, type, or order of parameters 2. has a different return type 3. is defined as protected or private 4. is defined as public or protected 5. is defined only as public

4. is defined as public or protected

A locally declared variable always ____ another variable with the same name elsewhere in the class. 1. uses 2. creates 3. deletes 4. masks

4. masks

When you create a new class using inheritance, you use the extends keyword to specify the __________________ when you define the ________________. 1. derived class, subclass 2. derived class, base class 3. superclass, base class 4. subclass, base class 5. superclass, subclass 6. subclass, superclass

5. superclass, subclass

double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is in vals[2][1]? 1. 1.3 2. 3.3 3. 3.5 4. 5.3

5.3

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

Before

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

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

== = is an assignment operator

input JTextField

A JTextField used to get user input.

Procedural

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

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.

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

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

print

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

When dividing what must the variable be put into?

A double because division automatically sets it to a double.

block

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

body

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

Transistors

A solid state device that has no mechanical or moving parts; the light switch of electricity flow

While Statement

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

binary

A string of bits, Base 2.

++ (unary increment operator)

Adds one to an integer variable.

What does the NEW keyword do?

Allocates new space in memory.

Refactoring

Cleans code whilst preserving behaviour.

What is the output of the following Java code? int[] list = {0, 5, 10, 15, 20}; int j; for (j = 1; j <= 5; j++) System.out.print(list[j] + " "); System.out.println(); 1. 5 10 15 20 0 2. 5 10 15 20 20 3. 0 5 10 15 20 4. Code contains index out-of-bound

Code contains index out-of-bound

event handler

Code that executes when a certain event occurs.

statement

Code that instructs the computer to perform a task. Every statement ends with a semicolon ( ; ) character. Most applications consist of many statements.

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.

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

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

throw

Creates a new exception object and indicates that an exceptional situation (usually something unwanted) has occurred.

enum

Creates a newly defined type — a group of values that a variable can have.

extends

Creates a subclass — a class that reuses functionality from a previously defined class.

new

Creates an object from an existing class.

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

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

Which of the following is not a benefit derived from using methods in programming? A. Code reuse B. Problems are more easily solved C. Simplifies programs D. All of the above are benefits

D. All of the above are benefits

To print the last element in the array named ar, you can write : A. System.out.println(ar.length); B. System.out.println(ar[length]); C. System.out.println(ar[ar.length]); D. None of these

D. None of these

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

Date birthday=new Date

Inheritance

De class laten afleiden van een andere class.

Synchronisatie

De handeling is ondeelbaar, het kan niet onderbroken worden door een andere thread.

Enumeration constants

De individuele waarden die een variabele van het datatype enumeration kan aannemen.

In a @return tag statement the description

Describes the return value

In a @return tag statement the description A. Describes the return value B. Must be longer than one line C. Cannot be longer than one line D. Describes the parameter values

Describes the return value

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

How to Execute Programs

Each type of CPU executes only a particular machine language A program must be translated into machine language before it can be executed Compiler: translates only once Most high-level languages: C, C++, etc. Interpreter: translates every time you run programs Most scripting languages: python, perl, etc. The Java approach is somewhat different. It combines the use of a compiler and an interpreter.

TreeMap

Een Map waarbij de entry's gesorteerd worden opgeslagen volgens de natural ordening van de sleutel.

NullPointerException

Een RuntimeException: het betreffende object kan geen null-waarde bevatten

Class

Een abstract beschrijving van een ding.

Interface

Een abstracte class waarin alleen abstracte methods en eventueel publieke constanten opgenomen zijn.

Inheritance Polymorphism

Een array maken met references naar objecten met eenzelfde base class.

Interface polymorphism

Een array maken van referance variabelen met als type een interface.

Wrapper class

Elke primitive data type heeft een bijhorende class

native

Enables the programmer to use code that was written in another language (one of those awful languages other than Java).

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.

How can exceptions be handled in Java?

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

IOExceptions

Exceptions die te maken hebben met in- en uitvoer.

RuntimeExceptions

Exceptions die zich voordoen tijdens het uitvoeren van een applicatie

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

Upcasting

Het proces om een object van een subclass te beschouwen als een object van zijn superclass.

Wildcard

Het type wordt helemaal niet vastgelegd; het wordt beschouwd als een joker.

Creating objects

How to create objects once a class is established? How to "hold" those created objects? For primitive types (such as byte, int, double), we use a variable of that particular type as a cup to store its actual value BUT Objects are different There is actually no such thing as an object variable, because we can't put a number on it. There is only an object reference variable An object reference variable holds something like a pointer or an address that represents a way to get to the object. When you copy a string object, you're really copying it's address.

HTTP

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

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 happens if a class has no modifier?

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

Basic Program Execution

If there are errors the compiler will complain and not let us go onto the next step. We must trace back to the source and fix the problem in our code. It's important to understand why you're getting errors. LOOK IT UP debuggers can help you find errors in your code

finally

Introduces the last will and testament of the statements in a try clause.

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

Java Runtime Environment (JRE)

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

Dangers of threads

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

class

Introduces a class — a blueprint for an object.

default

Introduces a path of execution to take when no case is a match in a switch statement.

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

JOptionPane.ERROR_MESSAGE

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

JRadioButtonMenuItem

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.

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.

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

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

No

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.

Can a top-level class be marked as protected?

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

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

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

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

hexidecimal

Number utilizing base 16

Assignment Operators

Often we perform an operation on a variable, and then store the result back into that variable Java provides assignment operators to simplify that process For example, the statement num += count; is equivalent to num = num + count; Other assignment operators: -=, *=, /=, %=

Jar

Om de hoeveelheid code die bevat zit in duizenden classes manipuleerbaar te houden, slaat men ze op in gecomprimeerde archieven.

Reference Assignment

Once a String object has been created, neither its value nor its length can be changed (it's immutable) However, its reference variables can change

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

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

Inheritance

One class can be used to derive another via inheritance Classes can be organized into hierarchies

nested or embedded

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

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

Danger of using GIT

Only one repository.

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

Overloading

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

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

Task (ANT)

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

FlowLayout

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

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)

set up main method

Public static void main (string[], args) {

git push

Publishes committed local files to remote repo.

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.

while

Repeats some statements over and over again (as long as a condition is still true).

Fill in the blank. Import statements are ______.

Required in all versions of Java.

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

jdb

Starts the Java debugger when typed at the Command Prompt.

algorithm

Step by step process.

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.

declare and initialize string variables

String itemToCheck; itemToCheck = "";

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;

The header of a value-returning method must specify this.

The data type of the return value

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

Argumenten van het wildcard type

Superclasses en interfaces als method parameter gebruiken zodat de method voor de verschillende implementaties en subclasses gebruikt kan worden.

concatenate and output

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

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

how to pass an object to a method

System.out.println(new Date()):

AND

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

NOT

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

More About System.out

The System.out object represents a destination (the monitor screen) to which we can send an output The System.out object provides another service in addition to println The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line

RGB value

The amount of red. green and blue needed to create a color.

The header of a value-returning method must specify this. A. The method's local variable name B. The data type of the return value C. The name of the variable in the calling program that will receive the returned value D. All of the above

The data type of the return value

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

Decimal points

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

What best describes the result of the following code segment? The ArrayList sampleArrayList has already been declared and initialized. int i = 63; sampleArrayList.add(i);

The int is converted to an Integer via auto boxing and then placed into the ArrayList. Primitives cannot be stored in an ArrayList. However, if they are placed into their primitive wrapper class they can be stored. Java will automatically make that conversion via its autoboxing feature if a primitive is placed into an ArrayList.

actionPerformed

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

setBounds

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

Objects and the Heap

The number of objects that a program creates is not known until the program is actually executed Java uses a memory area called the heap to handle this situation, which is a dynamic pool of memory on which objects that are created are stored When an object is created, it is placed in the heap -Two or more references that refer to the same object are called aliases of each other -One object can be accessed using multiple reference variables -Changing an object through one reference changes it for all of its aliases, because there is really only one object

Listeners

The objects that receive the information that an event occurred are called listeners.

If you print an object what will be printed?

The objects toString method.

CH12: All exception classes inherit from this class.

Throwable

What version of Unicode is supported by Java SE 7?

Unicode standard, version 6.0.0

setText

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

Throwable

Used to define own exceptions.

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

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

JTextField.RIGHT

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

Object

Value of a class type. Stores its state in fields and exposes its behavior through methods

Thread safe variables

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

Downcasting

Via expliciete typecasting een object van een superclass typecasted naar een object van een subclass.

Nested if Statements

We can put an if-else statement as part of another if statement, these are called nested if statements if ( condition1 ) if ( condition2 ) statement1; else statement2; An else clause is always matched to the last unmatched if (no matter what the indentation implies) Braces can be used to specify the if statement to which an else clause belongs Both if statements must be true for statement 1 to be printed

truncating

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

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 use underscores in primitives not including char or boolean?

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

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

array

a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created.

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 is JavaDoc?

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

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

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

add() remove()

add something to ArrayList remove something to ArrayList

CH13: To display a scroll bar with a JList component, you must _________.

add the JList component to a JScrollPane component

GridLayout

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

"interface" type

an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. An interface defines a protocol of communication between two objects. An interface declaration contains signatures, but no implementations, for a set of methods, and might also contain constant definitions. A class that implements an interface must implement all the methods declared in the interface. An interface name can be used anywhere a type can be used.

Events

allow components to notify each other when something happens.

Inheritance

allows code defined in one class to be reused in other classes.

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}

ASCII

american standard code for information interchange. an international standard for representing textual info. 8 bits/character. allows a total of 256 character to be represented

Syntax Error

an error of language resulting from code that does not conform to the syntax of the programming language

Map

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

ALU

arithmetic/logic unit. sub system that performs math and logical operations.

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

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

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

Assertion code

assert boolean_expression; assert boolean_expression : displayable_expression;

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

bert!

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

ArrayList<string> stringList = new ArrayList<string>();

code to declare a string array list called stringList

instantiation

construction of an object of that class

When you write an explicit ____ for a class, you no longer receive the automatically written version.

constructor

Package

contains a group of built-in Java classes

pseudocode

informal programming language with English-like constructs modeled to look like statements in a java-like language

pseudocode

informal programming language with english like constructs

Arguments

information passed to a method so it can perform its task

Things an object knows about itself are called ?

instance variables

variables declared inside a class but outside any method

instance variables

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

Logic Error

occurs when a program compiles successfully but produces an error during execution

op code

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

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

Methods in interfaces are automatically what?

public and abstract.

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)

time complexity

quantifies the amount of time taken by an algorithm to run; commonly expressed using big O notation

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.

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

setEditable

CH13: This method is inherited from JComponent and changes the appearance of a component's text.

setFont

CH13: This method can be used to store an image in a JLabel or a JButton component.

setIcon

CH13: You use this method to place a menu bar on a JFrame.

setJMenuBar

CH13: This method sets the intervals at which major tick marks are displayed on a JSlider component.

setMajorTickSpacing

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

setText

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

computer science

study of algorithms including their: mathematical and formal properties, hardware realizations, linguistic realizations, and application

CH11: In an inheritance relationship, this is the specialized class.

subclass

Common behavior can be defined in a ___ and inherited into a ___ using the ___ keyword.

superclass, subclass, extends

int x = (int)a;

syntax to cast type (double a = 1.54;) into an int

public Class Dog extends Animal implements Pet{}

syntax to create an Animal subclass called dog that has a pet interface

public interface Pet

syntax to create an interface called Pet

super.runReport();

syntax to run superclass' runReport() method

protocol stack

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

Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long 1. toString() 2. None of them 3. getName(), setName(), name 4. name, getName(), setName(), getID() 5. getName(), setName(), studentID, getID() 6. studentID, name, getName(), setName(), getID()

toString()

Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Assume that pete is a Person object variable that refers to a Person object. Which method is used to print this output: pete is Person@addbf1 1. getClass() 2. getAddress() 3. getName(), getID() 4. getID() 5. getName() 6. None of them 7. toString()

toString()

"final" modifier

use "final" to create a constant. The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change. For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter): static final double PI = 3.141592653589793;

Import Statement

used to access a built-in Java class that is contained in a package

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

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)

type name in angle brackets

what is a type parameter

when you don't want a class to be instantiated

what is an abstract class?

a reference variable of the object type linked together by the = operator

what is an object

changing an inherited method

what is overriding

package name + class name

what is the full class name

abstract and non-abstract

what kind of methods are allowed in an abstract class

Run-Time-Error

when a programcompiles successfully but does not execute

instantiation

when instantiating a class, constructing an object of that class

Semantic Errors

when the correct word in the wrong context is used in program code

void

when used in a method header, indicates that the method does not return any value when it is called

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

Everything from index 1 and up(Inclusive)

What happens when you divide and Int by 0?

Exception

Classpath

Geeft aan waar je andere zelfgeschreven classes vindt

Types of sets

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

What is composition?

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

Java Identifiers

Identifiers are the "words" in a program -Name of a class: Dog, MyFirstApp, and Lincoln -Name of a method: bark and main -Name of a variable: args (later in this course) Rules: A Java identifier can be made up of -letters -digits (cannot begin with a digit) -the underscore character ( _ ), -the dollar sign ($) Java is case sensitive: -Total, total, and TOTAL are different identifiers By convention, programmers use different case styles for different types of identifiers, such as title case for simple class names - Lincoln camel case for compound words - MyFirstApp upper case for constant variables - MAXIMUM

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.

super

Refers to the superclass of the code in which the word super appears.

ClassNotFoundException is a subclass of?

ReflectiveOperationException

IllegalAccessException is a subclass of?

ReflectiveOperationException

NoSuchMethodException is a subclass of?

ReflectiveOperationException

executeQuery (SQL command)

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

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

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 Reader/Writer and InputStream/Output Stream?

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

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.

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

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.

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.

Replaces

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

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

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.

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

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

...

What does element indexing start at?

0.

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

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

1 time

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

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

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

An object is a(n) ____ of a class. 1. instance 2. method 3. field 4. constant

1. Instance

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)

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

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

1. accessor

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

Size, style, and name

3. The font property controls the ____ of the font displayed by the Jlabel.

public static String exampleMethod(int n, char ch) Which of the following statements about the method heading above is NOT true? 1. The method has two parameters. 2. exampleMethod is an identifier giving a name to this specific method. 3. The method cannot be used outside the class. 4. It is a value-returning method of type String.

3. The method cannot be used outside the class.

Consider the following method definition. public int strange(int[] list, int item) { int count; for (int j = 0; j < list.length; j++) if (list[j] == item) count++; return count; } Which of the following statements best describe the behavior of this method? 1. This method returns the sum of all the values of list. 2. None of these 3. This method returns the number of times item is stored in list. 4. This method returns the number of values stored in list.

3. This method returns the number of times item is stored in list.

setTitle

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

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

3. []

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

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 }

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 value for the variable sum? int[][] sampleArray = new int[3][4]; for (int i = 0; i < 3; i++) { sampleArray[i][i+1] = 2; } int sum = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { sum += sampleArray[i][j]; } }

4

What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; for (j = 4; j >= 0; j--) { alpha[j] = j + 5; if (j <= 2) alpha[j + 1] = alpha[j] + 3; } 1. 9 2. 5 3. 8 4. 10

4. 10

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

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)

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

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

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.

Exception

Een class Dat je gebruikt bij het opvangen van onvoorziene omstandigheden.

ListIterator

Een class dat dient om een List te kunnen doorlopen van voren naar achteren en omgekeerd of vanaf een bepaalde positie.

Iterator

Een class dat dient om een collectie te kunnen doorlopen van voor naar achter.

Collections

Een class dat enkele constanten en wat algoritmen bevat voor uiteenlopende handelingen die met collecties te maken hebben.

DigitalFormat

Een class dat gebruikt wordt om decimale getallen in een specifieke formaat weer te geven.

Comparator

Een class dat geïmplementeerd kan worden om het het aantal sorteer wijzen te verhogen van een TreeSet of een TreeMap.

Anonieme inner class

Een class dat volledig in de method wordt beschreven en waarvan de beschrijving van de class onmiddellijk volgt na new.

StringTokenizer

Een class dat wordt gebruikt om een string op te splitsen in verschillende delen, gebaseerd op een scheidingsteken.

BigDecimal

Een class die decimale getallen exact kam weergeven doordat het werkt met meer dan 16 beduidende cijfers.

Singleton

Een class die speciaal geconstrueerd is om maar één object toe te laten.

Subclass

Een class gebaseerd op een bestaande class.

Generic class

Een class met een of meerdere parameters.

StringBuffer

Een class voor tekst dat wel concatenations toelaat.

Abstract class

Een class waarvan geen objecten geïnstantieerd kunnen worden.

Superclass

Een class waarvan overgeërfd wordt.

Collection framework

Een framework dat bestaat uit interfaces en bijhorende implementaties zodat er gewerkt kan worden met een reeks van objecten.

LinkedHashMap

Een gelinkte HashMap waarbij de entry's onderling ook verbonden zijn door 2 referenties.

Comparable<T>

Een generieke interface voor de method compareTo().

JPS

Een html-pagina waarin Java wordt aangeroepen.

HashSet

Een implementatie van Set dat intern gebruik maakt van een Hashtable om de elementen op te slaan.

LinkedHashSet

Een implementatie van de Set dat intern gebruik maakt van een combinatie van een Hashtable en een LinkedList.

TreeSet

Een implementatie van de SortedSet, waarbij de sortering bepaald wordt door de method compare() van de objecten.

Comparator-functieobject

Een instantie van een class dat de Comparator interface implementeert en doorgegeven wordt aan een TreeSet of TreeMap via één van zijn constructors

Set

Een interface afgeleid van de Collection interface dat geen dubbele waarden kan bevatten.

List

Een interface afgeleid van de Collection interface waarbij de volgorde van toevoegen blijft behouden, dat geen dubbele elementen kan bevatten, waarbij elk element een integer positie in de verzameling heeft.

SortedMap

Een interface afgeleid van de Map interface. De key-value paren zijn gesorteerd volgens de key. Het kan geen dubbels bevatten.

LinkedList

Een lijst die bestaat uit objecten die aan elkaar gekoppeld zijn door middel van referenties.

HashMap

Een map waarbij de plaats van de entry-objecten bepaald wordt door de hashcode van de key.

Final method

Een method dat niet meer overriden kan worden.

Instantiëren

Een object van een bepaalde class creëren.

Key-value paar

Een paar dat bestaat uit twee gegevens: een sleutel en een waarde.

Type parameter

Een parameter dat staat voor een nog niet bekende type en als parameter gebruikt wordt in een generic class.

Method overriding

Een subclass een eigen variant geven van een bestaande method uit de superclass.

Hashcode

Een waarde dat berekend wordt adhv de waarde(n) van een object.

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)

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)

When can super() be called.

Only the FIRST line of the constructor.

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.

equality operators

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

Nesting

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

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.

Head pointer (GIT)

Points to the current branch.

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.

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

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

System.out.println("Hello")

Prints Hello to console on a new line.

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

Private, Default, Protected, and Public.

Inheritance*

Process where one object acquires the properties of another.

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

Program compiles and runs properly.

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

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

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

Protected

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.

package

Puts the code into a package — a collection of logically related definitions.

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.

Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (size < capacity && value > 0) { a[size] = value; } 1. Reads up to 3 values and places them in the array in the unused space. 2. Reads one value and places it in the remaining first unused space endlessly. 3. Reads up to 3 values and inserts them in the array in the correct position. 4. Crashes at runtime because it tries to write beyond the array.

Reads one value and places it in the remaining first unused space endlessly.

Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (size < capacity && value > 0) { a[size] = value; size++; value = cin.nextInt(); } 1. Reads one value and places it in the remaining first unused space endlessly. 2. Crashes at runtime because it tries to write beyond the array. 3. Reads up to 3 values and places them in the array in the unused space. 4. Reads up to 3 values and inserts them in the array in the correct position.

Reads up to 3 values and places them in the array in the unused space.

Batch processing (JDBC)

Reduce overhead by executing a large number at once.

Class=Blueprint

Just like how one blueprint (class) is used to create several similar, but different houses (objects)

numChars = name1.length();

// returns the number of characters name1 contains

Boolean Expressions

A boolean expression often uses one of Java's equality operators or relational operators, which all return boolean results: Note the difference between the equality operator (==) and the assignment operator (=)

Boolean

A boolean value represents a true or false condition (1 bit) The reserved words true and false are the only valid values for a boolean type boolean done = false; A boolean variable are usually used to indicate whether a particular condition is true, such as whether the size of a dog is greater than 60

Assignment Conversion

Assignment conversion occurs when a value of one type is assigned to a variable of another Only widening conversions can happen via assignment

Logical Operators

They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands)

The Import Statement

Why didn't we import the System or String classes explicitly in earlier programs? All classes of the java.lang package are imported automatically into all programs It's as if all programs contain the following line: import java.lang.*; The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported

Java Reserved Words

You cannot use use reserved words for your own names (Java identifiers)

Charachter Strings

A string literal is represented by putting double quotes around the text examples: "I Rule!" "The World" "123 Main Street" "X" "" literal is an explicit data (constant) value used in a program Every character string is an object in Java, defined by the String class Every string literal represents a String object A string literal can contain any valid characters, including numeric digits, punctuation, and other special characters.

Variables

A variable is a name for a location (a chunk) in memory that holds a value (a fixed type of data) Variables come in two flavors: primitive and reference primitive: integer (such as 1, 2,...), floating point number (such as 1.2, 3.5, etc.), boolean (true or false) and char (such as 'A', 'B',...) reference: "address" of an object that resides in memory A variable declaration specifies the variable's name and the type of information that it will hold

Categorize each of the following situations as a compile-time error, run-time error, or logical error.

A. Multiplying two numbers why you mean to add them. logical error B. Dividing by zero run-time error C. Forgetting a semicolon at the end of a programming statement compile-time error D. Spelling a word incorrectly in the output logical error E. Producing inaccurate results logical error F. Typing { when you should have typed a ( compile-time error

Bit Permutations

Each additional bit doubles the number of possible permutations Each permutation can represent a particular item N bits can represent up to 2^N unique items, so to represent 50 states, you would need 6 bits: 1 bit: 2^1 = 2 items 2 bits: 2^2 = 4 items 3 bits: 2^3 = 8 items 4 bits: 2^4 = 16 items 5 bits: 2^5 = 32 items Five bits wouldn't be enough, because 2^5 is 32. Six bits would give us 64 permutations, and some wouldn't be used.

String mutation example to put into Java

Even though we can't change String value or length, several methods of the String class return new String objects that are modified versions of the original

The string class

Every character string (enclosed in double quotation characters) is an object in Java defined by the String class Every character string can be used to create a string object Because strings are so common, we don't have to use the new operator to create a String object (special syntax that works only for strings) String name1 = "Steve Jobs"; It is equivalent to String name1 = new String("Steve Jobs");

The Main Method

In Java, everything goes in a class (object-oriented) After you compile the source code (.java) into a bytecode or class file (.class), you can run the class using the Java Virtual Machine (JVM) When the JVM loads the class file, it starts looking for a special method called main, and then keeps running until the code in main is finished

Each class declares Instance Variables and Methods (Unique Values for the Objects in the Class)

Instance variables: descriptive characteristics or states of the object Ex. students are an instance variable of a class Methods: behaviors of the object (the actual doing thing of each instance variable) Ex. doing homework or taking exams are the methods of the instance variable "student"

String Indexes

It is occasionally helpful to refer to a particular character within a string This can be done by specifying the character's numeric index The index begins at zero in each string In the string "Hello" H is at the index 0 and o is at the index 4

Expressions

Order of operations is applied: Multiplication, division, and remainder are evaluated before addition, subtraction, and string concatenation Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order Assignment operator is last

Scanner Class

It is often useful to design interactive programs that read input data from the user The Scanner class provides convenient methods for reading input values of various types A scanner object can be set up to read input values from various sources including the user typing values on the keyboard The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner(System.in); Once created, the Scanner object can be used to invoke various input methods, such as: String answer = scan.nextLine(); The nextLine method reads all of the input until the end of the line is found, and return it as one String

Who will do the Java compiling?

Javac is the complier, not Eclipse. Eclipse is the software that runs javac. The Java virtual machine (the executable response) is called java For one class... what is the mechanism that allows us to run it? Answer: we are using an existing object

Promotion Conversion

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

The Random Class

The Random class is part of the java.util package It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values nextFloat() generates a random number [0, 1) nextInt() generates a random integer over all possible int values (positive or negative) nextInt(n) generates a random integer [0, n-1]

Demo

The filename of the source file must be the same as the class name (###case sensitive###) java MyFirstApp (###not MyFirstApp.class###)


संबंधित स्टडी सेट्स

Anatomy Lecture Chapter 9 and terms

View Set

CSC251-N811 Exam2 Study Guide Chp7

View Set

Health: Developing Muscular Strength and Endurance

View Set

Communications Chapter 2 Vocabulary

View Set

Surveys, Samples, Experiments, Data Displays, Descriptive Statistics

View Set

Gran Maestros de la Pintura: Picasso

View Set

A&P 1- Chapter 4 - Tissue Level of Organization

View Set