CS180 Final Exam

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

What are the 3 binary tree traversals?

(The first) inorder traversal: states that the program checks the left node, then the root node, and then the right node (The second) preorder traversal: states that the program checks the root node, then the left node, then the right node (The third) postorder traversal: states that the program checks the left node, then the right node, then the root node

What is a Object I/O (Serialization)?

- Objects that you create or objects from a Java package - Done using ObjectOutputStream and ObjectInputStream - If it's done using your own class, you must include the implements Serializable keyword in the class header

What is a High Level File I/O?

- Primitive types, for File I/O such as int, long, short, double, char and even String - Normally use DataOutputStream and DataInputStream

What is a Low Level File I/O?

- Raw data - byte oriented - Mainly used FileOutputStream and FileInputStream to process data in and out of the file.

How would you use BorderLayout?

... //Container pane = aFrame.getContentPane() ... JButton button = new JButton("Button 1 (PAGE_START)"); pane.add(button, BorderLayout.PAGE_START); //Make the center component big, since that's the //typical usage of BorderLayout. button = new JButton("Button 2 (CENTER)"); button.setPreferredSize(new Dimension(200, 100)); pane.add(button, BorderLayout.CENTER); button = new JButton("Button 3 (LINE_START)"); pane.add(button, BorderLayout.LINE_START); button = new JButton("Long-Named Button 4 (PAGE_END)"); pane.add(button, BorderLayout.PAGE_END); button = new JButton("5 (LINE_END)"); pane.add(button, BorderLayout.LINE_END);

how would you use CardLayout?

//Where instance variables are declared: JPanel cards; final static String BUTTONPANEL = "Card with JButtons"; final static String TEXTPANEL = "Card with JTextField"; //Where the components controlled by the CardLayout are initialized: //Create the "cards". JPanel card1 = new JPanel(); ... JPanel card2 = new JPanel(); ... //Create the panel that contains the "cards". cards = new JPanel(new CardLayout()); cards.add(card1, BUTTONPANEL); cards.add(card2, TEXTPANEL);

default byte

0

default int

0

default short

0

default double

0.0d

default float

0.0f

default long

0L

What does bitwise return?

1 - if results are different 0 - otherwise

What will the following block of code print? for(int i = 0; i < 3; i++) { switch(i) { case 1: System.out.println("1"); case 2: System.out.println("2"); case 3: System.out.println("3"); } }

12323

Assume you have this line of code in your project: String eclipse = "Not IntelliJ!"; What would invocation of eclipse.length() return?

13

What is the last position in the following array? int[] array2 = new int[20];

19

What it recursion?

A method calling itself from inside itself

Stack or queue: What is the best data structure (and why) for keeping threads waiting to get a core (CPU) to run? A. A queue so that eventually each thread will move from back to front and get a core. --> We want threads to get a fair chance at running. B. A queue so that the run-time system can "peek" to see which thread will next be run. --> There is never any reason to "peek". C. A stack so that a thread can be popped off and quickly moved to a core. --> A stack is a terrible idea, since a thread could get pushed down and never get out. D. A stack so that the most recent thread that was running can run again soon. --> A stack is a terrible idea. E. A stack since it can hold more threads than a queue. --> A stack is a terrible idea.

A. A queue so that eventually each thread will move from back to front and get a core. --> We want threads to get a fair chance at running.

What is a difference between an abstract class and an interface? A. Fields in an interface are public final static (i.e., constants). Fields in an an abstract class can be private. B. A Java class must say that it "implements" an interface, but it must say that it "abstract extends" an abstract class. --> No. It just says that it "extends" an abstract class. C. A Java class can extend multiple abstract classes, but can implement only one interface. --> The other way around. A Java class can extend multiple interfaces, but can implement only one (abstract or concrete) class. D. An abstract class may have methods with method bodies. An interface may not have methods with method bodies. --> An interface may have default methods with method bodies. E. An abstract class must have fields. An interface is not required to have any fields. --> Neither is required to have fields.

A. Fields in an interface are public final static (i.e., constants). Fields in an an abstract class can be private.

In class Robot is a method that begins... public static void main(String[] args) { Which best describes method main()? A. Method main() is where program execution begins. --> Without a main method, your class is not a program. B. Method main() is the Constructor method of class Robot. --> That would be named Robot (the name of the class). C. Method main() must be the only method in class Robot. --> There can be lots of methods in class Robot. D. Method main() must be where all input/output is done. --> Input/output can be done in any methods in class Robot. E. Method main() must be the first method at the top of class Robot. --> The main method can be anywhere in the set of methods.

A. Method main() is where program execution begins. --> Without a main method, your class is not a program.

What is the primary benefit of using buffers for File I/O? A. The program runs faster. --> Performing fewer physical reads speeds up the program. B. The program uses less memory. --> No. Buffers make the program use more memory. C. All input data is kept in the file until needed. --> No. Some input data is read from the file before it is needed. D. All output data is immediately written to a file. --> No. Output data stays in the buffer and is only written when the output buffer is full (or flushed). E. The entire file is input at once. --> No. Only a portion of the file is input, just enough to fill the input buffer.

A. The program runs faster. --> Performing fewer physical reads speeds up the program.

A class can implement multiple interfaces. A. True B. False

A. True

Where is the best place to run the JFrame? A. on the Event Dispatch thread --> This is the best place! B. on the main program thread --> This could cause the JFrame to freeze occasionally. C. on the SwingUtilities thread --> SwingUtilities is a class, not a thread. D. on the ActionListener interface --> The ActionListener interface reports if a button has been pushed. It is not a thread. E. anywhere is fine --> Event Dispatch thread is the best place!

A. on the Event Dispatch thread --> This is the best place!

public final class Quiz { public static void main(String [] args) { String x = "Purdue"; String y = "Pete"; y = x; y.concat(" Pete"); System.out.println(y); } } What is the output of this program? A.Purdue B.Pete C.Purdue Pete D.Purdue Purdue E.Pete Pete

A.Purdue

What are the 6 action Listeners and their uses?

ActionListener (Button interaction), MouseListener (mouse entry/exit), MouseMotionListener (mouse movement), ItemListener(check boxes/radio buttons), DocumentListener (text fields), KeyListener (keyboard entry)

what are two ways to initialize an arrayList?

ArrayList<String> someList = new ArrayList<String>(); Or you can have Java infer it: ArrayList<String> someList = new arrayList<>();

Why would you use a LinkedList over an ArrayList?

ArrayLists can only hold specific types of data while LinkedLists can hold different types of data with fewer restrictions

What are Hashmaps and how do you use them?

Associative Arrays, or Hashmaps, are a way to use non-integer values as an index for storage of data

Does do-while loop execute at least once or upon entry of the loop?

At least once, this is due to the condition being checked at the end of the loop, rather than the beginning like a while loop

Suppose that s is a string variable pointing to the string "Indianapolis". What string does s.substring(3,8) return? I n d i a n a p o l i s 0 1 2 3 4 5 6 7 8 9 10 11 s.length() = 12 s.substring(3,8) --&gt; [3,7] "ianap" A. "Indiana" B. "ianap" C. "ianapo" D. "diana" E. "dianap"

B. "ianap" 0, 1, 2, 3 1, 2, 3, ,4 ,5 ,6, 7, 8

Suppose that r is an object of the Random class and that the species array was declared as follows... String[] species = { "pine", "elm", "spruce", "oak", "walnut", "cedar", "maple" }; What are all the possible values that r.nextInt(species.length) can return? r.nextInt(int n) returns a value in the range [0-n) ... that is ... 0, 1, 2, ..., n-1. species.length is 7. So, r.nextInt(species.length) can return any of the values 0, 1, 2, 3, 4, 5, 6. A. 1, 2, 3, 4, 5, 6, 7 B. 0, 1, 2, 3, 4, 5, 6 C. 0, 1, 2, 3, 4, 5, 6, 7 D. 0, 1, 2, 3, 4 E. "pine", "elm", "spruce", "oak", "walnut", "cedar", "maple"

B. 0, 1, 2, 3, 4, 5, 6

What is a proxy method? A. A recursive method. --> A proxy method is not recursive. B. A non-recursive method that calls the recursive method. C. The last method called in a recursive sequence. --> No. That's a recursive method. D. A method that calls itself sometimes, but not all the time. --> No. That's a recursive method. E. A method with no parameters. --> No. That's a 0-parameter method.

B. A non-recursive method that calls the recursive method.

Which of these is an example of Overriding? A. Class Person has a method changeAddress() and Class Student (a subclass of Person) also has a method changeAddress() but with a different signature --> This is an example of Overloading B. Class Person has a method changeAddress() and Class Student (a subclass of Person) also has a method changeAddress() with the same signature --> Overriding is when there is a method with the same signature in a subclass C. Class Student has a method changeAddress(), but its superclass Person does not have a method changeAddress() --> Has nothing to do with Overriding D. Class Person has a method changeAddress(), but its subclass Student does not have a method changeAddress() --> Has nothing to do with Overriding E. Class Student has a three methods named changeAddress() all with different signatures --> This is an example of Overloading

B. Class Person has a method changeAddress() and Class Student (a subclass of Person) also has a method changeAddress() with the same signature --> Overriding is when there is a method with the same signature in a subclass

public final class Question { public static void main(String [] args) { int sum = 0; for (int i = 0; i >=0; i++) { sum += i; } System.out.println(sum); } The following code will run infinitely. A. True B. False

B. False

Why in the MyArrayList class does the method reallocate() have a private access modifier? A. It must be private since it is called by the public method add(String). --> It is called by the public method add(String), but that is not why it is private. B. It is not to be run by someone who instantitates a MyArrayList object. --> A private method is hidden from someone who instantitates a MyArrayList object. C. It creates a new array which the variable strings is going to reference. --> It does create a new array which the variable strings is going to reference, but that is not why it is private. D. So that it cannot be called by any other method in the MyArrayList class. --> Private methods can be called by any other method (public or private) in a class. E. It uses the private field strings. --> It does use the private field strings, but that is not why it is private.

B. It is not to be run by someone who instantitates a MyArrayList object. --> A private method is hidden from someone who instantitates a MyArrayList object.

An algorithm must be "complete". What does that mean? A. It must give the right answer(s). --> This means that it is correct. B. It must handle anything that comes up. --> This means that it is complete. C. It must end, i.e., not run forever. --> This means that it will end. D. It must be understandable to the person who or machine that is going to execute it. --> This is true, but not what "complete" means. E. It must be written in a programming language. --> Not necessary. Algorithms are stated in lots of languages.

B. It must handle anything that comes up. --> This means that it is complete. C. It must end, i.e., not run

Which one of the statements about Java GUIs is true? A. The BorderLayout add method always requires two parameters (component, location). --> There is an overloaded version with only one parameter that adds to BorderLayout.CENTER, B. You can change the JFrame's layout manager to be GridLayout. --> See slide 61 for how to do that. C. Using the GridLayout manager always requires that you specify exactly how many rows and columns to use. --> No. setLayout(new GridLayout(0,4)); says "four columns per row, as many rows as it takes". D. If a JFrame has a JPanel using the default FlowLayout manager that is showing 3 components per row and the user makes the JFrame much larger, the components will get larger and there will still be 3 components per row. --> No. There will likely be more than 3 components per row. E. Putting a JPanel inside a JPanel is not allowed. --> No. I showed several examples of doing just that.

B. You can change the JFrame's layout manager to be GridLayout. --> See slide 61 for how to do that.

public class Point { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } public static void main(String args []) { Point point0; Point point1; point0 = new Point(0, 0); point1 = new Point(0, 0); System.out.println(point0 == point1); } } What is the ouput of this program? A. true B. false

B. false

The sum of two positive integers that is computed using Java will always be greater than both of the integers. A.True B.False C.Insufficient information is given to provide an answer D.Integers cannot be summed in Java E. None of the above

B.False

Which message type is used with this dialog? i OK A.ERROR_MESSAGE B.INFORMATION_MESSAGE C.WARNING_MESSAGE D.QUESTION_MESSAGE E.PLAIN_MESSAGE

B.INFORMATION_MESSAGE

What are the 7 different GUI BorderLayouts and what do they look like?

BorderLayout: Has a top long panel, a bottom long panel, and three panels horizontal in the middle BoxLayout: Displays everything from top to bottom CardLayout: Displays one thing on top and everything else in a row horizontally below with ample spacing FlowLayout: Displays everything in a horizontal list GridBagLayout: Displays in a grid format with rows and columns but the rows and columns are not all the same size GridLayout: Displays everything in equally sized rows and columns unless specified otherwise

Which reader type is best for high volumes of data?

BufferedReader

How do you define an abstract class?

By declaring all the abstract methods abstract String getDetails(); abstract int getAmount();

What value does this expression return? (double) (1/2) * 8 Remember that what is in parentheses will be done first. (1/2) is integer division and (because of truncation) is 0. The (double) cast will change that to 0.0 and, of course, 0.0 * 8 is still 0.0. A. 4.0 B. 4 C. 0.0 D. 0 E. 0.0625

C. 0.0

public final class Quiz { public static void main(String [] args) { String name0; String name1; name0 = new String("Logan"); name1 = new String(name0); if(name0 == name1) { System.out.print("A"); } else { System.out.print("B"); } System.out.print("C"); } } What is the output of this program? A. AB B. AC C. BC D. BA E. CB

C. BC

Which of these statements about Sockets and ServerSockets is correct? A. A ServerSocket constructor specifies the IP address (or DNS name) and port number. --> A ServerSocket constructor specifies ONLY the port number. B. Both clients and servers use both Sockets and ServerSockets. --> Servers use both Sockets and ServerSockets. But, clients use only Sockets. C. Both clients and servers use Sockets. A server uses a ServerSocket to wait for a client to appear. D. Servers use only ServerSockets and do not use Sockets. --> Servers use both Sockets and ServerSockets. E. A Socket object invokes the accept() method to try to connect to a server. --> Only ServerSocket objects use the accept() method.

C. Both clients and servers use Sockets. A server uses a ServerSocket to wait for a client to appear.

Searching for a Purdue student in one of four files simultaneously is an example of...? The only two types of Decomposition discussed were Task Decomposition -- Split the task into multiple subtasks. Each subtask runs different code. Domain Decomposition -- Each subtask runs the same code, but on different input. (Searching for a student in several files simultaneously would be done by using the same code -- run() method -- for different files.) A. File Decomposition B. Task Decomposition C. Domain Decomposition D. Search Decomposition E. Thread Decomposition

C. Domain Decomposition

Suppose that a main method encounters the statement t3.join(); Suppose that thread t3's run() method has completed running. What happens? t3.join(); means "wait here until t3 has completed running and then go on to the next statement". A. The main method waits for all running threads to complete their run() methods before proceeding B. The main method waits for any other thread to complete its run() method before proceeding C. The main method proceeds to the next statement following the t3.join(); statement D. Thread t3 is re-started E. All threads except t3 that are running are terminated

C. The main method proceeds to the next statement following the t3.join(); statement

Which of the following is the correct way to test if two string variables point to strings that say exactly the same thing? A. if (school.sameas(university)) --> Java has no sameas method that works for strings B. if (school.equals.university) --> equals is a method that needs a parameter in parentheses C. if (school.equals(university)) --> run the equals method for the school object comparing it to the university object D. if (school == university) --> NO! This checks to see if the school variable and the university variable contain the same address E. if (school = university) --> NO! The = operator is not a comparison operator

C. if (school.equals(university)) --> run the equals method for the school object comparing it to the university object

All the following are allowed overloads of method... void magnify (int x, String y, double z) ... except which one? A. String magnify (double z) --> same name, but 1 parameter B. void magnify (int x, String p, double q, int r) --> same name, but 4 parameters C. int magnify (int a, String b, double c) --> differs only in return type, not a valid overloading D. double magnify (int a, String b) --> same name, but 2 parameters E. void magnify () --> same name, but no parameters

C. int magnify (int a, String b, double c) --> differs only in return type, not a valid overloading

public static void main(String [] args) { ServerSocket serverSocket = new ServerSocket(0); Socket clientSocket; while(true) { clientSocket = serverSocket.XXX(); RequestHandler.handleRequest(clientSocket); } } What should replace XXX? A.bind B.open C.accept D.connect E.new

C.accept

what are some of the static constants that define resultant operations in JOptionPane?

CLOSED_OPTION, CANCEL_OPTION, YES_OPTION, and NO_OPTION

Which one of these is correct about return statements? A. All methods must have at least one return statement. --> No. See the correct answer D. B. A return statement must always be the last statement in a method. --> No. There can be more than one return statement and they can be anywhere in the method. C. A method with a void return type cannot have a return statement. --> No. See the correct answer D. D. A method does not need a return statement if it is a method with a void return type, but it may have one or more. --> In this case the return statements are used to leave the method from different points ... like early if something goes wrong. E. A method with an int return type may have some return statements that return ints and some that return nothing. --> No. Every return statement must return a value of the return type.

D. A method does not need a return statement if it is a method with a void return type, but it may have one or more. --> In this case the return statements are used to leave the method from different points ... like early if something goes wrong.

public final class Question { public static void main(String[] args) { String x; System.out.println(x); } } What is the output of this program? A.null B.0 C. Empty String D. Compile-time error E. Runtime error

D. Compile-time error

Which is correct about a HashMap<K,V> variable named map? A. Either K or V could be a primitive type. --> Both must be reference types (classes). B. map[K] = V; is the way to put a value in the data structure. --> No. map.put(K,V) C. V = map[K]; is the way to get a value from the data structure. --> No. map.get(K) D. K is like an array subscript and V is like the value at that subscript location. E. V must be a reference type, but K can be a primitive type. --> Both must be reference types (classes).

D. K is like an array subscript and V is like the value at that subscript location.

1 int x = 0; 2 System.out.println(x++); 3 System.out.println(++x); What does this code display on screen? In statement 1, x is given the initial value 0. In statement 2, x++ is a post-increment, meaning that the statement is executed as if the ++ were not there (printing 0) and then x is incremented, making it 1. In statement 3, ++x is a pre-increment, meaning that x is first incremented, making it 2 and then the statement is executed (printing 2). A. Prints 1, then 1 B. Prints 1, then 2 C. Prints 0, then 1 D. Prints 0, then 2 E. Prints 0, then 3

D. Prints 0, then 2

Which of the following follows from the rule "Catches must be ordered from the lowest subclass to the highest superclass"? A. There should be no catch handler for the Exception class after the try block. --> No. It is fine to have a catch handler for the Exception class. Just be sure to put it last. B. The catch handler for the StudentNotFoundException class should be after the catch handler for the Exception class. --> No. The Exception class catch handler will work for any exceptions. Don't put any catch handlers for other classes after it. C. The catch handler for the StudentNotFoundException class should be before the catch handler for the NullPointerException class. --> No. These have nothing to do with each other. The order of these two does not matter. D. The catch handler for the Exception class should be the last catch handler after the try block. --> The Exception class catch handler will work for any exceptions. Put it last! E. The catch handler for the Exception class should be the first catch handler after the try block. --> No. The Exception class catch handler will work for any exceptions. Don't put any catch handlers for other classes after it.

D. The catch handler for the Exception class should be the last catch handler after the try block. --> The Exception class catch handler will work for any exceptions. Put it last!

When should you use a do-while loop? A. When the loop is an indefinite loop. --> Can use either a while or do-while for an indefinite loop. Usually a while loop is better. B. When the loop is a definite loop. --> Use a for-loop for a definite loop. C. When you want to use a sentinel boolean variable as the loop conditional. --> A do-while loop usually does NOT use a sentinel boolean variable. D. When the loop must be executed at least once. E. When the loop body could be executed zero times. --> No. The body of a do-while loop is always executed at least once.

D. When the loop must be executed at least once.

int tryAgain = JOptionPane.showConfirmDialog(null, "Do you want to try again?", "Alert", JOptionPane.YES_NO_OPTION); If you have the statement above in your program, which of the following is the best way to check if the user clicked the NO button? A. if (tryAgain == 0) --> If you want to compare the int that was returned, the NO button would be 1. B. if (tryAgain == -1) --> If you want to compare the int that was returned, the NO button would be 1. C. if (tryAgain == JOptionPane.YES_NO_OPTION) --> This is the named constant you use to say that you want two buttons -- YES and NO. D. if (tryAgain == JOptionPane.NO_OPTION) --> This is the named constant you use to see if the user clicked the NO button. E. if (JOptionPane.NO_OPTION == 0) --> JOptionPane.NO_OPTION is the named constant for 1, indicating that the user clicked the NO button.

D. if (tryAgain == JOptionPane.NO_OPTION) --> This is the named constant you use to see if the user clicked the NO button.

A class that implements an Interface must have... A. a default method --> Default methods are not required B. methods with the same name as the methods declared in the Interface --> see D C. methods with the same signature as the methods declared in the Interface --> see D D. methods with the same signature and the same return type as the methods declared in the Interface E. methods with the same signature, same return type, and same parameter names as the methods declared in the Interface --> Parameter names need not be the same

D. methods with the same signature and the same return type as the methods declared in the Interface

(Should be known for the Exam) What does implements Iterable do?

Defines a class that can be iterated over, in a loop for example

Wheel wagon = new Wheel (17.5); What does the variable wagon contain? Remember that for Reference types (like the Wheel class) the variable contains the address where the object is located. A. 17.5 B. 17 C. 0.0 D. The string "Wheel" E. The address in memory where the Wheel object is stored

E. The address in memory where the Wheel object is stored

When should you use recursion? A. When the solution requires more than 50 lines of code. --> Number of lines of code not important. B. When the solution requires method A calling method B and method B calling method C. --> This is NOT recursion. C. When the solution is going to take one loop. --> Perfect job for an iterative solution. D. When the solution is going to take a loop inside a loop. --> Still a good job for an iterative solution. E. When the solution is going to take a lot of loops or you cannot determine how many loops you will need.

E. When the solution is going to take a lot of loops or you cannot determine how many loops you will need.

True or False - Arrays can only be a maximum of 3 dimensions.

False

How would you use FlowLayout?

FlowLayout experimentLayout = new FlowLayout(); ... compsToExperiment.setLayout(experimentLayout); compsToExperiment.add(new JButton("Button 1")); compsToExperiment.add(new JButton("Button 2")); compsToExperiment.add(new JButton("Button 3")); compsToExperiment.add(new JButton("Long-Named Button 4")); compsToExperiment.add(new JButton("5"));

How would you use GridLayout?

GridLayout experimentLayout = new GridLayout(0,2); ... compsToExperiment.setLayout(experimentLayout); compsToExperiment.add(new JButton("Button 1")); compsToExperiment.add(new JButton("Button 2")); compsToExperiment.add(new JButton("Button 3")); compsToExperiment.add(new JButton("Long-Named Button 4")); compsToExperiment.add(new JButton("5"));

Why would an OptionalDataException be thrown?

If the data was not received in the same order that it was sent

How to determine if a tree is empty?

If the root node is null otherwise if the root node is not null then the tree has links to 0 or more trees Think of it as an actual tree that hasn't established a good root system yet

When can you use recursion?

If there is a base case, or exit point for the method to stop running, you can use recursion to do this but if there is no base case or exit point, do it iteratively.

What are two ways of creating threads in java?

Implementing the Runnable() interface and through that, implementing the run() method or extending the Thread class

What is Network I/O?

It is a communication over remote sources utilizing the internet as a way to communicated between two computers

What is the purpose of the Canvas class?

It is used for letting the user draw on specific JPanels, through utilization of the paint(Graphics g) method. When doing so, remeber screen coordinates: - (0, 0) is the top left of your screen - Think of it like an array, (where the array goes has however many columns of pixels you have as rows in the array, and however many rows of pixels you have as rows in the array).

What is the first step in declaring a GUI window?

JFrame

What is the name of a simpler GUI system?

JOptionPane which is used by invocation of a variety of static methods in order to ask for specific input

What are the 5 types of JOptionPane windows?

JOptionPane.PLAIN_MESSAGE, JOptionPane.ERROR_MESSAGE, JOptionPane.INFORMATION_MESSAGE, JOptionPane.WARNING_MESSAGE, JOptionPane.QUESTION_MESSAGE

How would you use GridBagLayout?

JPanel pane = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); //For each component to be added to this container: //...Create the component... //...Set instance variables in the GridBagConstraints instance... pane.add(theComponent, c);

What is used to put data in specific places in a JFrame?

JPanels

How would you use BoxLayout?

JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(250, 80)); listScroller.setAlignmentX(LEFT_ALIGNMENT); ... //Lay out the label and scroll pane from top to bottom. JPanel listPane = new JPanel(); listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS)); JLabel label = new JLabel(labelText); ... listPane.add(label); listPane.add(Box.createRigidArea(new Dimension(0,5))); listPane.add(listScroller); listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); //Lay out the buttons from left to right. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(cancelButton); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(setButton);

What is a pattern that should be followed when using FileIO?

Java -----> Open -> Read \ > Write

Why use SwingUtilities.invokeLater(Runnable r)?

Java GUI code should be run on the Event Dispatch Thread (EDT). This is done in an attempt to handle the interaction between the user and the GUI on one thread, and the interaction between Java and the GUI on another thread, in which it sets up and composes the JFrame By using this, you must make your class implement Runnable

What is happening in this code? public void makeItRain(ArrayList<Money> myMoney) { ArrayList<Money> bills = new ArrayList<>(); for(Money m : bills) { m.tossInAirRecklessly(); } }

Java will invoke the tossInAirRecklessly() method for each Money object, invoking the specific implementation of whichever class the Money object was instantiated to

When creating your own data structure you will want to use either implement it using LIFO or FIFO? Wtf does this mean?

LIFO (Last in, First out): to access something in the middle of the list you will have to dig through it by popping off elements above it in the list this is where push() and pop() methods are used FIFO (First in, First out): think of it as a line, tather than placing elements in front, you are placing them at the end, at the new tail node

What are the three levels of FIle I/O?

Low Level High Level Object Level

(Should be known for the Exam) What does implements Serializable do?

Marks a class as something that will be transferred over a stream, such as a FileOutputStream or a Socket connection.

If you out elements in a HashMap in a certain order will they be in that order?

Most likely not

Can you extend more than one super class?

No

Are recursion and looping the same?

No, because you may be able to program a method iteratively, in a loop, but you may not be able to program it recursively and vice versa

what does immutable mean in terms of Strings?

Once you set a String to a specific value, you cannot change it character by character

What is the difference between Overloading and Overriding?

Overloading is when you have two methods of the same name, but different signature - that is, different(number and types of) parameters and return type. Overriding is when you have a method in the super class that you are writing in a child class to perform something different than the super class. Think about equals() or toString() methods. For overriding, the signature and name must be identical.

What is Reverse Polish Notion?

Reverse Polish Notion or RPN, is the way of doing mathematical operations via stack If the item in the stack is a number, add it to the stack. If the item in the stack is an operation, operate the last two operands using hat operation The best way to understand RPN is to convert from a standard, infix expression(using PEMDAS), to an RPN expression

What are the three different node types and what are they?

Root Node : a node with no parents Leaf Node : A node with no children Interior Node : A node that can't be classified as either of the two examples above

What is a good way to prevent Server lag and blocking?

Servers service each of their clients on individual threads this way no Clients will suffer server lag or blocking

What happens if one client is "linked" to more than one server?

StreamHeaderException

what is an example of a 2D array?

String[][] array = new String[10][10];

what is an enhanced for loop?

The enhanced for loop can be used to iterate over a set of data, like a list or an array. It can also be used for any class that implements the Iterable interface public void enhancedForLoop() { int[] arrayOfNumbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i : arrayOfNumbers) { System.out.println(i); } }

If you extend a class what must you put in the sub classes constructor?

The first line must be an explicit call to the super class's constructor, via the super() call

What is the head node and tail node in terms of positions in a LinkedList?

The head node tells the LinkedList what is the first element in the list, and the tail node tells the LinkedLsit the last element in the list.

In Binary Search Trees what properties does the key element posses?

The key has a child that is a binary search tree The key in the left child of the root node is smaller than the root The key in the right child of the root node is bigger than the root

What do the head and tail node mean in terms of adding things to the LinkedList?

The tail node represents the first item placed in the list, while the head node represents the most recently placed item in the list

What is in a methods signature?

Their name, their number, order and types of their parameters

What is the point of ActionListeners

They Listen for actions from J-Utilities

How does a Hashmap or Associative Array get initialized?

They are instantiated in the same way as an ArrayList in that they must be initiliazed using the <t1, t2> brackets HashMap<String, Integer> map = new HashMap<>(); map.put("Zero", 0); map.put("One", 1); The first element, t1, defines the key that represents the index of the element in the HashMap The second element, t2, defines the definition of the t1st element

How are Sockets used?

They are used to connect to a Server

What is in a LinkedList?

They have a head and a node. Each node represents an element in the array

Java GUIs are modal. What does this mean?

They will halt the execution of the program until the window is closed or an action is executed on the window

What does having a default method in an interface mean?

This defines the method to contain code that does not have to be implemented every time. public interface anInterface { default public void displayNameDefault(String name) { System.out.println("Your name is " + name); } public void displayName(String name); public void displayNameAndJobTitle(String name, String jobTitle); }

What happens if SwingUtilities.invokeLater(...) is not used therefore the program is not on the EDT?

This may result in program failure, possible lag, and overall worse performance

A file needs to exist in order to read it (FileIO)

True

True or False - HashMaps are thought of as multi dimensional ArrayLists

True

True or False? Arrays have set sizes.

True

True or False - Network I/O and File I/O are very similar.

True, in fact the methods and classes you use for File I/O can be used for Network I/O and the same logic applies when doing Network I/O as you did with File I/O. If you use ObjectInputStream and ObjectOutputStream, data must be read in the same order as it was written.

What is Server-Client interaction?

When one computer is the server, and the other computers connect to it.

When do Race conditions occur?

When shared data is accessed by different threads simultaneously Another way of putting it is two threads racing to update a field or get the newest value of a field

what is a ragged or jagged array?

When the columns are not the same amount for each row int[][] raggedArray = new int[3][]; raggedArray[0] = new int[5]; raggedArray[1] = new int [3] raggedArray[2] = new int[4];

Can you implement multiple interfaces?

Yes

What is it called when you are running the program with threads?

You are running the program concurrently

When running a program normally what is this called?

You are running the program sequentially

What are data trees?

You can think of trees much like a dictionary - there are groups defined by each letter, and each of the words that start with that letter a node in that group, representing one element.

How do you create a Socket?

You must construct a Socket object with a specific constructor of an IP address (193.180.251.182) and a port (at max 65536) This allows someone to connect and communicate over a network

How to make a Server?

You need to use a ServerSocket object. Once this object is created you must specify that you are accepting connections on the Server by invoking the accept() method on the ServerSocket object

default char

\u0000

Given a binary tree like the following, which is the correct inorder traversal of the tree? 1 2 / \ 3 4 / \ 5 a) 4-2-5-1-3 b) 4-5-2-1-3 c) 1-2-3-4-5 d) 5-4-2-1-3

a) 4-2-5-1-3

Evaluate the following RPN Expression: 42 42 + 42 + 180 + 3 * + 10 + a) 856 b) 4242 c) StackOverflowException d) 158

a) 856

When making a thread halt execution for a specified amount of time, what do you have to do to ensure your program doesn't crash after the thread "reawakens"? a) Catch an InterruptedException b) Use the t.start() method again c) Use the t.join() method to have the method play "catch-up" d) Catch an IOException

a) Catch an InterruptedException

What is the most common behavioral interaction between two computers performing I/O Tasks over a network? a) Client-Server interaction b) Server-Client interaction c) Peer-to-Peer interaction d) Client-Queue-Client interaction

a) Client-Server interaction

If you have a binary tree that you must traverse, whihc is the most efficient way of traversal? a) Inorder traversal b) Preorder traversal c) Postorder traversal d) All traversal methods are jsut as efficient as the others.

a) Inorder traversal

When reading from a file what do you have to do before reading? a) Make sure the file exists b) Attempt to read data from the file before writing c) Ensure that you flush every write statement d) Verify that the file is empty before writing to it

a) Make sure the file exists

Which of these exception(s) is unchecked almost always? a) NullPointerException b) IOException c) StackOverflowException d) All of the above are checked exceptions

a) NullPointerException

If you don't read data in the same order it was written in, what will happen? a) OptionalDataException thrown b) IOException thrown c) Nothing will happen d) Your program will lag

a) OptionalDataException thrown

When performing an append operation on a file during the writing process, which are valid ways of doing this? a) Read all the data into an ArrayList, and append the data into the list, which you would then overwrite the file with. b) Write to the file using the append operation of a writer that supports this. c) Write to the file, and hope the writer doesn't delete past data. d) Do a check on whether the file already has data in it - if it does, read that in, and then write new data to the file, including the old data.

a) Read all the data into an ArrayList, and append the data into the list, which you would then overwrite the file with. b) Write to the file using the append operation of a writer that supports this. d) Do a check on whether the file already has data in it - if it does, read that in, and then write new data to the file, including the old data.

Which of these interfaces require implementation of 0 methods? a) Serializable b) Iterator c) Comparable d) Runnable

a) Serializable

What exception will be thrown if the client you write from changes between writes? a) StreamHeaderException b) OptionalDataException c) IOException d) No exceptions will be thrown

a) StreamHeaderException

If you have a binary tree with a root node that is null, what can you infer from this? a) The node has no children b) The node cannot be searched - it is almost like it is "locked off" c) The node has an infinite amount of children, and in an attempt to prevent the system from crashing, Java has turned the root node null. d) The node has no parents.

a) The node has no children

Which of the following loops is best for handling large data sets with an unknown size? a) for-each b) for c) while d) do-while

a) for-each for (int i : array){}

What is the name of the node with no children? a) leaf node b) child node c) rood node d) guardian node

a) leaf node

What is the methode used for removing an item from the top of the Stack? Assume your stack object is called stack. a) stack.pop() b) stack.push() c) stack.dequeue() d) stack.removeFirst()

a) stack.pop()

Suppose you have two constructors, one that takes an integer, and one that takes an integer and a String. How can you call the two parameter constructor from the one parameter constructor? Assume the integer is called num, and the String, str. a) this(num, str) b) super(str, num) c) this(str, num) d) super.this(str, num)

a) this(num, str)

For Stacks what is used to add method, remove method, and look for method?

add: Push remove: Pop look: Top, Peek

For Queues what is used to add method, remove method, and look for method?

add: Put, Enqueue remove: Get, DeQueue look: Peek, Front

For Deques(Stack) what is used to add method, remove method, and look for method?

add: addFirst remove: removeFirst look: peekFirst

For Deques(Queue) what is used to add method, remove method, and look for method?

add: addLast remove: removeFirst look: peekFirst

define serialization

allows us to convert an Object to stream that we can send over the network or save it as a file or store in a database for later usage

Evaluate thr following RPN Expression: 11 22 + 33+ a) 1155 b) 66 c) 39 d) 112233

b) 66

What is the concept called for Java deciding which method to use when incorporating a list of an abstract class? a) Static Binding b) Dynamic Binding c) Dynamic Decision Making d) Static Decision Making

b) Dynamic Binding

What do you have to do to ensure that data is written to a file every time? a) Make sure the file exists b) Ensure that you flush after every write statement c) Verify that the file is empty before writing to it

b) Ensure that you flush after every write statement

What is the name of the exception that is thrown if the file does not exist, when reading data from the file? a) ArrayIndexOutOfBoundsException b) FileNotFoundException c) OptionalDataException d) No exceptions are thrown

b) FileNotFoundException

When using a try-with-resources statement, what block is implied? a) Catch Block b) Finally Block c) No code blocks are implied d) Try Block

b) Finally Block

Can you have two methods with the same name in the same class? a) No, Java doesn't allow this and your code will not compile. b) Yes, provided that each methods signatures are different c) No, because Java will not know which method to go to upon call. d) Yes, because Java is smart enough to decide which one to choose based on the program's execution

b) Yes, provided that each methods signatures are different

When working with super classes, what is the modifier used to indicate that a method must be written in a child class? a) static b) abstract c) implements d) super.methodNameHere();

b) abstract

Which of the following is not a loop in Java? a) for-each b) for-every c) for d) while

b) for-every

What is the name of the node with a parent and a child? a) anterior node b) interior node c) root node d) child node

b) interior node

What is the name of the node with no parents? a) parent node b) root node c) child node d) leaf node

b) root node

Which of these methods do you use for making a Thread wait until another one finishes? Assume your thread object is called t. a) t.start() b) t.join() c) t.yield() d)t.run()

b) t.join()

Which of these methods do you use for making a thread wait for a specified amount of time before resuming? a) t.join() b) t.sleep(....) c) t.yield() d) t.interrupt()

b) t.sleep(....)

What can be used to speed up searches and analysis of large data sets?

by using trees of data

WHat is another name for HashMaps? a) Dynamic Arrays b) Two Dimensional ArrayList c) Associative Arrays d) Generic Arrays

c) Associative Arrays

Which of the following will not result in a StackOverflow Exception being thrown? a) Calling a method from inside itself without a base case b) Creating an object of the same type inside its constructor c) Calling a method from inside itself with a given base case d) Having a GUI indirectly recursively call a method that would call a method that would call a method.... and so on

c) Calling a method from inside itself with a given base case

What is the name of the thread on which all GUI based interactions between the user and the program should occur? (HINT, the abbreviation is EDT) a) Event Detail Thread b) Event Description Thread c) Event Dispatch Thread d) Event Debut Thread

c) Event Dispatch Thread

When writing a method with the same name and same signature as that of the super class in a child class, what is this concept called? a) Overloading b) Method overloading c) Method Overriding d) This concept is not allowed in Java

c) Method Overriding

Getter and Setter methods are also called ______ and ______. a) access modifier and deaccess modifier b) grabbers and placers c) accessor and mutator d) mutator and accessor

c) accessor and mutator

Which of the following is the modifier to determine an unchangeable, final, value? a) default b) public c) final d) static

c) final

Which JFrame method puts all the components in their preferred space based on the selected layout manager? Assume your JFrame object is called frame. a) frame.createRootPane() b) frame.setVisible(...) c) frame.pack() d) frame.update(...)

c) frame.pack()

How can you ensure that resources are shut off before program ends? a) Use the reader's close() method, or the equivalent. b) Use a try-wtih-resources statement c) Hope that your program closes all resources d) A and B

d) A and B

Evaluate the following RPN Expression: 30 x 400 1560 + a) 13560 b) 624030 c) 12000 d) Cannot compute RPN Expression

d) Cannot compute RPN Expression

When using a standard try-catch clause, what is guaranteed to run after every try-catch statement? a) Try Block b) The throws statement c) Catch Block d) Finally Block

d) Finally Block

What does the <> brackets in a definition of an ArrayList mean? a) Inferred data types from the initialization b) Part of the ArrayList class c) Defines something as a list d) Generic brackets defining data type

d) Generic brackets defining data type

What is the name of the exception that is thrown is the file cannot be found, when writing data? a) ArrayIndexOutOfBoundsException b) FileNotFoundException c) OptionalDataException d) No exceptions are thrown

d) No exceptions are thrown

Which of the following is the data type used for holding a single character? a) Strings b) char c) int d) all of the above

d) all of the above

Which of the following is the loop where at least one execution is guaranteed? a) for-each b) for c) while d) do-while

d) do-while

Which of the following is considered to be part of the method signature? a) throws declaration b) access modifier c) final modifier d) method name

d) method name

What is the default access modifier for a method? a) public b) private c) static d) package-private

d) package-private

Does for loop execute at least once or upon entry of the loop?

execute at least once except if the conditions in the for(int i = 0...) is not executable

What does the class extend when writing a custom exception?

extends Exception

What will the following block of code do? if (0b10 != 0b1) System.out.println("false");

false

default boolean

false

A file needs to exist in order to write in it (FileIO)

false the file doesn't have to exist, and once the data is flushed to the file, the files will be created.

Should methods and fields be public or private by convention?

fields should be private and methods should be public

define final

final, for making methods or fields, non modifiable. The values there are considered final, and once initiated, cannot be modified.

what does using final in a field mean?

if a field is final, it cannot be modified in a method, and must be initialized at the time of declaration You can also assign final fields inside a constructor, barring the fact that their value cannot be changed at a later time in the program

Strings are...

immutable, Objects, Not Primitive Types, Made up of letters

Go over check whether specific value is in tree

in the coding folder

Name 8 primitive types in Java

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

what are three ways to initialize an array?

int[] array1 = {1, 2, 3, 4, 5}; int[] array2 = new int[20]; int[] array3 = new int[]{1, 2, 3, 4, 5};

What can boolean evaluation in if statements use?

logical operations (AND &&, OR ||) or Bitwise (AND &, OR ^, OR |)

what is used to loop through a 2D array?

matrix.length and matrix[0].length

How do you use instanceof in terms of inheritance?

public class Employee extends Person{} By using the instanceof keyword here , you would be able to tell if an object of the Person class is an instance of an Employee

write a getter method or accessor method

public int getAnInt() { return anInt; }

write a setter method or mutator method

public void setAnInt(int value) { anInt = value; }

What are the two most common methods to use for ArrayLists?

set(): changing a value at a specific index add(): add an element in between specific indicies, implicitly shifting all elements right by one.

What are 6 basic but usefule methods for JFrame?

setResizable(...); setSize(...); setDefaultCloseOperation(...); setVisible(...); setTitle(...); add(...);

How to avoid race conditions?

shared data should have synchronized keyword. Think of it like a gatekeeper, in where only one thread is allowed to modify the field or get the newest data at a time.

What are some commonly used JOptionPane methods?

showMessageDialog(), showInputDialog(), showConfirmDialog(), and showOptionDialog()

What is the name of errors that are reported in the code?

stack trace

define static

static, for making methods accessible without object declaration, In other words, they are class level methods.

-> switch statements

switch(number) { case 0 -> System.out.println("zero"); case 1 -> System.out.println("one"); default -> { case 11, 13, 15 -> System.out.println("An odd number"); case 12, 14, 16 -> System.out.println("An even number"); } }

How to write switch statement?

switch(str) { case "CS180": //print something break; default; //print something break; }

What are the four most useful methods to you in thread management for a Thread object called t?

t.start(), which starts the Thread and invoke the run() method t.join(), which waits for another Thread to finish before executing t.yield(), which pauses the execution of the Thread t.sleep(....), which pauses the Thread for a parameterized amount of time in milliseconds

what does final do in a try catch block?

the code in final clause will run everytime

define transient

transient, if an object is going to be serialized, fields marked with the transient modifier will be excluded when the object is written. In other words, it indicates a field that should not be persistent between serialization.

example of a try-with-resources block

try (PrintWriter writer = new PrintWriter(new File("Test.txt"))) { writer.println("Hello World") } Resources are allocated inside the parenthesis of the try block, and are automatically close at the ends of the try block or if the catch blocks executes

What is an example of a try catch?

try { //code } catch (Exception e) { //do something }

Does while loop execute at least once or upon entry of the loop?

upon entry of the loop

what does using static in a field mean?

using static with fields means that the field is at a class level an can be accessed without creation of an object

when is && used?

when both or all conditions must be evaluated as true in order for the conditional to evaluate true

when is || used?

when one or both conditions must be evaluated as true in order for the conditional to evaluate true

What are the four different types of loops?

while, do-while, for, Enhanced for loop (also called for-each loop)


संबंधित स्टडी सेट्स

Midterm Part 2 American Government (REAL)

View Set

Viruses, lytic and lysogenic cycles

View Set

Tort 4: Negligence: causation and remoteness of damage

View Set

Microbial communities chapter 19a

View Set

Царство грибов(9-6)

View Set

Module 8; Chapter 10 Econ Homework

View Set