Java Programming Flashcards

1
Q

What is a module?

A

A group of related packages

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a package?

A

A group of related types, classes, interfaces or subpackages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Which package contains the Scanner class?

A

java.util

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a prerequisite for using a class? Why?

A
  • The package it is contained within must be imported
  • It informs the compiler where it is located.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What sections are included in API documentation for a class? What is the purpose of each?

A
  • Class overview: Describes the class’ functionality and how it is commonly used in a program.
  • Constructor summary: Provides a list and brief description of constructors that can be used to create objects of the class.
  • Method summary: Provides a list and brief description of all methods that can be called on an object of the class.
  • Constructor and method details: A detailed description of all constructors and methods for the class.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

True or False: API documentation only includes information about public methods.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What type of object is System.in?

A

InputStream

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

When is an InputStream object created?

A

When the java program is executed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the appropriate constructor for Scanner(System.in)?

A

Scanner(InputStream source)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does documentation provide for each method of a class?

A
  • Method declaration
  • Description of the method
  • List of parameters, if any
  • Description of the methods return value
  • List of possible exceptions the method may throw
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the javadoc tool used for?

A

Parses specially formatted multi-line comments to generate program documentation in HTML format

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the syntax for creating a javadoc comment?

A

/** Your comment here */

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the syntax for a block tag?

A

@keyword

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

At a bare minimum, each method should contain the following information as a javadoc comment.

A
  • Description
  • @param block tag
  • @return block tag
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does the @see block tag describe?

A

Relevant information like a website or another method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Which block tag specifies the author?

A

@author

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Which block tag specifies the version number?

A

@version

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

True or false: When a javadoc comment is updated, the HTML documentation is automatically updated.

A

False: The javadoc tool must be run.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are the types, classes, and interfaces in a package called?

A

Package members

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Which package is automatically imported by Java?

A

java.lang

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What elements make up a members fully qualified name?

A

the package name.the member name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are 3 ways a programmer can use a package member?

A
  • Fully qualified name
  • Use an import statement to import the package member.
  • Use an import statement to import the entire package.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the syntax for importing an entire package?

A

import packageName.*

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Which class serves as the base class for all other classes?

A

Object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What does an object's toString() method return by default?
A string containing the object's class name followed by the objects hash code in hexadecimal format.
26
What does object's equals(otherObject) method do? When does it return true?
- Compares two objects. - Returns true if the object references are identical. - Does not compare the objects' contents.
27
What happens if you concatenate an object with a string?
The string returned by the object's toString() method is concatenated to the string.
28
What is the role of garbage collection?
Finds all unreachable/unused allocated memory locations and automatically frees them. Does this at various intervals.
29
What type of error is a syntax error?
Compile-time
30
What is another name for a logic error?
A bug
31
What type of error is a logic error?
Runtime
32
How do you run javac to show all possible warnings?
javac -Xlint yourfile.java
33
How does a local variable get marked for garbage collection?
- When the local variable goes out of scope, the Java Virtual Machine decrements the reference count so that it is marked for deallocation. - The Java Virtual Machine invokes the garbage collector.
34
What does a .class file contain?
Bytecode
35
What is contained in a .java file?
Plaintext code
36
What is the machine language of the Java Virtual Machine?
Bytecode
37
What is a platform?
The hardware or software environment in which a program runs.
38
What are the two components of the Java platform?
- The Java Virtual Machine - The Java Application Programming Interface
39
Which Java feature is used to create sophisticated GUI's
User Interface Toolkits
40
What is the purpose of integration libraries?
They enable database access and manipulation of remote objects.
41
How does a java program become executable?
1. Java program (.java file) is compiled into a .class file containing byte code. 2. The Java Virtual Machine converts the byte code to machine code 3. The operating system interprets/processes the machine code
42
Which 2 packages are used by almost every application?
- java.lang - java.util
43
When can you use a package member's name without importing the package first and without using it's fully qualified name?
When the code you are writing is in the same package as the member you are attempting to use.
44
Where within the code does an import statement belong?
- Before type definitions - After package the package statement, if one exists
45
Which 2 packages are imported automatically by the compiler?
- java.lang - the package for the current file
46
How do you import public nested classes of an enclosing class? (Package name: graphics, Enclosing class: Rectangle)
- import graphics.Rectangle - import graphics.Rectangle.*
47
How do you use a package member if the package it is contained in is imported as well as another package containing a member by the same name?
Use the fully qualified name
48
What is the purpose of a static import statement?
Prevents the need to prefix static final fields and static methods with the class name each time they need to be used.
49
What is the syntax for a static import statement?
- import static package.class.staticmember - import static package.class.*
50
The main method must be inside the ___.
Class definition
51
The name of the class must match the name of the ___.
File
52
Class names start with an ___ letter. Method names start with a ___ letter.
- Uppercase - Lowercase
53
What's the most basic form of a class definition?
class name {}
54
What code at the top of a file enables the program to get input?
import java.util.scanner
55
What is a Scanner object?
A text parser that can get numbers, words, or phrases from an input source such as the keyboard
56
What is the syntax for creating a Scanner object?
Scanner scnr = new Scanner(System.in)
57
What does System.in corresponds to?
Keyboard input
58
What are the rules for identifiers?
Must be a sequence of letters: - (a-z, A-Z), underscore (_), - dollar signs ($) -digits (0-9) Must start with a: - letter - underscore - dollar sign
59
What is another word for a reserved word?
keyword
60
What would happen if you try to use a variable name outside of it's scope?
Compiler error
61
What is a variable declared within a class but outside any method?
Member variable or field
62
What is a variable declared within a method?
A local variable
63
What happens if a method's local variable (including a parameter) has the same name as a field?
In that method the name refers to the local item and the field is inaccessible.
64
What is meant by the term "side effects?"
When the method has effects that go beyond its parameters and return value. - IE if the method updates a field (variable in the class that contains the method)
65
What is a method's scope?
From the class's opening brace to the class's closing brace.
66
True or False: A method can access any other method defined in the same class, regardless of the order in which the methods are defined.
True
67
What is the size and supported range of a Byte?
- 8 bits (1 byte) - neg 128 to 127
68
What is the size and supported range of a short?
- 16 bits (2 bytes) - neg 32,768 to 32,767
69
What is the size and supported range of a int?
- 32 bits (4 bytes) - neg 2,147,483,648 to 2,147,483,647
70
What is the size and supported range of a long?
- 64 bits (8 bytes) - neg 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
71
What is the size and supported range of a float?
- 32 bits (4 bytes) - neg 3.4x1038 to 3.4x10 to the 38
72
What is the size and supported range of a double?
- 64 bits (8 bytes) - neg 1.7x10308 to 1.7x10 to the 308
73
What is the mantissa limited to in significant digits?
- About 7 significant digits for float - About 16 significant digits for double
74
When does an overflow occur?
When the value being assigned to a variable is greater than the maximum value the variable can store
75
What is the syntax for a constant or final variable?
Upper case letters with words separated by underscores
76
What is an automatic type conversion called?
Implicit conversion
77
For an arithmetic operator like + or *, if either operand is a double, what is the other operand converted to?
Double
78
For assignments, the ___ side type is converted to the ___ side type if the conversion is possible without loss of precision.
- Right - Left
79
What is done to explicitly convert a data type to another data type? What is the syntax?
- Type cast - (type) before the variable or literal
80
What happens to the value after the decimal when converted to a non-floating point type?
The value after the decimal is dropped (rounded down).
81
Are objects of the wrapper class mutable or immutable?
Immutable
82
How can you check the maximum and minimum values allowed for a numeric data type?
The wrapper classes have static data members for MAX_VALUE and MIN_VALUE.
83
When can you use equality operators with wrapper classes?
- When comparing to primitive variables/literal constants. - Otherwise, when you compare two wrapper class objects, it's just comparing the memory location of the object.
84
True or False: You also cannot use relational operators to compare objects of wrapper classes.
False. This works as expected. It will compare the values held within the wrapper classes.
85
What are two methods that can be used to compare objects of wrapper classes?
- .equals() - .compareTo()
86
When does num1.compareTo(num2) return positive? negative?
- When num1 is greater than num2 - When num1 is less than num2
87
When arithmetic operators are used with a wrapper class and a primitive, what is the type of the result?
Primitive, unboxing occurs.
88
What is a static method?
Methods that can be called by a program without creating an object.
89
What are two ways to convert an integer to a string?
- num1.toString(); - Integer.toString(num1);
90
How can you convert a number stored in a string to an int (primitive)?
Integer.parseInt(str1);
91
How can you convert a number stored in a string to an int (wrapper)?
Integer.valueOf(str1);
92
How do you convert an int/integer to binary?
Integer.toBinaryString(num1);
93
How do you get the next character held by the scanner object?
scar.next().charAt(0);
94
What type of object is System.out?
PrintStream
95
How does System.out.print/println work?
- System.out.print/println() convert the parameters to individual characters and stores them in the output buffer. - The system then outputs the contents of the buffer to the screen.
96
What type of object is System.in?
InputStream
97
What does System.in do?
Automatically reads the standard input from a buffer that the operating system fills with input data.
98
What needs to be added to main when using the InputStream?
throws IOException public static void main(String args[]) throws IOException {}
99
What is the role of a throws clause?
It indicates that during runtime the corresponding method may exit unexpectedly due to an exception.
100
How does System.in.read() work?
- Tells the operating system to read the standard input and fill a buffer with the input data. - The buffer is filled when a user hits Enter, which also adds a newline to the buffer. - read() method reads the first 8-bit ASCII value available from the operating system's buffer. - When the buffer is empty, System.in.read() waits for more keyboard input. - The user types "more" and presses return, filling the buffer with more data.
101
True or False: Programmers read directly from System.in to get user input.
False. Instead of directly reading bytes from System.in, a program typically uses the Scanner class, which automatically scans/converts a sequence of bytes into the desired data type. Scanner scar = new Scanner(System.in); Note that any InputStream object can be passed into Scanner's constructor. Not just System.in.
102
What is the size of the boolean data type?
1 bit
103
What is the size of a char data type?
2 bytes
104
Object memory is created using the ___ keyword.
new
105
What two methods are provided by System.out for output formatting?
printf() and format() Note: They work the same.
106
What arguments are needed for the printf() method?
1. Format string 2. Format specifiers Example format string: The %s account saved you $%f over %d years\n" Example format specifiers: account, total, years account = %s total = %f years = %d
107
What do the format specifiers describe?
The type of input to be expected. For example: %c = char %d = decimal integer value %f = float or double %e = scientific notation %s = string %n = new line
108
To how many decimal places are floats output to by default?
6
109
What is the format for sub-specifiers?
%(flags)(width)(.precision)specifier
110
What does the width sub-specifier describe?
Specifies the minimum number of characters to print.
111
What if the formatted value has more characters than the width sub-specifier requests?
The value will not be truncated.
112
What if the formatted value has fewer characters than the width sub-specifier requests?
The output will be padded with spaces
113
What does the .precision sub-specifier describe for floats??
The number of digits to print following the decimal point.
114
What are 4 flag sub-specifiers for numeric types and what do they do?
- dash character: Left aligns the output given the specified width, padding the output with spaces. - +: Prints a preceding + sign for positive values. Negative numbers are always printed with the - sign. - 0: Pads the output with 0's when the formatted value has fewer characters than the width. - space: Prints a preceding space for positive value.
115
How is scientific notation formatted?
3.12e+01 would be 3.12e^1
116
What does the precision sub-specifier do with strings?
Specifies the maximum number of characters to print.
117
Which flags are available for strings?
dash character: left-aligns text. Output is always padded with spaces.
118
What method is used to immediately output the buffer?
.flush()
119
What commonly will cause the .flush() method?
- Outputting a \n character - System.out.println
120
What are non-static variables called?
Instance variables, because their value is unique to each instance (object) of the class.
121
What are static variables called?
Class variables.
122
How do you determine the range of numbers a data type can hold based upon the number of bytes?
(2 ^ number of bytes)/2 = negative number subtract 1 to get the upper limit.
123
What is the difference between instantiation and initialization?
- Instantiation: Memory for the object is created using the new keyword. Reference to the memory is returned. - Initialization: Constructor for the class is called.
124
What is "declaration?"
- Creating a variable - Associating a variable name with an object type
125
How does declaration differ for primitive types vs objects?
- Declaration also reserves the memory for primitive types. - With objects, this is done with the new keyword.
126
How does the compiler differentiate between constructors?
The number and type of the arguments.
127
What happens if you do not declare a constructor for a class?
- It will inherit the no argument constructor from its parent. - If you did not create a parent class, it will inherit the constructor from the Object class.
128
Is this is a valid instantiation of a string variable? String school = "Red Rocks";
Yes, this is a string literal.
129
When can you use the == operator to compare strings?
If the new keyword was not used to create either string.
130
What are methods used to obtain information about an object called?
Accessor methods
131
What method can be used to determine the number of characters in a string?
.length()
132
What are 3 ways to concatenate a string?
- str1.concat(str2); - "Hi".concat(" Rachael"); - str1 + str2;
133
What is a primitive data type?
- A simple value - A type that holds the assigned value instead of holding the memory location of an object
134
What is a block scope variable? What is it's scope?
- A variable declared inside a block of code, nested within a method. - The block of code where it was declared.
135
List the widening conversion order.
byte -> short -> char -> int -> long -> float -> double
136
How should you compare floats for equality? Why?
(float1 - float2) < Math.abs(0.0001); Because floating points cannot always be exactly represented in the limited amount of bits available.
137
What is the epsilon?
Difference threshold indicating that floating-point numbers are equal.
138
Which class can be used to print the exact decimal value of a floating point number?
BigDecimal
139
What are the precedence rules for operators?
1. Parentheses 2. Logical not (!) 3. Arithmetic operators 4. Relational operators 5. Equality/Inequality operators 6. Logical AND 7. Logical OR
140
Which has higher precedence: == or !=?
Both have the same precedence. Read from left to right.
141
What are the requirements for a switch statement's expression?
1. Must be one of the following data types: byte, int, short, the wrapper classes for the previously mentioned types, char, string 2. Must be a constant expression. Aka you cannot use a variablen bn;'
142
What is the switch statement's expression?
The part that is evaluated in parentheses after the switch keyword.
143
How do you compare two strings for equality?
- str1.equals(str2); - str1.compareTo(str2) == 0;
144
Do uppercase or lowercase letters have a lower value?
Uppercase
145
How do you ignore case when comparing strings?
- str1.equalsIgnoreCase(str2); - str1.compareToIgnoreCase(str2);
146
What are two ways of concatenating a string?
- str1 + str2; - str1.concat(str2);
147
What is the string value equal to after the following operation? str1 = str1.concat('!');
Error, because '!' is a character is not a string.
148
What does the indx argument represent? indexOf(item, indx)
The starting index of the search
149
What does the following method do? replace(findStr, replaceStr)
Returns a new String in which all occurrences of findStr have been replaced with replaceStr.
150
What does the following method do? replace(findChar, replaceChar)
Returns a new String in which all occurrences of findChar have been replaced with replaceChar.
151
How do you get the next character from user input?
scnr.next().charAt(0)
152
What does a break statement do in a loop?
Causes an immediate exit from the loop.
153
What is the purpose of control structure?
Change program flow based upon a logical condition.
154
What are the compound operators?
- && - || - !
155
What is the syntax for one-way selection?
if (expression) {}
156
What is the syntax for two-way selection?
if (expression) {} else (expression) {}
157
What is the syntax for multiple-way selection?
if (expression) {} else if (expression) {} else (expression) {}
158
What are the 3 steps for writing a loop?
1. Initialize loop variable 2. Test loop variable 3. Update loop variable
159
What is a method?
A named list of statements.
160
What is contained in the methods definition?
Name and block of statements. - Zybooks doesn't specifically call out parameters?
161
What is a parameter's scope?
When the method is called to when the method is returned.
162
Which memory region do static variables reside in? What is their scope?
- Static region - Global scope
163
What are static methods commonly used for?
Mutating private static members of a class.
164
True or False: A method with a void return type can be used in an expression.
False: It cannot because it does not return a value.
165
What is the member access operator?
The period that follows an object or class name when invoking members of that class.
166
What are some benefits of writing methods?
- Code reuse - Modularity - Improved code readability
167
What is a test bench? A test vector?
- A separate program whose sole purpose is to check that a method returns correct output values for a variety of input values. - Each unique set of input values.
168
What is the syntax for an assert?
assert testExpression : detailedMessage
169
What is logged if an assert fails?
- Current line number - A detailed message denoted by detailedMessage,
170
How do you enable assertions when executing a Java program?
In command line: java -ea HrMinToMinTestHarness
171
What is an EOFException?
End of file or end of stream has been reached unexpectedly during input
172
What is an InputMismatchException?
Received input does not match expected type or the input is out of range for the expected type (thrown by Scanner)
173
What is a FileNotFoundException?
Attempt to open a file denoted by a filename failed
174
What is an ArithmeticException?
Arithmetic condition failed (Ex: Divide by zero error)
175
What is the syntax for throwing a custom exception?
throw new Exception("Invalid date.");
176
What must be done if throwing a custom exception?
Must be contained within a try block and the catch block must catch the exception. catch (Exception e) { System.out.println(e.getMessage()) }
177
What is the purpose of the "throws" clause?
Specifies the types of exceptions that a method may throw and callers of the method should handle.
178
Where should the throws clause be specified?
After a method's parameters list and before the opening brace
179
True or False: A method may throw more than one exception type?
True: Each exception type should be specified separated by commas.
180
What is an unchecked exception?
Exception caused by hardware or logic errors that a programmer usually cannot anticipate and handle.
181
What is Java's "catch or specify" requirement?
Methods must either catch a checked exception using a catch block, or specify that the method throws the checked exception using a throws clause.
182
True or False: Catching or specifying an unchecked exception in a throws clause is mandatory.
False: It is optional. Only checked exceptions must be caught or specified.
183
If Exception can catch all exception types, why not use it always?
A program that uses the Exception type may not be able to differentiate between caught exceptions or may catch unintended exception types
184
How do you create a custom exception type?
1 2 3 4 5 public NaNException() { super("NaN Exception"); } public class NaNException extends Exception { } public class NaNException extends Exception { public NaNException() { super("NaN Exception"); } }
185
What needs to be imported when intending to read from a file?
- import java.io.FileInputStream; - import java.io.IOException;
186
What is the syntax for reading from a file?
fileByteStream = new FileInputStream("numFile.txt"); inFS = new Scanner(fileByteStream);
187
Which objects need to be created to write to a file?
- FileOutputStream fileStream = new FileOutputStream("helloWorld.txt"); - PrintWriter outFS = new PrintWriter(fileStream);
188
On which object do you call the close method when you want to stop writing to a file?
The PrintWriter object.
189
On which object do you call the close method when reading from a file?
The FileInputStream object
190
Which classes need to be imported to write to a file?
- import java.io.FileOutputStream; - import java.io.IOException;
191
What is an input string stream?
A Scanner object initialized from a String
192
What is the syntax for creating a input string stream?
Scanner inSS = new Scanner(userInfo);
193
What is a benefit of using an output string stream before outputting to the user?
An output string stream allows a programmer to build and format a String before outputting to a file or the screen.
194
What does the StringWriter class do?
Provides a character stream to output characters.
195
What is the syntax of the return type of a method that returns an Optional?
Optional
196
How do you return an Optional?
return Optional.isNullable(objectYouWantToReturn);
197
How do you check whether an optional contains an object?
optionalObject.isPresent()
198
How do you get the object from the optional?
optionalObject.get()
199
When should you use an optional?
As a return type when the method may return null.
200
When should you use exception handling?
For things outside of developer control (ie. files and user input)
201
What is a checked exception?
Exceptional conditions that a well-written application should anticipate and recover from.
202
What is an error?
Exceptional conditions that are external to the application that cannot be anticipated or recovered from.
203
What is a runtime exception?
Exceptional conditions that are internal to the application that the application cannot anticipate or recover from.
204
How do you format catch if you want to catch multiple exception types?
catch (ExceptionType1 | ExceptionType2 e) {}
205
All ___ exceptions are unchecked exceptions.
Runtime
206
printStackTrace() method prints a trace of a statement’s ___ scope.
Dynamic scope
207
What is dynamic scope?
The hierarchy of methods that the method call in question is nested within...
208
What are two things that should be checked when opening a file using the File class?
- !file.exists() - !file.canRead()
209
What are 3 things that should be checked when writing to a file?
- !file.exists() - !file.canWrite() - fileName.length == 0
210
What is a stream?
An object that delivers data to and from other objects.
211
Reading until end of line
See Week 6 Pre-work File IO slide 10. File myFile = new File("demo.dat"); FileReader fileReader; BufferedReader reader; try{ fileReader = new FileReader(myFile); reader = new BufferedReader(fileReader); String line = ""; line = reader.readLine(); while (line != null ) { System.out.println("READ from FILE: " + line); line = reader.readLine(); } reader.close(); } catch(IOException e) { System.out.println(e.getMessage() + "\tRead Error\n"); }
212
How do you write to the end of a line?
File myFile = new File("demo.dat"); FileReader fileWriter; BufferedReader writer; try{ fileWriter = new FileWriter(myFile); writer = new BufferedWriter(fileWriter); writer.write("Hello World");
213
What is the default value of elements in a boolean array?
False
214
What is the syntax for initializing array elements at declaration
int[] myArray = {5, 7, 11};
215
What is a perfect size array?
An array where the number of elements is exactly equal to the memory allocated. (All elements are filled)
216
What is an oversize array?
- An array where the number of elements used is less than or equal to the memory allocated. - Since the number of elements used in an oversize array is usually less than the array's length, a separate integer variable is used to keep track of how many array elements are currently used.
217
What types cannot be used with generics? What is the workaround?
- Primitives - Utilize their wrapper classes
218
What is the syntax for declaring a generic class?
public class TripleItem > {
219
What is the syntax for a generic method signature?
public static > TheType tripleMin(TheType item1)
220
What does "extends Comparable >" do in public class TripleItem > {
Requires that any type used to create an object of the class be extended from comparable.
221
True or False: The .add() and .remove() list methods handle resizing the list.
True
222
What two constructors should be implemented for custom classes implementing a collection interface?
- A void (no arguments) constructor, which creates an empty collection. - A constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.
223
What is the syntax for creating an ArrayList with explicit values at initialization?
ArrayList arrayList = new ArrayList<>(Arrays.asList("John", "Chris", "Eric"))
224
How do you print elements of an array in JDK 4?
List list1 = new ArrayList(); list1.add("list1: hello"); list1.add(10); String tmp1; for(int i = 0; i < list1.size(); i++) { tmp1 = (String) list1.get(i); // cast required System.out.println(tmp1); }
225
What is the format of a method parameter if you need to take in a generic list?
public void method(List inList)
226
What is the format of a method parameter if you need to take in a generic list of only types extending a certain class?
public void method(List inList)
227
What are 7 restrictions of generics?
- Cannot Instantiate Generic Types with Primitive Types - Cannot Create Instances of Type Parameters - Cannot Declare Static Fields Whose Types are Type Parameters - Cannot Use Casts or instanceof With Parameterized Types - Cannot Create Arrays of Parameterized Types - Cannot Create, Catch, or Throw Objects of Parameterized Types - Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type
228
When can casting be done?
- Between classes of the same hierarchy - Between primitives
229
What is the method to add or update an element in a HashMap?
.put("key", "Value")
230
What is the method for checking whether a HashMap has a specific key?
.containsKey("Key")
231
What does a method definition contain?
- An access modifier - Return type - Name, parameters - Statements
232
How do you know if a UML diagram is representing the method signature?
- It shows the data type, separated with a colon, after the member name. - It shows the return type after the colon for methods.
233
How do you represent public, private and protected in a UML diagram?
- public: + - private: - - protected: #
234
Describe the 3 perspectives of a class diagram.
- Conceptual: represents the concepts in the domain - Specification: focus is on the interfaces of Abstract Data Type (ADTs) in the software - Implementation: describes how classes will implement their interfaces
235
How is an abstract class represented in a UML diagram?
Italics
236
How is inheritance represented in a UML diagram?
Solid line with a hollow arrow
237
How is an association between two classes represented in a UML diagram?
A solid line
238
How is cardinality represented in a UML diagram for the following: - Exactly one - Zero or one - Zero or more - One or more - Ordered
Each is displayed below the line - Exactly one: 1 - Zero or one: 0..1 - Zero or more: * - One or more: 1..* - Ordered: (ordered)
239
What is aggregation?
- It represents a "part of" relationship. - ie: Class2 is part of Class1.
240
How is aggregation represented in a UML diagram?
Solid line with a hollow diamond at the association end (the end that it funnels up to)
241
What is composition?
- A special type of aggregation where parts are destroyed when the whole is destroyed. - ie: Objects of Class2 live and die with Class1. - ie: Class2 cannot stand by itself.
242
How is composition represented in a UML diagram?
A solid line with a filled in diamond.
243
What is a dependency?
- A special type of association that exists between two classes where changes to the definition of one may cause changes to the other (but not the other way around).
244
How is a dependency represented in a UML diagram?
Dashed line with a simple arrowhead (>), rather than a triangular one.
245
What is realization?
Realization is a relationship between the blueprint class (interface) and the object containing its respective implementation level details.
246
How is realization (interface) represented in a UML diagram?
Dashed line with a hollow arrow.
247
How would you configure a class so that an object could not be created from it?
Give it a private constructor.
248
If you would like to use the implicitly created default constructor, what do you have to check?
That the super class has a default, no argument constructor.
249
What can you use the super class keyword for?
- To refer to the super class instances as well as static members - To invoke a super class method or constructor
250
It is a good idea for comparators to also implement ___. Why?
- java.io.Serializable - As they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap)
251
What is the syntax for Javadoc comments?
/** Description: {@link Class}

@param for each parameter */

252
What indicates that the named item is an interface in a UML diagram?
- the name is surrounded by double angle brackets - <>
253
What is an abstract class?
A class that guides the design of subclasses but cannot itself be instantiated as an object.
254
What does the protected access modifier allow access to?
Derived classes and all classes in the same package
255
Which super class members does a derived class have access to?
Public and protected
256
What is a member accessible to if no access specifier is listed?
Self and other classes in the same package.
257
Which access modifier cannot be used on classes?
- Protected. - Instead, do not specify the access modifier. This will make the class accessible to other classes within its package.
258
When overriding a method, which annotation should be used?
@Override
259
What is abstraction?
Abstraction means to simplify reality and focus only on the data and processes relevant to the program being built.
260
What does polymorphism mean?
A subclass can implement an inherited method in its own way.
261
What does encapsulation mean?
Data and the programs that manipulate those data are bound together and their complexity are hidden.
262
True or False: A subclass inherits it's superclass' constructor.
False, but it can invoked from the subclass.
263
How do you create a mutable class that cannot be subclassed?
Use the final keyword on the class declaration.
264
Parents (can/cannot) call child methods.
Cannot
265
Parents (can/cannot) be assigned to child objects.
Cannot - Good: parentObj = childObj - Bad: childObj = parentObj
266
Method overloading is runtime or compile-time polymorphism?
Compile-time
267
Method overriding is runtime or compile-time polymorphism?
Runtime
268
What is hierarchical inheritance?
Multiple subclasses extend from a single superclass. For example
269
What must be done if you want a class to implement an interface but not provide implementation for one or more of it's methods?
The class must be declared as abstract.
270
What can you do in abstract classes that you cannot do in interfaces?
- Declare fields that are not static and final - Define public, private and protected concrete methods that are defined and implemented
271
What features are specific to interfaces in contrast with abstract classes?
- All fields are automatically public, static and final - All methods that you declare or define are public
272
What features do abstract classes and interfaces share?
- May contain methods declared with or without implementation - Cannot be instantiated
273
When should you consider using an abstract class?
- You want to share code among several closely related classes. - You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private). - You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
274
When should you consider using interfaces?
- You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes. - You want to specify the behavior of a particular data type, but not concerned about who implements its behavior. - You want to take advantage of multiple inheritance of type.
275
What is a non-static nested class called?
Inner class
276
What is a static nested class called?
Static nested classes (duh)
277
What is the syntax for creating a new inner class object if the inner class is not declared as static?
OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer.new InnerClass();
278
What is the syntax for creating a new inner class object if the inner class is declared as static?
OuterClass.InnerClass inner = new OuterClass.InnerClass();
279
What is the main purpose of packages?
- Group related classes - Avoid name conflicts - Write more maintainable code
280
How do you create a package?
- Choose a name for the package, in all lowercase letters - Put a package statement with that name at the first line of every source file you want to include within the package
281
How many package statements may a file contain?
One
282
How do event driven applications work?
- An event is generated with every keystroke, mouse click and window change. - The event object is passed to the event listener that has been created to handle that components events.
283
How do you create a JavaFX application?
- Import javafx.application.Application - Create a class that extends 'Application' - Call launch(args) in main. - Override the start(Stage primaryStage) method - In the start method, create a Group object representing the root. - In the start method, create a Scene object, passing in the root and optionally the height/width of the scene. - Add the scene object to the stage primaryStage.setScene(scene) - Show the contents of the scene primaryStage.show()
284
What is the javaFX stage?
The entire window, including the close, minimize and maximize buttons.
285
What is the javaFX scene?
The content within the stage
286
What is the start() method?
The entry point method where Java FX graphics code is written.
287
What is the stop() method?
An empty method that can be overridden. Here you can write logic to stop the application.
288
What is the init() method?
An empty method that can be overridden but you cannot create stage nor scene in this method.
289
What are 3 ways to terminate a JavaFX application?
- Close the last window of the application. - Platform.exit(): Preferred because the method below doesn't call stop(). - System.exit(init)
290
Which package contains the stage class?
javafx.stage
291
What method has to be called to show the stage?
show()
292
What argument must be passed to the start method?
Stage object
293
What package contains the Scene class?
javafx.scene
294
What steps need to be taken within the start method?
- Prepare a scene graph with the required nodes. - Prepare a Scene with the required dimensions and add the scene graph (root node of the scene graph) to it. - Prepare a stage and add the scene to the stage and display the contents of the stage.
295
Which parameters does the Scene constructor take? Which is mandatory?
- Root node (Mandatory) - Height (double type) - Width (double type)
296
What is the lifecycle of a JavaFX application?
- An instance of the application class is created. - Init() method is called. - The start() method is called. - The launcher waits for the application to finish and calls the stop() method.
297
What method should be called to allow users to close the application via the x button, but still run additional logic?
window.setOnCloseRequest(e -> { e.consume(); closeProgram(); }) closeProgram() is the method written by the person giving this tutorial. It has additional logic, like saving the file and confirming whether the user actually wants to close the application. setOnCloseRequest would normally close regardless of user selection made in closeProgram. e.consume() bypasses the auto closure so closeProgram() can handle what to do.
298
What is the base class for all nodes that have children in the scene graph?
Parent
299
What is a node in JavaFX?
A visual or graphic object of a scene graph
300
In which package are controls for skinning and theming JavaFX?
javafx.scene.control
301
What is FXML?
An XML-based declarative markup language for constructing a JavaFX application user interface.
302
How are inline CSS styles set?
Via the Node object's setStyle method.
303
What is the prefix for all JavaFX property names?
-fx-
304
True or False: An application can only have one scene.
False, an application can have multiple scenes but only one can be displayed at a time.
305
What needs to be imported to use the Pane class?
javafx.scene.layout.Pane
306
How do you add components to a pane?
pane.getChildren().add(outputField);
307
How do you set the scene to be displayed?
applicationStage.setScene(scene);
308
How do you set the application's title?
applicationStage.setTitle("Salary");
309
How do you display the application's window to the user?
applicationStage.show();
310
Which pane component positions graphical components into a 2 dimensional grid?
GridPane
311
What must be done after creating a GridPane?
Create the Scene object and pass the GridePane object as an argument.
312
What is an inset?
Spacing, or padding, between the outer edges of the grid and the window
313
How do you add padding between the outer edges of the grid and the window?
- import javafx.geometry.Insets - Create an insets object with 4 arguments representing top, right, bottom, and left padding in pixels. - Pass the insets object to the GridPane object's set padding method. gridPadding = new Insets(10, 10, 10, 10); gridPane.setPadding(gridPadding);
314
Which method is used to set the padding between columns?
- Horizontal gap between columns: gridPane.setHgap(10); - Vertical gap between rows: gridPane.setVgap(10);
315
What is the order of Insets constructor parameters?
Top, right, bottom, left padding
316
A JavaFX GUI component that supports user input generates an ___ to notify the program when a user interacts with the component, such as when pressing a button.
Action event
317
What is the import statement for the Button class?
import javafx.scene.control.Button
318
How do you implement a button?
- import javafx.scene.control.Button; - import javafx.event.ActionEvent; - import javafx.event.EventHandler; - Button buttonName = new Button("ButtonText"); - gridPane.add(buttonName, 0, 2); - Set and define an ActionHandler
319
What is the purpose of the ActionEvent object?
It notifies the program of the occurrence of a component-related event, such as a user pressing a button
320
What is the purpose of the EventHandler object?
It defines how a program should respond to specific events, such as an ActionEvent
321
How is the EventHandler specified for a Button object?
buttonObject.setOnAction() with the EventHandler object as the argument. The EventHandler object is declared and instantiated as an anonymous class within the setOnAction argument section.
322
What is the syntax for passing the EventHandler as an object to the setOnAction method?
buttonObject.setOnAction(new EventHandler() { @Override public void handle(ActionEvent event) { // Write event handling instructions here } });
323
What members can the EventHandler access? Which can it not?
- The enclosing class's members - Local variables or objects declared in the enclosing method, such as local variables in the start method.
324
What is the method used to make a text field editable?
setEditable(true)
325
How do you create a new alert?
- Alert alert = new Alert(AlertType.ERROR, "Enter a positive hourly wage value.");
326
What does the showAndWait() alert method do?
- Makes the Alert visible to the user and waits for the user's response. - The program resumes execution after the user presses the Alert's "OK" button, which closes the Alert window.
327
What is the initial step to create and run a new JavaFX Maven FXML application project in NetBeans IDE?
Select the "JavaFX FXML Application" template under the Maven category. This template sets up the basic project structure, including the necessary configuration files and directories to support JavaFX development.
328
What is the purpose of the App.java JavaFX file?
Contains the `main` method and extends the `Application` class. It sets up the primary stage and loads the initial scene, making it the entry point of the application.
329
What is the purpose of the PrimaryController.java file?
This file is associated with `Primary.fxml` and is responsible for handling user interactions and events defined in the UI layout. It serves as a controller in the MVC (Model-View-Controller) pattern.
330
What is the purpose of the Primary.fxml file?
This file is an XML-based layout file that defines the structure and appearance of the user interface. It separates the presentation layer from the application logic, allowing for a clean design and easier maintenance.
331
What is the purpose of the controller in the mvc architectural pattern?
The Controller acts as an intermediary between the View and the Model. It responds to user inputs, manipulates the data model as necessary, and updates the view accordingly.
332
What is the purpose of loadFXML?
The `loadFXML` method is designed to: - locate an FXML file based on the given filename - load its user interface components by initializing an `FXMLLoader` - return a `Parent` object that represents the root node of the FXML's UI structure.
333
What is the purpose of the launch() method?
Responsible for setting up the JavaFX runtime and environment. It triggers the `start(Stage stage)` method, where the primary stage and scene are configured and displayed. The method effectively initiates the JavaFX application lifecycle.
334
What 3 things are associated with each event?
- Source - Target - Type
335
Which package needs to be imported to use event?
javafx.event
336
What is the base class for JavaFX events?
Event
337
What is the general process for handling events?
Register a filter or a handler for an event # The operating or windowing system captures events and notifies listener objects when a type of event they are listening for has occurred # The listener is notified by calling the event handling method
338
What happens if no listener is subscribed for the event type?
The event is ignored
339
What does the target of an event need to implement?
EventTarget interface
340
What do Window, Scene and Node implement?
EventTarget interface
341
What are 6 types of events?
ActionEvent # MouseEvent # DragEvent # KeyEvent # ScrollEvent # TouchEvent
342
What are 3 ways to inform user that validation has failed?
- Alert (Not recommended) - Hidden label that becomes visible upon error, displaying an error message. - Hidden imageView that becomes visible upon error, with tool-tip error upon hovering
343
How do you create a ComboBox?
@FXML private ComboBox fxid; # private Observable comboBoxData = FXCollections.observableArrayList(); # Add data to the list comboBoxData.add(new DataType(parameters)); comboBoxData.add(new DataType(parameters2)); comboBoxData.add(new DataType(parameters3)); # Add list to the combo box fxid.setItems(comboBoxData); # Create a handler @FXML private void handleComboBoxAction() { Person selectedPerson = comboBox.getSelectionModel().getSelectedItem(); outputTextArea.appendText("ComboBox Action (selected: " + selectedPerson + ")\n"); } https://code.makery.ch/blog/javafx-2-event-handlers-and-change-listeners/
344
How are hyperlinks handled?
Same way you handle a button: Create a method, then set "On Action," under "Code" in SceneBuilder, to that method, prepended with a hash symbol.
345
Each ___ provides methods to observe changes made to its value. We can ___.
- Property - Listen for changes
346
True or False: Sliders have an ActionEvent
False, they have a Number called valueProperty that contains the current value of the slider.
347
What is the syntax for listening for a slider value change?
- @FXML private Slider slider; In the initialize() method add a ChangeListener: - slider.valueProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue observable, Number oldValue, Number newValue) { outputTextArea.appendText("Slider Value Changed (newValue: " + newValue.intValue() + ")\n"); } }); https://code.makery.ch/blog/javafx-2-event-handlers-and-change-listeners/
348
What argument does addListener() require?
A ChangeListener of type Number ChangeListener
349
ChangeListener is an ___ so we need to create a ___ that implements ChangeListener:
- Interface - Concrete class
350
Every ChangeListener must have an override method called ___ that will be called every time ___.
- changed() - a change occurs
351
What is the syntax for listening for TextField changes?
- @FXML private TextField textField; And this is how we can react to changes of the text. We’ll use a ChangeListener as described above (see Slider section): - textField.textProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue observable, String oldValue, String newValue) { outputTextArea.appendText("TextField Text Changed (newValue: " + newValue + ")\n"); } });
352
What is the syntax for creating ListViews?
- @FXML private ListView listView; - private ObservableList listViewData = FXCollections.observableArrayList(); - listViewData.add(new Person("Lydia", "Kunz")); listViewData.add(new Person("Anna", "Best")); listViewData.add(new Person("Stefan", "Meier")); listViewData.add(new Person("Martin", "Mueller")); - Set the data into the list. This must be in the initialize() method as this is the time when we can be suure that the variable listView is initialized with the ListView from the fxml file. listView.setItems(listViewData);
353
How do you listen for ListView element changes?
Similar to Sliders and TextBoxes listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue observable, Person oldValue, Person newValue) { outputTextArea.appendText("ListView Selection Changed (newValue: " + newValue + ")\n"); } });
354
The listener must implement ___ like ___ or ___.
- An interface - EventHandler - InvalidationListener
355
The source implements the ___.
- EventTarget interface
356
What is a source?
GUI objects (e.g., a Button object) which generate an ActionEvent
357
What is the EventHandler's only abstract method?
void handle(T event)
358
What is the benefit of creating the EventHandler class within another class?
- It has access to the enclosing class's members, including private - The inner class can be private to the rest of the application, preventing it from being instantiated directly
359
True or False You can have more than one inner class for EventHandlers.
True
360
When would you use an anonymous inner class instead of a standard inner class to implement an EventHandler?
If you will only ever create one object from each inner class.
361
What is an anonymous class?
A class that's defined right where you want to use it.
362
What can be used in place of an anonymous inner class?
Lambda expression
363
What is the syntax for creating an EventHandler using a Lambda expression?
clickMe.setOnAction(event -> { //Implementation code });
364
What is recommended when using a Lambda expression to create an EventHandler?
- Create a helper method containing the code you want to execute when the event is called. - Call the helper method in the Lambda expression clickMe.setOnAction(event -> handleClickMe(event));
365
What is the syntax for calling a helper method via a Lambda expression?
- clickMe.setOnAction(event -> handleClickMe(event)); - If only calling one method: clickMe.setOnAction(this::handleClickMe);
366
What are 5 ways to define an EventHandler?
- handle(this) & override the handle() method. - Private inner class (nested class) - Anonymous inner class - Lambda expression - Delegation class
367
What is a limitation of using the ViewController's handle() method?
Only one handle() method can be defined, which is not ideal if handling more than one type of event.
368
Describe the "Delegation class" method of implementing an EventHandler.
- Event handling is delegated to a public helper class - Classes are passed as objects of each other to communicate back and forth. - The helper class can only access public classes and fields.
369
What is an anonymous class?
- A class with no identifier for which only a single object can be created.
370
What is the syntax for implementing an EventHandler using a private inner class?
public class ViewController implements Initializable { @FXML private Button btn; @Override public void initialize(...) { btn.setOnAction(new BtnInnerHandler()); //anonymous object } private class BtnInnerHandler implements //private inner class EventHandler @Override public void handle(ActionEvent e) {...} }
371
What is an anonymous object?
An object with no reference identifier that can only be used at the time of object creation.
372
What is the syntax for creating a KeyEvent handler and check for a specific key press?
In initialize method: txtName.setOnKeyPressed(new TabKeyEvent()); private class TabKeyEvent implements EventHandler { @Override public void handle(KeyEvent event) { if (event.getCode() == KeyCode.TAB) { //What you want do } } }
373
What is the syntax for creating an anonymous inner class EventHandler?
txtEmail.setOnAction(new EventHandler () { @Override public void handle(ActionEvent event) { //Do stuff here } });
374
What is the syntax for creating an EventHandler using a delegation class?
//Within initialize method of view controller btn.setOnAction(new BtnDelegateHandler(this)); //Within completely new class class BtnDelegateHandler implements EventHandler { private ViewController app; public BtnDelegateionHandler(ViewController vcApp) { app = vcApp; } @Override public void handle(ActionEvent e) { app.printStatement(); } }
375
What are the two types of listeners?
- ChangeListener - InvalidationListener
376
When are listeners used?
When a value of a property changes
377
What is a ChangeListener called?
When a value of a property has been recalculated.
378
What 3 arguments are passed to a ChangeListener?
- The property whose value has changed - The previous value of the property - The new value of the property
379
How should you set up the project, using a Main class to call the application?
public class Main { public static void main(String[] args) { App.main(args) } }
380
In which package should the controller files be created?
Source Packages
381
Where should images be saved in your project?
Other Sources >src/main/resources/images
382
What type of folder should the images folder be?
A resource folder
383
In which method is the initial scene graph loaded?
start(Stage stage)
384
What is the setRoot method used for?
To swap out the scene graphs
385
What is the syntax of the setRoot method?
static void setRoot(String fxml) throws IOException { scene.setRoot(loadFXML(fxml)); }
386
What should the initial view controller have that will be accessible by the secondary view controller?
A static public method or a field that can be accessed by the other controller public void initialize(URL url, ResourceBundle rb) { btnLogin.setOnAction( (t) -> { try { if (!txtUserName.getText().isEmpty()) { LoginViewController.userName = txtUserName.getText(); App.setRoot("helloView") } } catch (IOException ex) { System.out.println(ex.getMessage()); } } }
387
How do you get a value in a second view controller from the first view controller?
Get the field value from the first view controller in the contructor of the second... For example, if the first view controller is called LoginViewController and has a public field userName, the constructor for HelloViewController would look like this: public HelloViewController() { helloName = LoginViewController.userName; }
388
What does a JAR file contain?
The compiled class files and all application resources (ie. images) The Java and JavaFX runtimes A launcher
389
What do you run in Netbeans to create a JAR file?
Clean and Build
390
What does Clean and Build use to package your build?
Options that are set as project properties
391
Review steps to create a JAR file
Pre-work week 12