JAVA FINAL 9

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

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

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.

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.

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

-20

-24 % -5 is ________.

-4

-24 % 5 is ________.

-4

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

...

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

...

Pass by reference

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

Pass by value

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

What is the difference between process and thread?

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

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

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

Which memory capacity is the largest?

12,000,000 megabytes

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

15

abstract window toolkit

ABT

What is an accessor?

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

9. Why is it critical that accumulator variables are properly initialized?

An accumulator is used to keep a running total of numbers. In a loop, a value is usually added to the current value of the accumulator. If it is not properly initialized, it will not contain the correct total.

event

An action that can trigger an event handler.

method

An application segment containing statements that perform a task.

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

A color image is broken down into individual pixels (points), each of which is represented by

3 values denoting the intensity of red, green, and blue in the image

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

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

What is blank final variable?

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

String.valueOf

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

String.equals

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

setText

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

Instance Variable

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

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.

applet

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

String

A sequence of characters that represents text information.

String literal

A sequence of characters within double quotes.

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.

single-selection statement

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

2. Why should you indent the statements in the body of a loop?

By indenting the statements, you make them stand out from the surrounding code. This helps you to identify at a glance the statements that are conditionally executed by a loop.

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

Interface

Een abstracte class waarin alleen abstracte methods en eventueel publieke constanten opgenomen zijn.

Abstract class

Een class waarvan geen objecten geïnstantieerd kunnen worden.

Final class

Een class waarvan niet meer overgeërfd kan worden.

Superclass

Een class waarvan overgeërfd wordt.

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.

Hashcode

Een waarde dat berekend wordt adhv de waarde(n) van een object.

Bounded wildcard

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

Synchrinized wrapper

Een wrapper class die een object thread safe maakt

comment (//)

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

23. True or False: One limitation of the for loop is that only one variable may be initialized in the initialization expression.

F

26. True or False: To calculate the total number of iterations of a nested loop, add the number of iterations of all the loops.

F

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

False

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

False

________provides an integrated development environment (IDE) for rapidly developing Java programs. Editing, compiling, building, debugging, and online help are integrated in one graphical user interface.

Java IDE

________ consists of a set of separate programs for developing and testing Java programs, each of which is invoked from a command line.

Java JDK

JSE API

Java Standard Edition Application Programming Interface Libraries

What is the JVM?

Java Virtual Machine.

________is a technical definition of the language that includes the syntax and semantics of the Java programming language.

Java language specification

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.

Java portability

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

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

No

Is it legal to use .super in static methods?

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

Can you statically import a package?

No, you can only import classes statically.

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

No.

Does Java have multiple inheritance?*

No. Instead deal with interfaces.

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

That classes toString.

What does it mean if a string is immutable?

That it cannot be changed once it is created.

message dialog

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

class name

The identifier used as the name of a class.

destructive

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

int value

The variable type that stores integer values.

5. This is a variable that controls the number of iterations performed by a loop. a. loop control variable b. accumulator c. iteration register variable d. repetition meter

a

output JTextField

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

What is a mutator?

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

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.

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

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

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

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

Method

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

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 variable

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

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

&&

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

If two variables contain aliases of the same object then

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

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

Java ________ can run from a Web browser.

applets

main class

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

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

ar[0]

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

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

binary search

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

two-dimensional array

array with an array at each element in the array

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

7. The do - while loop is this type of loop. a. pretest b. posttest c. prefix d. postfix

b

2. What will the println statement in the following program segment display? int x = 5; System.out.println(++x); a. 5 b. 6 c. 0 d. None of these

b. 6

10. This type of loop always executes at least once. a. while b. do - while c. for d. any of these

b. do - while

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

orphaned data

data that isn't referenced anywhere

A Java variable is the name of a

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

variable

data value that can change

primitive data type

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

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

The line of Java code "// System.out.println("Hello");" will

do nothing

Transaction processing (JDBC)

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

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

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

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

final double MAX_LENGTH = 99.98;

Consider a method defined with the header: public void foo(int a, int b). Which of the following method calls is legal? 1) foo(0, 0.1); 2) foo(0 / 1, 2 * 3); 3) foo(0); 4) foo( ); 5) foo(1 + 2, 3 * 0.1);

foo(0 / 1, 2 * 3);

Close Window (GUI)

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

The main difference between a frame and a panel is

frames can have a title bar; panels cannot

Hamcrest

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

memory

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

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

generalization and specialization

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

getMessage

overloading a method

giving more than one meaning to a method name

To declare an int variable number with initial value 2, you write

int number = 2;

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

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

IDE

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

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

What is super()?

it calls the superclass constructor.

If a method does not have a return statement, then

it must be a void method

what is the objects state

its how the object reacts when you invoke those methods

Which JDK command is correct to run a Java application in ByteCode.class?

java ByteCode

Which library package would you import to use NumberFormat and DecimalFormat?

java.text

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

java.util

How do you run a program using commands.

javac ClassName.java java ClassName

CH13: The ListSelectionListener interface is in this package.

javax.swing.event

Object-Oriented Programs

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

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.

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

long

count-controlled loop

loop body is executed a fixed number of times

posttest loop

loop body is executed at least once, then condition is tested

sentinel-controlled loop

loop body is executed until a certain condition is met

Computer can execute the code in ________.

machine language

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

main memory

Instance data for a Java class

may be primitive types or objects

The speed of the CPU is measured in ________.

megahertz gigahertz

object reference

memory location of an object

The word println is a(n)

method

class method

method defined for a class

instance method

method defined for an object

Having multiple class methods of the same name where each method has a different number of or type of parameters is known as

method overloading

exception thrower

method that may directly or indirectly throw an exception

Every letter in a Java keyword is in lowercase.

true

CH13: You use this method to place a menu bar on a JFrame.

setJMenuBar

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

boolean

type with possible values of true of false

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

unchected exceptions

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

class data value

used to represent information shared by all instances or to represent collective information about instances

argument

value passed into an object

CH13: A list selection listener must have this method.

valueChanged

Which of the following would return the last character of the String x? 1) x.charAt(0); 2) x.charAt(last); 3) x.charAt(length(x)); 4) x.charAt(x.length( )-1); 5) x.charAt(x.length( ));

x.charAt(x.length( )-1);

The String class' compareTo method

yields 0 if the two strings are identical

Object Oriented

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

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

"FRINK ZIPPI"

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

$343 radius

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.

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

'4'

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

'o'

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

'x' 120

Preincrement

++counter

Given the following assignment statement, which of the following answers is true regarding the order that the operators will be applied based on operator precedence? a = (b + c) * d / e - f;

+, *, /, -

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

How can I set a cookie in JSP?

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

What are Predefined variables or implicit objects?

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

What is source and listener?

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

ANT

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

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

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

volatile

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

Instance variables

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

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

-- comments ** comments **

Predecrement

--counter

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

0 and 1

What does element indexing start at?

0.

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

0.0139

Binary numbers are composed entirely of

0s and 1s

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

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

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

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

Suppose you have the following declaration. char[] nameList = new char[100]; Which of the following range is valid for the index of the array nameList. (i) 1 through 100 (ii) 0 through 100 1. Both are invalid 2. Only (i) 3. None of these 4. Only (ii)

1. Both are invalid

Black box Steps

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

TDD Mantra

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

3 different groups of patterns

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

Interface rules

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

Refactoring Techniques

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

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

1. Finds the position of the smallest value in a.

An object is a(n) ____ of a class. 1. instance 2. method 3. field 4. constant

1. Instance

4 heavyweight Swing components

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

Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (value > 0) { a[size] = value; size++; value = cin.nextInt(); } 1. May crashe at runtime because it can input more elements than the array can hold 2. Reads up to 3 values and inserts them in the array in the correct position. 3. Reads one value and places it in the remaining first unused space endlessly. 4. Reads up to 3 values and places them in the array in the unused space.

1. May crashe at runtime because it can input more elements than the array can hold

Levels of synchronization

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

What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 1; if (j > 2) alpha[j - 1] = alpha[j] + 2; } 1. None of these 2. alpha = {1, 2, 3, 4, 5} 3. alpha = {1, 5, 6, 7, 5} 4. alpha = {4, 5, 6, 7, 9}

1. None of these

If a class's only constructor requires an argument, you must provide an argument for every ____ of the class that you create. 1. object 2. type 3. parameter 4. method

1. Object

Suppose you have the following declaration. double[] salesData = new double[1000]; Which of the following range is valid for the index of the array salesData. (i) 0 through 999 (ii) 1 through 1000 1. Only (i) 2. None of these 3. Both are invalid 4. Only (ii)

1. Only (i)

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

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

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

What does the following loop print? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = a[0]; for (int i = 1; i < len; i++) if (a[i] > x) x = a[i]; System.out.println(x); 1. 36 2. 6 3. 12 4. 1

3. 12

What does the following loop print? int[] a = {6, 9, 1, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] < a[x]) x = i; System.out.println(x); 1. 6 2. 1 3. 2 4. 4

3. 2

What is the value of alpha[2] after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) alpha[j] = 2 * j + 1; 1. 1 2. 4 3. 5 4. 6

3. 5

The arguments in a method call are often referred to as ____. 1. concept parameters 2. constants 3. actual parameters 4. argument lists

3. Actual parameters

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

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

What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; for (j = 4; j >= 0; j--) { alpha[j] = j + 5; if (j <= 2) alpha[j + 1] = alpha[j] + 3; } 1. 9 2. 5 3. 8 4. 10

4. 10

What is the value of alpha[4] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 2; for (j = 1; j < 5; j++) alpha[j] = alpha[j - 1] + 3; 1. 5 2. 11 3. 8 4. 14

4. 14

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

4. 15

int[] array1 = {1, 3, 5, 7}; for (int i = 0; i < array1.length; i++) if (array1[i] > 5) System.out.println(i + " " + array1[i]); What is the output of the code fragment above? 1. 0 3 2. 7 3 3. 5 1 4. 3 7

4. 3 7

What is the value of alpha[2] after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) alpha[j] = 2 * j + 1; 1. 4 2. 6 3. 1 4. 5

4. 5

double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is in vals[2][1]? 1. 3.3 2. 3.5 3. 1.3 4. 5.3

4. 5.3

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}

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

Type parameter

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

________ is the Java assignment operator.

=

What is the difference between = and ==?

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

1. What will the println statement in the following program segment display? int x = 5; System.out.println(x++); a. 5 b. 6 c. 0 d. None of these

A

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.

input JTextField

A JTextField used to get user input.

Procedural

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

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.

single precision

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

double precision

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

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

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

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

15

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

15

char

16 bit unicode character

short

16 bit, useful if memory an issue

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

18.0

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

2

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

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

25

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

3

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

A boolean value

Boolean

A boolean value represents a true or false condition (1 bit) The reserved words true and false are the only valid values for a boolean type boolean done = false; A boolean variable are usually used to indicate whether a particular condition is true, such as whether the size of a dog is greater than 60

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

++ (unary increment operator)

Adds one to an integer variable.

19. When writing data to a file, what is the difference between the print and the println methods?

After the println method writes its data, it writes a newline character. The print method does not write the newline character.

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.

Can we treat all types of exceptions the same?

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

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

Diamonds

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.

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.

What does the NEW keyword do?

Allocates new space in memory.

dot separator

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

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.

Comparator class als inner class

Een Comparator class integreren in een andere class.

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.

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.

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.

Enumeration

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

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.

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.

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.

Abstract method

Een method dat niet uitgevoerd kan worden.

Entry

Een object in een LinkedList

Instantiëren

Een object van een bepaalde class creëren.

Generics

Een oplossing voor het probleem van typecasting bij Collections enMaps.

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.

ArrayList

Een resizable array implementatie van de List interface.

Method overriding

Een subclass een eigen variant geven van een bestaande method uit de superclass.

Package

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

Unmodifiable wrapper

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

Data member

Eigenschap van een class

The condition Exp1 ^ exp2 evaluates to true when ____.

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

Wrapper class

Elke primitive data type heeft een bijhorende class

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.

The following code fragment reads in two numbers: (Choose all that apply.) Scanner input = new Scanner(System.in); int i = input.nextInt(); double d = input.nextDouble(); What are the correct ways to enter these two numbers?

Enter an integer, a space, a double value, and then the Enter key. Enter an integer, two spaces, a double value, and then the Enter key. Enter an integer, an Enter key, a double value, and then the Enter key.

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.

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.

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.

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.

Event-Driven Programing

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

binary operator

An operator that requires two operands.

unary operator

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

Loop

Another general name for a repetition statement.

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.

20. True or False: The do-while loop is a pretest loop.

F

21. True or False: The for loop is a posttest loop.

F

22. True or False: It is not necessary to initialize accumulator variables.

F

Packages

For purposes of accessing them, classes in the Java API are grouped into packages

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.

GUI

Graphical User Interface

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.

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

False

Staging area

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

Dynamic binding

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

Upcasting

Het proces om een object van een subclass te beschouwen als een object van zijn superclass.

Type casting

Het type van een variabele omzetten in een andere type.

Wildcard

Het type wordt helemaal niet vastgelegd; het wordt beschouwd als een joker.

JTextField

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

What is composition?

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

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

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

CH12: FileNotFoundException inherits from ________.

IOException

JOptionPane.WARNING_MESSAGE

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

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

case sensitive

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

What is method overloading?

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

What is method overriding?

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

The body of a while statement executes _____.

If it's condition is true

2

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

Basic Program Execution

If there are errors the compiler will complain and not let us go onto the next step. We must trace back to the source and fix the problem in our code. It's important to understand why you're getting errors. LOOK IT UP debuggers can help you find errors in your code

Church-Turing Thesis

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

What is final variable?

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

Double

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

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

ImageIcon

4. Why are the statements in the body of a loop called conditionally executed statements?

Because they are only executed when a condition is true

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

Because they will only be called from methods inside of Rational

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

Becauseof ambiguity.

Final

Behoudt gedurende het hele programma dezelfde waarde

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)

What is static block?

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

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

Both are false.

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

Both expressions are true.

Casting Conversion

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

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

It becomes part of the component and is laid out automatically

is true regarding the mod operator, %

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

What happens when a class final?

It cannot be extended?

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

It cannot be overloaded.

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.

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 is the function of a frame's pack method?

It sets the size appropriately for display

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

It throws an exception which must be caught.

short s = (short)9; int i = 8; s+=i; Will this compile,if so what is the output?

It will compile because += and other operators like that do a cast. So s+=i; is s = (short)(s+i);

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

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

iterator()

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

When an argument is passed to a method,

Its value is copied into the method's parameter variable

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

JCheckBox Text

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

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

JOptionPane.ERROR_MESSAGE

The ________ method displays a message dialog box.

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

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

JRadioButtonMenuItem

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

JTextArea

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

JTextArea

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

JTextField

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.

________is Architecture-Neutral.

Java

________is interpreted.

Java

________is an object-oriented programming language.

Java C++

The expression "Java " + 1 + 2 + 3 evaluates to ________.

Java 123

________ contains predefined classes and interfaces for developing Java programs.

Java API

JDK

Java Development Kit

What is the JDK?

Java Development Kit.

What is the function of the dot operator?

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

Methods are commonly used to

Break a problem down into small manageable pieces

methods are commonly used to

Break a problem down into small manageable pieces.

Continuous Integration (CI)

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

CruiseControl

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

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

Dialog Box

GUI object resembling a window on which messages can placed

event source

GUI object where the event occurs

Windowed Application

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

Property

Gedrag van een class

Classpath

Geeft aan waar je andere zelfgeschreven classes vindt

Quick Check: The Random Class

Given a Random object reference named gen, what range of values are produced by the following expression?

Quick Check: Booelan Expressions

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

Swing

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

Abstract Windowing Toolkit (AWT)

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

Event Listeners (Observer?)

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

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

MAX_VALUE COUNT

Benefits of Encapsulation*

Maintainability, Flexibility and Extensibility.

How do you make a constant.

Make a variable with final and static modifiers.

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

Make the class final

join (Threads)

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

How many types of memory areas are allocated by JVM?

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

The ________ method returns a raised to the power of b.

Math.pow(a, b)

Since you cannot take the square root of a negative number, you might use which of the following instructions to find the square root of the variable x?

Math.sqrt(Math.abs(x));

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

gigabyte

Maximum memory size is 2^30 memory bytes

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

Merge

Difference between method Overloading and Overriding.

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

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

Method body

Finalize

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

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.

Setter

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

Getter

Method om de waarde van een datamember op te halen.

What are the two things classes have?

Methods and Variables.

Event Handlers

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

Mocking

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

Abstract Data Types

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

formatting

Modifying the appearance of text for display purposes.

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

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

NIC

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.

Static

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

Immutable

Niet te wijzigen

Are arrays used only for primitives?

No

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

No

Can a local variable be static?

No

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

No

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

No

Can an abstract method be final?

No

Can an abstract method be static?

No

Can their be any duplicate cases in a switch statement?

No

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

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

No

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

No

Is it legal to use .this in static methods?

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

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

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

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

No - The parameters have to be different.

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

No - You need the new keyword

Can you override Strings methods if yes why?

No because String is a final class.

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

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

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

NumberFormatException

heap sort

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

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

Object

What does String Buffer extend?

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.

Which class is the superclass for every class.

Object class.

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

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.

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

________ is the brain of a computer.

CPU

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.

Attributes (ANT)

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

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.

Decimal, Text

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

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

Date birthday=new Date

Encapsulation

De buitenwereld heeft geen rechtstreekse controle over de inhoud.

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.

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.

dir command

Command typed in a Command Prompt window to list the directory contents.

git commit

Commits staged files to Repo.

run

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

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.

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.

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

If method A calls Method B, and method B calls method C, and method C calls method D, when method D finishes, what happens?

Control is returned to method C

JTextArea

Control that allows the user to view multiline text.

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

Counter

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

Counts the even elements in a.

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

Counts the even elements in a.

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

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

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

Loop-Continuation Condition

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

What does the finally keyword do?

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

bug

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

Repetition Statement

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

What does the term generic mean?

A generic type is a parameterized type - a type

block

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

statements

A line of java code.

Header

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

variable

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

Infinite Loop

A logical error in which a repetition statement never terminates.

NOT (!) operator

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

XOR operator (^)

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

OR operator (||)

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

AND operator (&&)

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

breakpoint

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

Refactor - encapsulate collection

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

Refactor - replace error code with exception

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

getText

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

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.

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.

floating-point number

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

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

Public

Accessible by all.

Protected

Accessible if in same package.

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

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

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

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

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

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

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

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

To print the last element in the array named ar, you can write : A. System.out.println(ar[length-1]); B. System.out.println(ar[length()-1]); C. System.out.println(ar[ar.length-1]); D. System.out.println(ar[ar.length]);

System.out.println(ar[ar.length-1]);

how to pass an object to a method

System.out.println(new Date()):

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

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

19. True or False: The while loop is a pretest loop.

T

24. True or False: A variable may be defined in the initialization expression of the for loop.

T

25. True or False: In a nested loop, the inner loop goes through all of its iterations for every iteration of the outer loop.

T

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.

@Test(timeout = T)

Test fails if runs longer than T milliseconds.

@Test(expected = X.class)

Test is expected to throw exception X.

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

Test.java

Glass box

Testing code (can see code)

Black box

Testing to specifications (code unseen)

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.

*decision*

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

Instantiation

The act of creating a new instance of an object.

workflow

The activity of a portion of a software system.

RGB value

The amount of red. green and blue needed to create a color.

Title bar

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

initialization value

The beginning value of a variable.

Class

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

{}

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

semicolon ( ; )

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

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

Overriding

Operator && __.

Performs short-circuit evaluation

Task (ANT)

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

FlowLayout

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

Nesting

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

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.

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

Protected

Executable

Pseudocode usually only describes ____ lines of code.

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

Batch processing (JDBC)

Reduce overhead by executing a large number at once.

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.

Which of the following is not part of a method call? A. Return type B. Parentheses C. Method name D. All of the above are part of a method call

Return type

executeQuery (SQL command)

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

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.

Integer.parseInt

Returns the integer equivalent of a String.

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

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.

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.

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

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

13. What is the advantage of using a sentinel?

Sometimes the user has a list of input values that is very long, and doesn't know the number of items there are. When the sentinel value is entered, it signals the end of the list, and the user doesn't have to count the number of items in the list.

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

mantissa

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

isSelected

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

BorderLayout

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

jdb

Starts the Java debugger when typed at the Command Prompt.

Static Variables and Threads

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

What do static imports import?

Static variables and static methods.

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

StoreCustomer

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.

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

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;

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

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

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.

Signature rule (subtypes)

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

Properties rule (subtypes)

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

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the data type of the array above? 1. num 2. int 3. char 4. list

int

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } What is the return type of the method above?

int

You can create an array of three integers by writing :

int ar[] = new int[3];

this()

invokes the constructor.

local variable

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

The Swing package

is complementary to the AWT

K&R Style

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

The JDK command to compile a class in the file Test.java is

javac Test.java

reconstruction step

last child is moved to root node, check and update the heap to satisfy the value-relationship constraint starting at the root

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

list selection event

LAN

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

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

local variable

Consider a sequence of method invocations as follows: main calls m1, m1 calls m2, m2 calls m3 and then m2 calls m4, m3 calls m5. If m4 has just terminated, what method will resume execution?

m2

run()

main method for an individual thread

control statement

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

ASCII

maps characters to a number; human and machine readable

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

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.

exception handling

mechanism used to improve a program's robustness

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

constructor

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

The behavior of an object is defined by the object's

methods

Things an object can do are called?

methods

In order for a computer to be accessible over a computer network, the computer needs its own

network address

Internet Protocol

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

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

never

Which of the following reserved words in Java is used to create an instance of a class? 1) class 2) public 3) public or private, either could be used 4) import 5) new

new

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

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.

Standard Output Device

normally the monitor

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

Properties

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

What is wrong with the following method call? displayValue (double x);

The data type of the argument x should not be included in the method call

The header of a value-returning method must specify this.

The data type of the return value

The header of a value-returning method must specify this. A. The method's local variable name B. The data type of the return value C. The name of the variable in the calling program that will receive the returned value D. All of the above

The data type of the return value

What is the default value of the local variables?

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

setBounds

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

Logical NOT

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

straight-line form

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

Program Development

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

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

String Concatenation Operator

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

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

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

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)

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.

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.

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

While

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

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

Are StringBuffer/StringBuilder final classes?

Yes

Can an abstract class extend a concrete one?

Yes

Can an abstract class have a constructor?

Yes

Can array use all of the methods that object can?

Yes

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

Yes

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

Yes

Can you forget some parts of a for loop?

Yes

Can you have an array of objects?

Yes

15. Describe a programming problem requiring the use of nested loops?

There are many possible examples. One example is a program that asks for the average temperature for each month, for a period of five years. The outer loop would iterate once for each year and the inner loop would iterate once for each month.

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

Can you use short in a switch statement?

Yes

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

Yes

Do you have to initialize a local variable?

Yes

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

Yes

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

Yes

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 you have virtual functions in Java?

Yes, all functions in Java are virtual by default.

Another way to generate a Random Number

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

double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is the value of vals[4][1] in the array above? 1. 7.1 2. There is no such value. 3. 7.3 4. 1.1

There is no such value.

Can we execute a program without main() method?

Yes, one of the way is static block

Can we intialize blank final variable?

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

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

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

Can you declare the main method as final?

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

Can we override the overloaded method?

Yes.

arithmetic operators

These operators are used for performing calculations.

Logical Operators

They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands)

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.

if...else statement

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

-g compiler option

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

multiplication operator

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

% (remainder operator)

This operator yields the remainder after division.

assignment operator

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

if statement

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

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.

CH12: All exception classes inherit from this class.

Throwable

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

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.

initialization

To start, the first value given to a variable

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

primative types or built in type

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

Is the String class final?

Yes

Is the instance block executed before the constructor?

Yes

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

Yes

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

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

print

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

set

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

Java Reserved Words

You cannot use use reserved words for your own names (Java identifiers)

23. How do you open a file so that new data will be written to the end of the file's existing data?

You create an instance of the FileWriter class to open the file. You pass the name of the file (a string) as the constructor's first argument, and the boolean value true as the second argument. Then, when you create an instance of the PrintWriter class, you pass a reference to the FileWriter object as an argument to the PrintWriter constructor. The file will not be erased if it already exists and new data will be written to the end of the file.

Refactor - split loop

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

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

You'll likely receive a syntax error

EJB

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

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

^

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.

Hashcode (GIT)

Uniquely identify each commit.

Input Tokens

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

setText

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

JInternalFrame

Use for Multiple Document Interface (MDI)

Observable

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

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

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

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.

relational operator

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

Throwable

Used to define own exceptions.

showMessageDialog

Used to display a message dialog: JOptionPane.____.

JDBC (Java Database Connectivity)

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

ResultSet (JDBC)

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

JTextField.CENTER

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

JTextField.LEFT

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

JTextField.RIGHT

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

11. This expression is executed by the for loop only once, regardless of the number of iterations. a. initialization expression b. test expression c. update expression d. pre-increment expression

a

13. This is a special value that signals when there are no more items from a list of items to be processed. This value cannot be mistaken as an item from the list. a. sentinel b. flag c. signal d. accumulator

a

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

a Dimension object

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

double

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

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

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.

protocol

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

A containment hierarchy is

a nested collection of relationships among containers

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

a one-way link

Logical or semantic errors (Error Type 3/3)

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

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

Every statement in Java ends with ________.

a semicolon (;)

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

Mistyping "println" as "printn" will result in

a syntax error

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

In Java a variable may contain

a value or a reference

If you want to draw a red circle inside of a green square in an applet where the paint method is passed a Graphics object called page, which of the following sets of commands might you use?

page.setColor(Color.green); page.fillRect(50, 50, 100, 100); page.setColor(Color.red); page.fillOval(60, 60, 80, 80);

Copy Constructor

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

Parameter(overloaded) constructor

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

procedure

performs an action but doesn't return anything;

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

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

The expressions that are passed to a method in an invocation are called

actual parameters

actual parameter

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

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

add

CH13: To display a scroll bar with a JList component, you must _________.

add the JList component to a JScrollPane component

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

truncating

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

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.

GridLayout

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

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

all of these

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

all of these

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

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

Events

allow components to notify each other when something happens.

Java.text's NumberFormat class includes methods that

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

Inheritance

allows code defined in one class to be reused in other classes.

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] = 2 * j; if (j % 2 == 1) alpha[j - 1] = alpha[j] + j; } 1. alpha = {0, 2, 4, 6, 8} 2. alpha = {0, 2, 9, 6, 8} 3. alpha = {3, 2, 9, 6, 8} 4. alpha = {0, 3, 4, 7, 8}

alpha = {3, 2, 9, 6, 8}

What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 5; if (j % 2 == 1) alpha[j - 1] = alpha[j] + 2; }

alpha = {8, 6, 10, 8, 9}

An API is

an Application Programming Interface

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

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.

Private Keyword

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

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.

Syntax Error

an error of language resulting from code that does not conform to the syntax of the programming language

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

Map

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

Unicode

an international system of character representation

instance

an object of a particular class

What is a Collection?

an object that stores multiple elements in a single unit

instance

an object; created from a class

software life cycle

analysis, design, coding, testing, operation

White space

and combination of nonprinting characters

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

ar[2]

Arrays

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

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

private

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

private

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;

CH11: Fields in an interface are ________.

both final and static

Java is an example of

both high-level language and fourth generation language

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

bounding box

A block is enclosed inside ________.

braces

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

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.

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

bytecodes

3. In the expression number++ , the ++ operator is in what mode? a. prefix b. pretest c. postfix d. posttest

c

9. This type of loop has no way of ending and repeats until the program is interrupted. a. indeterminate b. interminable c. infinite d. timeless

c

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

c

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

c = a.concat(b);

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

call stack

What is this()?

calls a constructor in the same class?

this.method()

calls an instance method in the current class.

Architecturally Neutral

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

A method that has the signature void m(int[] ar) : A. can change the values in the array ar B. cannot change the values in the array ar C. can only change copies of each of the elements in the array ar D. None of these

can change the values in the array ar

If you pass the first element of the array ar to the method x() like this, x(ar[0]); the element ar[0] :

cannot be changed by the method x()

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)

Of the following types, which one cannot store a numeric value? 1) int 2) byte 3) float 4) char 5) all of these can store numeric values

char

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

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

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

checked exceptions

postcondition assertion

checks a condition that must be true after method execution

assertion

checks for a condition that must be true

precondition assertion

checks for a condition that must be true before a method is executed

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.

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

class

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

Postincrement

counter++

Postdecrement

counter--

Clean Build

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

In Java, "instantiation" means

creating a new object of the class

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

currentStockVal

15. To open a file for reading, you use the following classes. a. File and Writer b. File and Output c. File and Input d. File and Scanner

d

Example of three references and two object

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

Using getCurrencyInstance( ) formats a variable, automatically inserting

decimal point for cents dollar sign percent sign

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

overload a method

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

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

operation

deployment and maintenance

Class Definition

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

object-oriented programming

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

Depend (ANT)

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

JOptionPane is a class that provides GUI

dialog boxes

If you attempt to add an int, a byte, a long, and a double, the result will be a ________ value.

double

Instance

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

Encapsulation

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

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

Enum

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

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

equals

exception

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

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

short circuit evaluation

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

delegation based event model

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

analysis

feasibility study; result is a requirements specification

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

final

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

findArea totalLength

zero-indexing

first element begins at zero as opposed to one

flops

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

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

floppy disk hard disk flash stick

event-driven programming

flow of execution is determined by events;

instruction register

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

Memory Address Register (MAR)

holds the address of the cell to be fetched or stored

A class' constructor usually defines

how an object is initialized

Which of the following is a legal Java identifier? 1) i 2) class 3) ilikeclass! 4) idon'tlikeclass 5) i-like-class

i

To use JOptionPane in your program, you may import it using:

import javax.swing.JOptionPane; import javax.swing.*;

quick sort

in-place, divide-and-conquer, massively recursive sort; array is split in two parts based on a pivot point (one with elements larger than the pivot, one with elements smaller than the pivot) and is recursively repeated

array element

individual value in an array

pseudocode

informal programming language with English-like constructs modeled to look like statements in a java-like language

Arguments

information passed to a method so it can perform its task

Which of the following Applet methods is called automatically when the applet is first loaded? 1) Applet (the Applet's constructor) 2) init 3) start 4) getCodeBase 5) getImage

init

Suppose a Scanner object is created as follows: Scanner input = new Scanner(System.in); What method do you use to read an int value?

input.nextInt();

object

instance of exactly one class, and belongs to that class

Things an object knows about itself are called ?

instance variables

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

instanceof

Objects

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

instance data value

instances of the same class will possess the same set of data values

stored program concept

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

event handler

processes the events and determines what to do

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.

java.lang.Thread

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

the reserved words

public static void class

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.

Clock -hr: int -min: int -sec: int +Clock() +Clock(int, int, int) +setTime(int, int, int): void +getHours(): int +getMinutes(): int +getSeconds(): int +printTime(): void +incrementSeconds(): int +incrementMinutes(): int +incrementHours(): boolean +equals(Clock): boolean +makeCopy(Clock): void +getCopy(): Clock Which of the following would be a default constructor for the class Clock shown in the figure above? 1. public Clock(0, 0, 0) { setTime(); } 2. private Clock(10){ setTime(); } 3. public Clock(0) { setTime(0); } 4. public Clock(){ setTime(0, 0, 0); }

public Clock(){ setTime(0, 0, 0); }

Basic Enum class

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

The main method for a Java program is defined by

public static main(String[ ] args)

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

The main method header is written as:

public static void main(String[ ] args)

unchecked exceptions

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

construction phase

satisfy the structural constraint (numbers places in heap); satisfy the value relationship constraint (start w/ last parent node)

What is scope?

scope is the concept of the access granted to a variable depending on where it is seen. class level variables can be 'seen' or accessed anywhere within their given class whereas variables declared in the body of a method cannot be accessed from other methods in the same class.

Passing

sending arguments to a method

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

method

sequence of instructions that a class or an object follows to perform a task

loop

sequence of instructions that is executed repeatedly

SASD

sequential access storage device does not require that all units of data be identifiable via unique addresses; to find the data, we must search sequentially, asking "Is this what I'm looking for?"

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

sequential search

linear search

sequential search; n/2 comparisons; array is searched from the first position to the last position

Mutator methods typically begin with the word "____".

set

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)

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

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)

Program Statements

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

I/O buffer

small amount of memory that the I/O controller has

selection sort

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

A Java program is best classified as

software

computability

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

insertion sort

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

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.

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

A cast is required in which of the following situations? 1) using charAt to take an element of a String and store it in a char 2) storing an int in a float 3) storing a float in a double 4) storing a float in an int 5) all of these require casts

storing a float in an int

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

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

subclass

arithmetic/Logic Unit (ALU)

subsystem that performs such mathematical and logical operations as addition, subtraction, and comparison for equality; registers, interconnections between components, and ALU circuitry

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

sum += number; sum = sum + number;

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

super

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

super();

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

superclass

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

t (before main)

truth table

table used in logic to compute the functional values of logical expressions; this table has input columns that list all combination of true/false values and the corresponding outputs for those

class

template for instantiating objects; dictates what an object can or cannot do; defines the properties and behaviors for an object

Class

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

break statement

terminates switch statement; causes execution to continue from the statement following the switch statement

boolean expression

test condition

pretest loop

test is done before the execution of the loop body

Mocks

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

Stubs

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

Fakes

test objects with working methods but have limited functionality.

Dummies

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

protocol stack

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

Inheritance

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

Java API

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

Autoboxing is

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

Attributes

the characters that define an object as part of a class

Method Body

the code held bw the curly braces following the method

For a computer to communicate over the Internet, it must use

the combined TCP/IP protocol

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

Inheritance

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

The System.currentTimeMillis() returns ________.

the current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time)

formal parameter

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

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

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

what is a subclass?

the descendant of a superclass

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

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

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.

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

Boolean

true or false

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}

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.

The advantage(s) of the Random class' pseudo-random number generators, compared to the Math.random method, is that

you may create several random number generators you can generate random ints, floats, and ints within a range you can initialize and reinitialize Random generators

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 value will z have if we execute the following assignment statement? float z = 5 / 10;

z will equal 0.0

long

64 bit

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

76

One byte has ________ bits.

8

byte

8 bit, useful if memory an issue

byte

8 bits

Stop

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

Before

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

setHorizontalAlignment

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

Math.pow(2, 3) returns ________.

8.0

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

9

Comment

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

state button

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

newline

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

JLabel

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

JTextArea

Display textual data or accept large amounts of text input.

case sensitive

Distinguishes between uppercase and lowercase letters in code.

Default constructor

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

DNS

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

The ________ method parses a string s to a double value.

Double.parseDouble(s);

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

Editable

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

"0.0"

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

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

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.

Checkout

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

Software Patterns

- Reusable solution to common problem. - Description/Template

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

66

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 wrapper classes?

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

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

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

Generics

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

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

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

...

Call

...

Mismanaged threads result in

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

Javac

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

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.

Name and type

3. Every variable has a ________.

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.

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

int

32 bit

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

binary

A string of bits, Base 2.

empty string ("")

A string that does not contain any characters.

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

C++

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;

CLOB

Character Large OBject

Glass box steps

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

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

JOptionPane.ERROR_MESSAGE

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

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.

git init

Initialise an empty repository

Class=Blueprint

Just like how one blueprint (class) is used to create several similar, but different houses (objects)

format

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

static

Not belonging to a class or individual objects.

Danger of using GIT

Only one repository.

Another Example

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

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

Overloading

setEditable

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

setText

Sets the text property of the JTextArea component.

algorithm

Step by step process.

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

Multiplies

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

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.

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

bounds property

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

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

Quick Check: Nested Statements

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

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)

round off errors

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

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)

________ is an operating system.

Windows XP

How is an instance block wrote?

With two brackets outside of the main method.

Refactor - extract method

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

Book-Title

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

Class

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

Console Applications

character output to a computer screen in a DOS window

Instance

existing object of a class

Logic Error

occurs when a program compiles successfully but produces an error during execution

event

occurs when the user interacts with a GUI object

Methods in interfaces are automatically what?

public and abstract.

Which of the following is NOT a modifier?

return

Procedures

sets of operations performed by a computer program

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)

override

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

numChars = name1.length();

// returns the number of characters name1 contains

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

// used to demonstrate an output message

-25 % 5 is ________.

0

25 % 1 is ________.

0

Assume that x, y, and z are all integers (int) equal to 50, 20, and 6 respectively. What is the result of x / y / z?

0

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

0

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

30

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

37 % 6

24 % 5 is ________.

4

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

4

What does the following loop print? int[] a = {6, 1, 9, 5, 12, 7}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 1) x++; System.out.println(x); 1. 18 2. 2 3. 22 4. 4

4

What is the length of TEXT?

4

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

word is spelled incorrectly; parentheses is omitted.

6. Syntax errors occur for many reasons, such as when a(n) ____.

Size and location of component

6. The bounds property controls the ____.

Not changed

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

6 bits can be used to represent ________ distinct items or

64

setText

7. A Jlabel component displays the text specified by ____.

In straight-line form

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

KeyPressed

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

Components of a color

9. RGB values specify the ____.

int

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

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

99

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

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

API

Application Programming Interface; a code library for building programs

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.

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

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.

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.

Generic collections

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

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

compound boolean expressions

Combination of two conditionals that evaluate to true or false.

JComboBox

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

Which of the following statements is correct? 1) Every line in a program must end with a semicolon. 2) Every statement in a program must end with a semicolon. 3) Every comment line must end with a semicolon. 4) Every method must end with a semicolon. 5) Every class must end with a semicolon.

Every statement in a program must end with a semicolon.

DASD

Every unit of information has a unique address but the time needed to access the information depends on its physical location and the current state of the device. Stands for direct access storage device.

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

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

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

Everything from index 1 and up(Inclusive)

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

What happens when you divide 0 by 0?

Exception

What happens when you divide and Int by 0?

Exception

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 JOptionPane dialog icon typically used to caution the user against potential problems is the ____.

Exclamation point

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

Infinite

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

Infinity

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

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.

________ are instructions to the computer.

Software Programs

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.

JLabel

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

termination condition

The condition that stops the loop.

To improve readability and maintainability, you should declare ________ instead of using literal values such as 3.14159.

constants

When you write an explicit ____ for a class, you no longer receive the automatically written version.

constructor

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.

Layout managers are associated with

containers

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

Package

contains a group of built-in Java classes

Memory Data Registrar (MDR)

contains the data value being fetched or stored

control flow invariant

control must flow must flow invariably to a case

nested conditional

control statement within another control statement

reading a file

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

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

<

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.

Unchecked exception

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

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

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.

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

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

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

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

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

What is the difference between Array and vector?

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

What is the difference between Assignment and Initialization?

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

What is BDK?

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

Atomic Swing Components

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

What is the use of bin and lib in JDK?

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

Deadlock

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

Top Swing Level

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

Disadvantages of Centralised Servers

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

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

GIT

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

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 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 a cloneable interface and how many methods does it contain?

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

What is Domain Naming Service(DNS)?

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

What is JDBC?

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

What are JSP ACTIONS?

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

What is JSP?

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

What are JSP scripting elements?

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

What is a Jar file?

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

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

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)

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

What is servlet?

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

Why should we go for inter-servlet communication?

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

Encapsulation*

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

Disadvantages of TDD

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

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

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

What is the difference between set and list?

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

Starvation

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

What are the types of statements in JDBC?

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

Local Repository

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

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

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.

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.

Advantages of exceptions

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

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.

What are the states associated in the thread?

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

How to create and call stored procedures?

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

What are Transient and Volatile Modifiers?

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

What is URL?

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

What is UNICODE?

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

Disadvantages of the the Lock (version control)

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

What are Vector, Hashtable, LinkedList and Enumeration?

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

Central Repository

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

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.

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.

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

What is the difference between abstract class and interface?

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

What is difference between overloading and overriding?

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

What is the difference between Integer and int?

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

What are drivers available?

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

What 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

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

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

What is final, finalize() and finally?

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

What is finalize() method?

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

Checked exception

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

Timer

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

What is the lifecycle of an applet?

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

Object lock (synchronization)

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

Java

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

Queues

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

Lists

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

final

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

What modifiers may be used with top-level class?

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

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.

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.

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

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

Object-oriented programming

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

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

...

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

...

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

...

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

...

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

...

data access class

...

The extension name of a Java bytecode file is

.class

What are 5 method of the class object.

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

The extension name of a Java source code file is

.java

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

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

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

1) radius 4) findArea

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

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

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

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

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

1,3,4,6,7

What does the following loop print? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = a[0]; for (int i = 1; i < len; i++) if (a[i] < x) x = a[i]; System.out.println(x); 1. 1 2. 12 3. 6 4. 36

1. 1

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; How many components are in the array above? 1. 100 2. 0 3. 50 4. 99

1. 100

What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 5; for (j = 1; j < 5; j++) { if (j % 2 == 0) alpha[j] = alpha[j - 1] + 2; else alpha[j] = alpha[j - 1] + 3; } 1. 13 2. 15 3. None of these 4. 10

1. 13

double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} How many rows are in the array above? 1. 4 2. 0 3. 2 4. 3

1. 4

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the index number of the last component in the array above? 1. 99 2. 100 3. 0 4. 101

1. 99

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

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

1. Any number

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)

Redundant

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

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

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

Client/server programming (Daemon thread)

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

Subtype rules

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

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

1. Sums the even elements in a.

Test Driven Development (TDD)

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

Version control principles

1. The Lock 2. The Merge

Valid Identifier

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

The reference to an object that is passed to any object's nonstatic class method is called the ____. 1. this reference 2. magic number 3. literal constant 4. reference

1. This

setBackground

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

Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements replaces the first object in the collection with element? 1. a.set(0, element); 2. a.set(element, 0); 3. a.add(0, element); 4. a[0] = element;

1. a.set(0, element);

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

1. accessor

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

1. classification

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

1. constructor

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

1. constructor

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

1. nested

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

1. println(pete.toString());

To call a superclass method from a subclass method, when both methods have the same name and signature, prefix the call to the superclass method with: 1. super 2. the name of the superclass (that is, Person, if that is the name of the superclass) 3. no prefix is necessary. You cannot call an overridden superclass method from the subclass method you've overridden. 4. this 5. base

1. super

Which of the following expressions will yield 0.5? (Choose all that apply.) 1) 1 / 2 2) 1.0 / 2 3) (double) (1 / 2) 4) (double) 1 / 2 5) 1 / 2.0

1.0 / 2 (double) 1 / 2 1 / 2.0

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the value at index 10 of the array above?

10

What is the output of the following Java code? int[] alpha = {2, 4, 6, 8, 10}; int j; for (j = 4; j >= 0; j--) System.out.print(alpha[j] + " "); System.out.println();

10 8 6 4 2

Picture elements

10. Pixels are ____.

Print

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

At

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

int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the value of num.length in the array above? 1. 0 2. 100 3. 99 4. 101

100

What is the result of 45 / 4?

11

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

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

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

2, 3

Suppose that sales is a two-dimensional array of 10 rows and 7 columns wherein each component is of the type int , and sum and j are int variables. Which of the following correctly finds the sum of the elements of the fifth row of sales? 1. sum = 0; for(j = 0; j < 10; j++) sum = sum + sales[5][j]; 2. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[4][j]; 3. sum = 0; for(j = 0; j < 10; j++) sum = sum + sales[4][j]; 4. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[5][j];

2. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[4][j];

What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; for (j = 4; j >= 0; j--) { alpha[j] = j + 5; if (j <= 2) alpha[j + 1] = alpha[j] + 3; } 1. 8 2. 10 3. 9 4. 5

2. 10

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

2. 10

What is the value of alpha[4] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 2; for (j = 1; j < 5; j++) alpha[j] = alpha[j - 1] + 3; 1. 11 2. 14 3. 5 4. 8

2. 14

char[][] array1 = new char[15][10]; How many dimensions are in the array above? 1. 3 2. 2 3. 1 4. 0

2. 2

public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } How many constructors are present in the class definition above? 1. 3 2. 2 3. 1 4. 0

2. 2

Assume that two arrays are parallel. Assume the first array contains a person's id number and the second contains his or her age. In which index of the second array would you find the age of the person in the third index of the first array? 1. 2 2. 3 3. 1 4. It cannot be determined from the information given.

2. 3

int[] hits = {10, 15, 20, 25, 30}; copy(hits); What is being passed into copy in the method call above? 1. 10 2. A reference to the array object hits 3. The value of the elements of hits 4. A copy of the array hits

2. A reference to the array object hits

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

2. Any number

public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } Which of the following statements would you use to declare a new reference variable of the type Illustrate and instantiate the object with a value of 9 for the variable x? 1. Illustrate.illObject(9); 2. Illustrate illObject = new Illustrate(9); 3. Illustrate illObject(9); 4. illObject = Illustrate(9);

2. Illustrate illObject = new Illustrate(9);

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int z = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Where is identifier z (block three's local variable) visible? 1. In block three and main 2. In block three only 3. In two and block three 4. In one and block three

2. In block three only

Methods that require you to use an object to call them are called ____ methods. 1. accessor 2. instance 3. internal 4. static

2. Instance

The toString() method is automatically inherited from the __________________ class. 1. GObject 2. Object 3. java.lang 4. Root 5. Component

2. Object

Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following statements are valid in Java? (Assume that cin is Scanner object initialized to the standard input device.) (i) bigRect.length = cin.nextDouble(); bigRect.width = cin.nextDouble(); (ii) double l; double w; l = cin.nextDouble(); w = cin.nextDouble(); bigRect.set(l, w); 1. Only (i) 2. Only (ii) 3. Both (i) and (ii) 4. None of these

2. Only (ii)

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

2. Sums the even elements in a.

/

2. The ________ operator performs division.

Compiler

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

Which of the following is used to allocate memory for the instance variables of an object of a class? 1. the reserved word public 2. the operator new 3. the operator + 4. the reserved word static

2. The operator new

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

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

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

2. This program throws an exception.

Primitive

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

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

2. Will not compile (syntax error)

Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements adds the object to the beginning of the collection? 1. a[4] = element; 2. a.add(0, element); 3. a.insert(element); 4. a.add(element, 0); 5. a[0] = element;

2. a.add(0, element);

A variable comes into existence, or ____, when you declare it. 1. is referenced 2. comes into scope 3. overrides scope 4. goes out of scope

2. comes into scope

A(n) ____ constructor is one that requires no arguments. Student Response Value Correct Answer Feedback 1. write 2. default 3. class 4. explicit

2. default

Programmers frequently use the same name for a(n) ____ and an argument to a method simply because it is the "best name" to use. 1. block 2. instance field 3. variable 4. constant

2. instance field

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is NOT part of the heading of the method above? 1. static 2. int smaller; 3. minimum(int x, int y) 4. public

2. int smaller;

Clock ---------------------------------------- -hr: int -min: int -sec: int --------------------------------------- +Clock() +Clock(int, int, int) +setTime(int, int, int) : void +getHours() : int +getMinutes() : int +getSeconds() : int +printTime() : void +incrementSeconds() : int +incrementMinutes() : int +incrementHours() : int +equals(Clock) : boolean +makeCopy(Clock) : void +getCopy() : Clock ---------------------------------------- According to the UML class diagram above, which of the following is a data member? 1. printTime() 2. min 3. Clock() 4. Clock

2. min

To access the name instance variable from inside a method defined in the Student class, name must use the _____________ modifier. (We'll ignore the default package-private access if no modifier is used.) 1. public 2. protected or public 3. private or protected 4. private 5. protected 6. Any of them

2. protected or public

Which of the following is NOT true about return statements? 1. A method can have more than one return statement. 2. return statements can be used in void methods to return values. 3. Whenever a return statement executes in a method, the remaining statements are skipped and the method exits. 4. A value-returning method returns its value via the return statement.

2. return statements can be used in void methods to return values.

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

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

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

2.0

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

2.5

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)

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.

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

3. Finds the position of the largest value in a.

What does the following loop do? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] > value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. Removes (deletes) value from a so that the array remains ordered. 2. Places value in the last element of a 3. Inserts value into a so that the array remains ordered. 4. Places value in the first unused space in a (where the first 0 appears)

3. Inserts value into a so that the array remains ordered.

Consider the following statements. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println("Length = " + length + "; Width = " + width + "\n" + + " Area = " + area() + "; Perimeter = " + perimeter()); } public double area() { return length * width; } public void perimeter() { return 2 * length + 2 * width; } } What is the output of the following statements?

3. Length = 14.0; Width = 10.0 Area = 140.0; Perimeter = 48.0

Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public void perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(); Which of the following sets of statements are valid in Java? (i) bigRect.set(10, 5); (ii) bigRect.length = 10; bigRect.width = 5; 1. Only (ii) 2. None of these 3. Only (i) 4. Both (i) and (ii)

3. Only (i)

Which of the following class definitions is correct in Java? (i) public class Student { private String name; private double gpa; private int id; public void Student() { name = ""; gpa = 0; id = 0; } public void Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } (ii) public class Student { private String name; private double gpa; private int id; public Student() { name = ""; gpa = 0; id = 0; } public Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } 1. Both (i) and (ii) 2. None of these 3. Only (ii) 4. Only (i)

3. Only ii

What is the last index of the string TEXT?

3. The first letter starts with index 0.

Size, style, and name

3. The font property controls the ____ of the font displayed by the Jlabel.

public static String exampleMethod(int n, char ch) Which of the following statements about the method heading above is NOT true? 1. The method has two parameters. 2. exampleMethod is an identifier giving a name to this specific method. 3. The method cannot be used outside the class. 4. It is a value-returning method of type String.

3. The method cannot be used outside the class.

Consider the following method definition. public int strange(int[] list, int item) { int count; for (int j = 0; j < list.length; j++) if (list[j] == item) count++; return count; } Which of the following statements best describe the behavior of this method? 1. This method returns the sum of all the values of list. 2. None of these 3. This method returns the number of times item is stored in list. 4. This method returns the number of values stored in list.

3. This method returns the number of times item is stored in list.

setTitle

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

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

3. []

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

3. a (line 25)

Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements adds the object to the end of the collection? 1. a[3] = element; 2. a[4] = element; 3. a.add(element); 4. a.add(element, 4);

3. a.add(element);

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

3. accessor

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

3. class

When you create your own new, user-defined types, there are really three different strategies you can use. Which of these is not one of those strategies? 1. defining a component from scratch, inheriting only the methods in the Object class 2. extending an existing component by adding new features 3. defining a component from scratch, inheriting no methods whatsoever 4. combining simpler components to create a new component

3. defining a component from scratch, inheriting no methods whatsoever

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

Consider the following method which takes any number of parameters. Which statement would return the first of the numbers passed when calling the method? int first = firstNum(7, 9, 15); public int firstNum(int..nums) { // what goes here? } 1. return nums[0] 2. return nums; 3. return nums...0 4. return nums.first;

3. return nums..0

Which of the following words indicates an object's reference to itself? 1. public 2. that 3. this 4. protected

3. this

Mutator methods typically have a return type of ______________. 1. boolean 2. String 3. void 4. int

3. void

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

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

Consider the following statements. public class PersonalInfo { private String name; private int age; private double height; private double weight; public void set(String s, int a, double h, double w) { name = s; age = a; height = h; weight = w; } public String getName() { return name; } public int getAge() { return age; } public double getHeight() { return height; } public double getWeight() { return weight; } } Assume you have the following code fragment inside a method in a different class: PersonalInfo person1 = new PersonalInfo(); PersonalInfo person2 = new PersonalInfo(); String n; int a; double h, w; Which of the following statements are valid (both syntactically and semantically) in Java? (i) person2 = person1; (ii) n = person1.getName(); a = person1.getAge(); h = person1.getHeight(); w = person1.getWeight(); person2.set(n, a, h, w); 1. None of these 2. Only (ii) 3. Only (i) 4. Both (i) and (ii)

4. Both (i) and (ii)

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

4. Finds the position of the largest value in a.

Assume you have a Student object and a Student variable named bill that refers to your Student object. Which of these statements would be legal? bill.name = "Bill Gates"; // I bill.setName("Bill Gates"); // II println(bill.getName()); // III bill.studentID = 123L; // IV println(bill.getID()); // V 1. II, III, IV, VI 2. IV, V 3. All of them 4. II, III, V 1 5. None of them

4. II, III, V

Parentheses

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

Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following sets of statements are valid (both syntactically and semantically) in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); 1. Both (i) and (ii) 2. Only (ii) 3. None of these 4. Only (i)

4. Only (i)

Which of the following class definitions is correct in Java? (i) public class Student { private String name; private double gpa; private int id; public void Student() { name = ""; gpa = 0; id = 0; } public void Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } (ii) public class Student { private String name; private double gpa; private int id; public Student() { name = ""; gpa = 0; id = 0; } public Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } 1. Only (i) 2. Both (i) and (ii) 3. None of these 4. Only (ii)

4. Only (ii)

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

4. Sums the odd elements in a.

Compiler

4. Syntax errors are found by the ____.

setIcon

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

setText()

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

Which of these are superclass members are not inherited by a subclass? 1. a protected method 2. a protected instance variable 3. a public instance variable 4. a public constructor 5. a public method

4. a public constructor

Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements adds the object to the end of the collection 1. a[3] = element; 2. a.add(element, 4); 3. a[4] = element; 4. a.add(element);

4. a.add(element);

What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = 2 * j; if (j % 2 == 1) alpha[j - 1] = alpha[j] + j; } 1. alpha = {0, 2, 4, 6, 8} 2. alpha = {0, 3, 4, 7, 8} 3. alpha = {0, 2, 9, 6, 8} 4. alpha = {3, 2, 9, 6, 8}

4. alpha = {3, 2, 9, 6, 8}

If a method in the superclass is declared protected, you may replace it in the subclass as long as the subclass method that you define: 1. has a different number, type, or order of parameters 2. has a different return type 3. is defined as protected or private 4. is defined as public or protected 5. is defined only as public

4. is defined as public or protected

A locally declared variable always ____ another variable with the same name elsewhere in the class. 1. uses 2. creates 3. deletes 4. masks

4. masks

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

4. println(pete.toString());

Mutator methods typically begin with the word "____". 1. read 2. get 3. call 4. set

4. set.

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

the line number of the error; a brief description of the error.

5. Upon finding a syntax error in an application, the compiler will notify the user of an error by giving the user ____.

Replaces

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

When you define a subclass, like Student, and don't supply a constructor, then its superclass must: 1. have an explicit working constructor defined 2. have no constructors defined 3. have an explicit default (no-arg) constructor defined 4. have an explicit copy constructor defined 5. have no constructors defined or have an explicit default (no-arg) constructor defined.

5. have no constructors defined or have an explicit default (no-arg) constructor defined.

When you define a subclass, like Student, and add a single constructor with this signature Student(String name, long id), an implicit first line is added to your constructor. That line is: 1. No implicit lines are added to your constructor 2. this(); 3. super(name, id); 4. base(); 5. super();

5. super();

When you create a new class using inheritance, you use the extends keyword to specify the __________________ when you define the ________________. 1. derived class, subclass 2. derived class, base class 3. superclass, base class 4. subclass, base class 5. superclass, subclass 6. subclass, superclass

5. superclass, subclass

double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is in vals[2][1]? 1. 1.3 2. 3.3 3. 3.5 4. 5.3

5.3

Nondestructive

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

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)

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,

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

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.

end-of-line comment

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

full-line comment

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

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.

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

A compiler

JTextField component

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

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

use of constructors in new instances

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

Switch Statement

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

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

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

double

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

print

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

What is this automatically? 45e7

A double

When dividing what must the variable be put into?

A double because division automatically sets it to a double.

By default what is this considered - 12.21?

A double.

source code file

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

pixel

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

3. Describe the difference between pretest loops and posttest loops. ?

A pretest loop tests its test expression before each iteration. A posttest loop tests its test expression after each iteration.

algorithm

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

control

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

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

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

While Statement

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

application

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

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.

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.

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.

book-title capitalization

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

sentence-style capitalization

A style that capitalizes the first letter of the first word In the text (for example, Cartons per shipment): other letters in the text are lowercase, unless they are the first letters of proper nouns.

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.

Class

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

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.

Variables

A variable is a name for a location (a chunk) in memory that holds a value (a fixed type of data) Variables come in two flavors: primitive and reference primitive: integer (such as 1, 2,...), floating point number (such as 1.2, 3.5, etc.), boolean (true or false) and char (such as 'A', 'B',...) reference: "address" of an object that resides in memory A variable declaration specifies the variable's name and the type of information that it will hold

True and False

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

Counter

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

Print

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

primitive type

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

Constant

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

constant

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

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

integer

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

keyword

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

reserved word

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

Algorithm

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

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

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

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

A1

ASCII

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

forward slash (/)

An arithmetic operator that indicates division.

asterisk (*)

An arithmetic operator that performs multiplication.

Declaration with Initialization

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

left operand

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

right operand

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

operand

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

variable

An identifier that represents a location in memory.

10. What is an infinite loop? Write the code for an infinite loop. ?

An infinite loop is a loop that has no way of stopping, it occurs when a programmer forgets to write code inside the loop that makes the test condition false. There are several possibilities to do an endless loop, here are a few I would choose: for(;;) {} while(1) {} / while(true) {} do {} while(1) / do {} while(true)

pseudocode

An informal language that helps programmers develop algorithms.

What is a field?

An instance variable

By default what is this considered - 12?

An int.

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

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

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

JTextArea method _ adds text to a JTextArea.

Append

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

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.

semicolon (;)

Character used to terminate each statement in an application.

What are the different types of exception in Java?

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

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.

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

Refactoring

Cleans code whilst preserving behaviour.

17. Why should a program close a file when it's finished using it?

Closing a file writes any unsaved data remaining in the file buffer.

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.

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

Compares the equality of two strings.

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

Compares two object area memories.

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

Compilation Error

What does Javac do?

Compiles the program.

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.

BoxLayout

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

Intermediate Swing Level

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

final or user-defined constant

Constant, cannot be changed.

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.

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

Local variables (field)

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

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

Definite repetition

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

Definite repetition

this

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

left brace ({)

Denotes the beginning of a *block of code*.

right brace (})

Denotes the end of a *block of code*.

In a @return tag statement the description

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

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)

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

Suppose we want to store a tic-tac-toe board in a program; it's a three-by-three array. It will store "O", "X" or a space at each location (that is, every location is used), and you use a two-dimensional array called board to store the individual tiles. Suppose you pass board to a method that accepts a two-dimensional array as a parameter. If the method was designed to process two-dimensional arrays of various sizes. What information about the size of the array would have to be passed to the method so it could properly process the array? A. the number of columns in the array B. the number of rows in the array C. the number of cells in the array D. Both A and B E. No additional information is needed, as the array carries its size information with it.

E. No additional information is needed, as the array carries its size information with it.

Suppose we define a class called NameInfo. It has several private fields, including String hospName; and several public methods, including one that accesses hospName: String getName(); Now, we define an array like this: NameInfo[] listOfHospitals = new NameInfo[100]; Which expression below correctly accesses the name of the hospital that's stored in position 5 (that is, the 6th element) of the listOfHospitals? A. listOfHospitals.getName(5) B. listOfHospitals.hospName[5] C. listOfHospitals[5].hospName D. listOfHospitals[getName(5)] E. listOfHospitals[5].getName()

E. listOfHospitals[5].getName()

ClassCastException

Error dat ontstaat bij verkeerde downcasting

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

When is an instance block executed?

Every Time an instance of the class it was created is made. Before the constructor.

Events

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

The string class

Every character string (enclosed in double quotation characters) is an object in Java defined by the String class Every character string can be used to create a string object Because strings are so common, we don't have to use the new operator to create a String object (special syntax that works only for strings) String name1 = "Steve Jobs"; It is equivalent to String name1 = new String("Steve Jobs");

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

Hardware

Types of Maps

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

Types of sets

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

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

Header

The Main Method

In Java, everything goes in a class (object-oriented) After you compile the source code (.java) into a bytecode or class file (.class), you can run the class using the Java Virtual Machine (JVM) When the JVM loads the class file, it starts looking for a special method called main, and then keeps running until the code in main is finished

An action

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

base or radix

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

public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Where is identifier x (block three's local variable) visible? 1. In two and block three 2. In block three and main 3. In block three only 4. In one and block three

In block three only

Methods

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

1. Briefly describe the difference between the prefix and postfix modes used by the increment and decrement operators. ?

In postfix mode the operator is placed after the operand. In prefix mode the operator is placed before the variable operand. Postfix mode causes the increment or decrement operation to happen after the value of the variable is used in the expression. Prefix mode causes the increment or decrement to happen first.

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

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"

bytecode

Instructions for the Java virtual machine

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

Int

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

Integer.parseInt(s);

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.

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

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

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.

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

Scanner Class

It is often useful to design interactive programs that read input data from the user The Scanner class provides convenient methods for reading input values of various types A scanner object can be set up to read input values from various sources including the user typing values on the keyboard The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner(System.in); Once created, the Scanner object can be used to invoke various input methods, such as: String answer = scan.nextLine(); The nextLine method reads all of the input until the end of the line is found, and return it as one String

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

It is one

What is the reference type of a polymorphic object instance?

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

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.

Java compiler translates Java source code into ________.

Java bytecode

Java Development Kit (JDK)

Java compiler and interpreter. includes JRE and JSE API

________ is a software that interprets Java bytecode.

Java virtual machine

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

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.

Public

Kan door de buitenwereld worden aangeroepen.

Private

Kan niet door de buitenwereld worden aangeroepen

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.

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 you make a constructor final?

No, constructor can't be final.

Is constructor inherited?

No, constructor is not inherited.

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

No, interfaces can't be instantiated.

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

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

Can local variables use the static modifier?

No, local variables can only use the final modifier.

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

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

Can local variables use access modifiers?

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

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

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

Can you set a float to 1.0?

No, that would automatically make it a double.

Can we override static method?

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

Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Which of these fields or methods are inherited by the Person class? 1. getName(), setName(), studentID, getID() 2. getName(), setName(), name 3. None of them 4. studentID, name, getName(), setName(), getID() 5. name, getName(), setName(), getID()

None of them

Consider the following declaration. double[] sales = new double[50]; int j; Which of the following correctly initializes all the components of the array sales to 10. (i) for (j = 0; j < 49; j++) sales[j] = 10; (ii) for (j = 1; j <= 50; j++) sales[j] = 10;

None of these

To print the last element in the array named ar, you can write : A. System.out.println(ar.length); B. System.out.println(ar[length]); C. System.out.println(ar[ar.length]); D. None of these

None of these

What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 1; if (j > 2) alpha[j - 1] = alpha[j] + 2; }

None of these

What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 1; if (j > 2) alpha[j - 1] = alpha[j] + 2; } 1. alpha = {1, 2, 3, 4, 5} 2. alpha = {4, 5, 6, 7, 9} 3. alpha = {1, 5, 6, 7, 5} 4. None of these

None of these

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.

hexidecimal

Number utilizing base 16

Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following sets of statements are valid (both syntactically and semantically) in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); 1. Both (i) and (ii) 2. Only (ii) 3. Only (i) 4. None of these

Only (i)

Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following sets of statements are valid (both syntactically and semantically) in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); 1. Only (ii) 2. None of these 3. Only (i) 4. Both (i) and (ii)

Only (i)

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)

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)

Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Which of the following statements correctly instantiate the Rectangle object myRectangle? (i) myRectangle Rectangle = new Rectangle(10, 12); (ii) class Rectangle myRectangle = new Rectangle(10, 12); (iii) Rectangle myRectangle = new Rectangle(10, 12); 1. Only (ii) 2. Only (iii) 3. Only (i) 4. Both (ii) and (iii)

Only (iii)

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

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

size property

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

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

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

Operating system

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.

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

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

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.

System.out.println("Hello")

Prints Hello to console on a new line.

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

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

Promotion Conversion

Promotion happens automatically when operators in expressions convert their operands Example: int count = 12; double sum = 490.27; double result = sum / count; The value of count is converted to a floating point value to perform the division calculation

font property

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

background property

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

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)

git push

Publishes committed local files to remote repo.

Commit

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

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

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

What does array.asList do?

Puts an array as an array list.

wait() (Thread Communication)

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

Volatility is a property of

RAM

Random Access Memory

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

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.

Logical AND and Logical OR

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

Design patterns

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

Java was developed by ________.

Sun Microsystems

Argumenten van het wildcard type

Superclasses en interfaces als method parameter gebruiken zodat de method voor de verschillende implementaties en subclasses gebruikt kan worden.

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.

AND

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

What is the 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);

NOT

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

OR

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

The Random Class

The Random class is part of the java.util package It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values nextFloat() generates a random number [0, 1) nextInt() generates a random integer over all possible int values (positive or negative) nextInt(n) generates a random integer [0, n-1]

More About System.out

The System.out object represents a destination (the monitor screen) to which we can send an output The System.out object provides another service in addition to println The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line

Diamond (in the UML)

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

size

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

name

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

type

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

+=

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

==, <= and <

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

Which of the following statements about strings is NOT true? 1. The class String contains many methods that allow you to change an existing string. 2. A String variable is actually a reference variable. 3. When a string is assigned to a String variable, the string cannot be changed. 4. When you use the assignment operator to assign a string to a String variable, the computer allocates memory space large enough to store the string.

The class String contains many methods that allow you to change an existing string.

DecimalFormat

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

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.

Incrementing

The process of adding 1 to an integer.

class declaration

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

Escape Sequence

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

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

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.

7. Which loop should you use in situations where you want the loop to repeat until theboolean expression is false , but the loop should execute at least once?

The do - while loop.

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

Decimal points

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

keyPressed event

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

21. What is a potential error that can occur when a file is opened for reading?

The file does not exist.

Demo

The filename of the source file must be the same as the class name (###case sensitive###) java MyFirstApp (###not MyFirstApp.class###)

8. Which loop should you use when you know the number of required iterations?

The for loop.

What is the purpose of the Java garbage collection?

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

extends keyword

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

class keyword

The keyword used to begin a class declaration.

actionPerformed

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

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

What is object cloning?

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

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.

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.

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.

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.

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

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

horizontalAlignment property

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

editable property

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

icon property

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

horizontalAlignment property

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

text property

The property that specifies the text displayed by a JLabel.

location property

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

Problem Solving

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

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.

String Concatenation

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

program control

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

functionality

The tasks or actions an application can execute.

setText

The text on a JLabel is specified with _____.

JCheckBox text

The text that appears alongside a JCheckBox.

Sequence, selection and repetition

The three types of program control are _____.

.java file

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

.class file

The type of file that is executed by the Java Runtime Environment (JRE). A ____ file is created by compiling the application's .java file.

14. Why must the value chosen for use as a sentinel be carefully selected?

The value chosen for a sentinel must be carefully selected because you want it to be unique enough that it will not be mistaken for a regular value in a list you are working with.

What is an actual parameter?

The value passed into a method by a method call

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.

update statement

The way the index of a loop changes value.

5. Describe the difference between the while loop and the do - while loop. ?

The while loop is a pretest loop and the do - while loop is a posttest loop.

6. Which loop should you use in situations where you want the loop to repeat until the boolean expression is false , and the loop should not execute if the test expression is false to begin with?

The while loop.

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.

Primitive Types

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

Language Levels

There are four programming language levels. Each type of CPU has its own specific machine language The other levels were created to make it easier for a human being to read and write programs

11. Describe a programming problem that would require the use of an accumulator. ?

There are many possible examples. A program that asks the user to enter a business's daily sales for a number of days, and then displays the total sales is one example

A JCheckBox is selected when the isSelected method returns __.

True

Method overloading

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

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

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

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.

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

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.

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

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

XINSTXIN.

Which of the following is true regarding Java syntax and semantics? 1) a Java compiler can determine if you have followed proper syntax but not proper semantics 2) a Java compiler can determine if you have followed proper semantics but not proper syntax 3) a Java compiler can determine if you have followed both proper syntax and semantics 4) a Java compiler cannot determine if you have followed either proper syntax or semantics 5) a Java compiler can determine if you have followed proper syntax and can determine if you have followed proper semantics if you follow the Java naming convention rules

a Java compiler can determine if you have followed proper syntax but not proper semantics

Single Responsibility Principle

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

Cohesion

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

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

a communication issue between subsystems

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

A URL (Universal Resource Locator) specifies the address of

a document or other type of file on the Internet

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

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

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

a logic error

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

a logical error

repetition statement

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

assembly language

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

Mutator method

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

static method

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

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

14. To open a file for writing, you use the following class. a. PrintWriter b. FileOpen c. OutputFile d. FileReader

a. PrintWriter

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

6. The while loop is this type of loop. a. pretest b. posttest c. prefix d. postfix

a. pretest

8. The for loop is this type of loop. a. pretest b. posttest c. prefix d. postfix

a. pretest

binary

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

Comments should

be insightful and explain what the instruction's intention is

CH11: Abstract classes cannot _______.

be instantiated

Why do computers use zeros and ones?

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

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

In a UML diagram for a class

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

array

collection of data values of the same type; reference data type

12. This is a variable that keeps a running total. a. sentinel b. sum c. total d. accumulator

d. accumulator

4. What is each repetition of a loop known as? a. cycle b. revolution c. orbit d. iteration

d. iteration

Data Hiding

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

HashSet

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

properties

data values(members) -variables -constants

try-catch control statement

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

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

exception handler

checked exception

exception that is check at compile time

exception propagator

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

exception catcher

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

exchange sort

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

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

execute

Logic

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

Polymorphism

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

cast

explicitly converting a value from one type to a different type

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

extends

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

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

getSelectedIndex

Programming style is important, because ________. (Choose all that apply.) 1) a program may not compile if it has a bad style 2) good programming style can make a program run faster 3) good programming style makes a program more readable 4) good programming style helps reduce programming errors

good programming style makes a program more readable good programming style helps reduce programming errors

binary tree

graph with edges, connected nodes such that there is a root node and no node has more than two children nodes

GUI

graphical user interface

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.

Abstraction

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

instance variables

identifiers used to descibe the attributes of an object.

selection statement

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

coding

implement the design into a program; result is a program

switch statement

implements selection control flow

behaviors

methods; action for the object to do

public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } What is the name of the method above?

minimum

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

minimum(5, 4);

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

minimum(5, 4);

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

minimum(5, 4);

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

mnemonic

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

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

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

multiple interval selection mode

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

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

Indentifier

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

Variables

named computer memory locations that hold values that might vary

an instance is another way of saying ____?

object

event listener

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

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

objects are instances of classes

Java

oject oriented language

off-by-one error

one fewer iteration or one too many

Which of the following is a legal Java identifier? 1) 1ForAll 2) oneForAll 3) one/4/all 4) 1_4_all 5) 1forall

oneForAll

Private

only accessible if in same class.

The advantages of the DecimalFormat class compared with the NumberFormat class include

only precise control over the number of digits to be displayed and control over the presence of a leading zero

abstract method

only the method header but no body

op code

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

boolean operator

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

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.

||

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

Inheritance

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

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.

To define a class that will represent a car, which of the following definitions is most appropriate? 1) private class car 2) public class car 3) public class Car 4) public class CAR 5) private class Car

public class Car

Visibility modifiers include

public, private, protected

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

public, protected, default, private.

Variables in interfaces are declared what automatically?

public, static and final.

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.

time complexity

quantifies the amount of time taken by an algorithm to run; commonly expressed using big O notation

The ability to directly obtain a stored item by referencing its address is known as

random access

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)

overriding a method

redefining a method in a subclass

string

reference data type; array of characters; immutable; pass-by-value

interface

reference data type; includes only constants and abstract methods

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

relationships

extraction phase

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

design

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

Bounded generic types

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

syntax

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

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

parameter passing

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

merge sort

splits the list into two equal halves and places them in separate arrays, each array is recursively sorted then merged back together to form the final sorted list

Application

stand-alone, executable program

Block Comments

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

javadoc Comments

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

Line Comments

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

In addition to their usage providing a mechanism to convert (to box) primitive data into objects, what else do the wrapper classes provide?

static constants

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

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

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

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 a variable can be accessed

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

Syntax

the rules of the language

To determine the number of valid elements in an ArrayList, use:

the size() method

What does the static keyword mean?

the static keyword is used to define a field or method that will not change across all instances of that class - it defines a class level element that can be accessed without instantiating an object of that class

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

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

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

Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long 1. toString() 2. None of them 3. getName(), setName(), name 4. name, getName(), setName(), getID() 5. getName(), setName(), studentID, getID() 6. studentID, name, getName(), setName(), getID()

toString()

Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Assume that pete is a Person object variable that refers to a Person object. Which method is used to print this output: pete is Person@addbf1 1. getClass() 2. getAddress() 3. getName(), getID() 4. getID() 5. getName() 6. None of them 7. toString()

toString()

Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Which of these fields or methods are inherited by the Person class? 1. toString() 2. getName(), setName(), studentID, getID() 3. studentID, name, getName(), setName(), getID() 4. name, getName(), setName(), getID() 5. getName(), setName(), name 6. None of them

toString()

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

tool tip

StringTokenizer is a class in the java.util library that can divide a String based on some delimiter String (a delimiter is a separator). If the instruction StringTokener st = new StringTokenizer(str, "&&"); is executed, where str is some String, then st divides up str into separate Strings whenever

two ampersands are found

A Java character is stored in ________.

two bytes

An "alias" is when

two different reference variables refer to the same physical object

bubble sort

type of exchange sort; compare the first pair of elements(exchange if needed), compare the second pair, third, fourth, and so on until the end of the list; highest number guaranteed to be in the last place after first sort

Exceptions

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

address

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

testing

unit testing or integration testing; debugging

Integer

unsigned int, 0 -> 2^31 -1

Long

unsigned long

sort-in-place

use same same amount of memory space when sorted

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

variable

local variable

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

protected

variables/methods available to any class that extends the original

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

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

w (before method two)

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

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)

To add a value 1 to variable x, you write (Choose all that apply.) 1) 1 + x = x; 2) x += 1; 3) x := 1; 4) x = x + 1; 5) x = 1 + x;

x += 1; x = x + 1; x = 1 + x;

To assign a double variable d to a float variable x, you write

x = (float)d;

To assign a value 1 to variable x, you write

x = 1;

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

x = y;

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

x is 2

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

x is 3

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

x is 5.5 and y is 5

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


Set pelajaran terkait

comb for 6 sigma class, Six Sigma Green Belt

View Set

MGMT 474 Chapter 5: Person-Focused Pay

View Set

Visual Perception System - Perceptual Constancies - PSYCH EXAM

View Set

America's first southeast Asian war-the Philippine insurrection

View Set