Advanced Java Programming,

Ace your homework & exams now with Quizwiz!

Precedence of B. Op

! && ||

Not Equal to

!=

What is the one-time cost for a developer's account at Google Play?

$25.00

How much is Amazon's annual fee for a developer account?

$99.00

Modulo

%

And

&&

cast object type for readObject()

(Product)in.readObject()

Sequential Search Algorithm

*Search ends when found or end is reached without finding element *Can search an unsorted array

all of the classes in the *exception class hierarchy* inherit from the _____ class

*Throwable* class (683)

the _____ is an internal list of all the methods that are currently executing

*call stack* (699)

catch clause [code]

*catch (ExceptionType ParameterName)* (684) ~(name of exception class.....variable name)

_____ is the process of reconstructing a serialized object

*deserialization* (712)

_____ is the process of converting an object to a series of bytes and saving them to a file

*object serialization* (712)

*throws* [code]

*public void displayFile(String name) throws* *FileNotFoundException* (703) ~if there is more than 1 type of exception, you separate them with commas

_____ is a file that allows a program to read data from any location within the file, or write data to any location within the file

*random access file* (712)

the _____ method returns the deserialized object

*readObject* method (725) ~throws a number of different exceptions if an error occurs

a(n) _____ is a list of all the methods in the *call stack*

*stack trace* (699) ~it indicates the method that was executing when an exception occurred and all of the methods that were called in order to execute that method

*throw statement* [code]

*throw new Exception("Out of fuel");* (704) throw new ExceptionType(MsgString);

general format of a try statement with a finally clause [code]

*try {* -->*try block statements* *} catch (ExceptionType ParameterName) {* -->*catch block statements* *} finally {* -->*finally block statements* *}* (697)

general format of the try statement [code]

*try {* -->*try block statements* *} catch (ExceptionType ParameterName) {* -->*catch block statements* *}* (684)

general format of the *seek method* [code]

*void seek(long position)* (721)

Addtion

+

Subtraction

-

Greater than

>

Greater than or equal to

>=

Which of the following is not a wildcard type?

? sub B

What is the order Java looks for a match for overloaded methods?

1) exact match 2) match a superclass type 3) expand to larger primitive 4) autoboxed type 5) var args

What are the 3 rules for overriding methods?

1) return type - same or subclass (covariant) 2) exception - throws same or subclass 3) access modifier - same or more accessible

Consider a List that implements an unordered list. Suppose it has as its representation a singly linked list with a head and tail pointer (i.e., pointers to the first and last nodes in the list). Given that representation, which of the following operations could be implemented in O(1) time? 1. Insert item at the front of the list 2. Insert item at the rear of the list 3. Delete front item from list 4. Delete rear item from list

1,2,3

to *open a binary file for input*, you can use the following classes including:

1. *FileInputStream* 2. *DataInputStream* (715)

to *write data to a binary file* you must create objects from which classes:

1. *FileOutputStream* 2. *DataOutputStream* (713)

Implementing an interface

1. Include the phrase 2. Define each method declared in the interface(s). (i.e. public class Rectangle implements Measurable)

What modifiers may be used with an inner class that is a member of an outer class?

A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

a

A .................... manages the threading for the servlets and JSPs and provides the necessary interface with the Web server. a. Web Container b. EJB Container c. Servlets d. Applets

value, elements

A method can change the ______ of the ______ in an array argument

method; definition of the method

A variable's type determines what __________ names can be used, but the object the variable references determines which ___________ will be used.

abstract

A(n) ______________ method must be overridden by any non_______ derived class and given a definition *If a class has at least one ______ method the class must be declared to be ______ *has no body *You cannot create objects of that class; can only be a bass class

What method must be implemented by all threads?

All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.

Forgetting to set the reference instance variable of the last node in a linked list to null will cause a compile-time error. (program will not compile.) T or F

False

True or False: A toast notification is also called a muffin message.

False

True or False: You can select one or more radio buttons at one time in a RadioGroup control.

False

When using a linked list, you do not need to know when the end of the list has been reached. T or F

False

What does null instanceof Object return?

False null is not an object

True or False: This is the proper way to initialize an array: doubles { } driveSize = ["32.0", "64.0", "128.0"];

False (double[] driveSize = { "32.0", "64.0", "128.0" };)

True or False: URL stands for Unified Resource Locator.

False (Uniform Resource Locator)

True or False: Hexadecimal color codes are defined as a triplet of three colors using hexadecimal numbers, where colors are specified first by a ampersand sign followed by how much red (00 to FF), how much green (00 to FF), and how much blue (00 to FF) are in the final color.

False (it's a pound sign!)

True or False: There are 7 drawable folders available in the res folder.

False (there are 5 for low-, medium-, high-, extra high-, and extra extra high-density screens: ldpi, mdpi, hdpi, xhdpi, and xxhdpi respectively)

file object definition

File fileObject = new File(path name)

Which of the following reads binary data from a disk file?

FileInputStream inputStream = new FileInputStream("input.bin");

what occurs in buffered text writing stream

FileWriter object created, passed to BufferedWriter constructor, BufferWriter object passed to PrintWriter constructor, creates PrintWrter object (stream layering/wrapping)

<Date>

Fill in the code in Comparable______ c = new Date();

recursiveBinarySearch(list, key, low, high)

Fill in the code to complete the following method for binary search. public static int recursiveBinarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; return __________________________; } public static int recursiveBinarySearch(int[] list, int key, int low, int high) { if (low > high) // The list has been exhausted without a match return -low - 1; // Return -insertion point - 1 int mid = (low + high) / 2; if (key < list[mid]) return recursiveBinarySearch(list, key, low, mid - 1); else if (key == list[mid]) return mid; else return recursiveBinarySearch(list, key, mid + 1, high); }

(s.charAt(0) != s.charAt(s.length() - 1)) // Base case

Fill in the code to complete the following method for checking whether a string is a palindrome. public static boolean isPalindrome(String s) { if (s.length() <= 1) // Base case return true; else if _____________________________ return false; else return isPalindrome(s.substring(1, s.length() - 1)); }

isPalindrome(s, low + 1, high - 1)

Fill in the code to complete the following method for checking whether a string is a palindrome. public static boolean isPalindrome(String s) { return isPalindrome(s, 0, s.length() - 1); } public static boolean isPalindrome(String s, int low, int high) { if (high <= low) // Base case return true; else if (s.charAt(low) != s.charAt(high)) // Base case return false; else return _______________________________; }

C. fib(index - 1) + fib(index - 2) D. fib(index - 2) + fib(index - 1)

Fill in the code to complete the following method for computing a Fibonacci number. public static long fib(long index) { if (index == 0) // Base case return 0; else if (index == 1) // Base case return 1; else // Reduction and recursive calls return __________________; }

C. n * factorial(n - 1) D. factorial(n - 1) * n

Fill in the code to complete the following method for computing factorial. /** Return the factorial for a specified index */ public static long factorial(int n) { if (n == 0) // Base case return 1; else return _____________; // Recursive call }

Which of the following classes are used with data in binary form? I FileInputStream II FileReader III RandomAccessFile

I and III

Erasure of types limits Java code somewhat with generics. Which of the following are limitations of generic code? I cannot instantiate a type variable II cannot return a type variable III cannot pass a type variable

I only

Consider an old fashioned telephone booth that can be occupied by one person at a time. Suppose one person went in and dialed a part of her number, and had to leave the booth. A second person went in and dialed a part of his number, and before the number was fully dialed, a connection to some other phone was made. What Java threads analogy fits this scenario? I The two people are the threads II The shared data is the telephone III The state of the object is corrupt

I, II, III

Suppose a linked-list class called MyLinkedList with a generic E type has been instantiated with a java.awt.Component type variable. Consider its instance method locate with the following header: public void locate(MyLinkedList<? extends E>) { . . . } Which type cannot be passed to method locate? I MyLinkedList<JButton> II MyLinkedList<Component> III MyLinkedList<JTextField>

I, II, and III

Consider the following code snippet: public static <E> void print(E [] a) { for (int i = 0; i < a.length; i++) { System.out.println(a[i] + " "); } } int[] a = {3,6,5,7,8,9,2,3}; String[] s = {"happy","cat","silly","dog"}; Boolean[] b = {true, true, false}; Which of the following are correct calls to this generic print method? I print(a); II print(s); III print(b);

II and III only

Which method(s) are part of the Thread class? I public void run(Runnable runnable) II public void start(Runnable runnable) III public void start()

III

When you communicate with a web server to obtain data, you have two choices: I) You can make a socket connection and send GET and POST commands. II) You can make a server connection and send GET and POST commands. III) You can use the URLConnection class and have it issue the commands on your behalf. IV) You can use the URL class and have it issue the commands on your behalf.

III and I.

internet protocol

IP is an acronym that stands for _____ _____.

What is the property that defines the name of a Button control?

Id

No Explanation: It is illegal to refer to a generic type parameter for a class in a static method or initializer, because generic type for a class belongs to a specific instantiation of the class.

If E is a generic type for a class, can E be referenced from a static method?

What is the catch or declare rule for method declarations?

If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

clients and servers servers

Generally, the Socket and DatagramSocket classes are used to implement both _____ and _____, while the ServerSocket class is only used to implement _____.

Socket DatagramSocket ServerSocket

Generally, the _____ and _____ classes are used to implement both clients and servers, while the _____ class is only used to implement servers.

The Collection Classes : LinkedList

Implements a linked list by extending AbstractSequentialList.

The Collection Classes : TreeSet

Implements a set stored in a tree. Extends AbstractSet. -Access and retrieval times are quite fast -sorted in an ascending order according

The Collection Classes : AbstractCollection

Implements most of the Collection interface.

The Collection Classes : AbstractMap

Implements most of the Map interface.

mutually acceptable communication

In order for two or more computers connected to a network to be able to exchange data in an orderly manner, each computer must use a _____ _____ _____ protocol. The protocol defines the rules by which they communicate.

Where is the newDocumentBuilder method?

In the DocumentBuilderFactory class.

What is the difference between the client-server architecture and the three-tier architecture?

In the client-server architecture, each client program has a presentation layer.

n is 1.

In the following method, what is the base case? static int xMethod(int n) { if (n == 1) return 1; else return n + xMethod(n - 1); }

Does this override Object's equals method? public boolean equals(Lion l) { // code here }

No, it overloads it. Parameter must be an Object o

Can hashCode() use more instance variables for comparison than equals(Object o)?

No, often hashCode() uses less than equals(Object o)

!

Not

value of readObject()

Notice that the return _______ is cast to an Employee reference.

Classes often correspond to ____ in a requirements description.

Nouns

What is numeric promotion?

Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

The two IO classes used for serialization are ___ and ___.

ObjectInputStream, ObjectOutputStream.

writing object to file definition

ObjectOutputStream out = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream("file.dat")))

How are Observer and Observable used?

Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

a

Objects with application scope are part of a particular Web application. a. True b. False

accessor, mutator

On the OneWayNoRepeatsList class you access the arrays using ___________ and _________ methods

If an object is garbage collected, can it become reachable again?

Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

Which of the following statements about linked lists is correct?

Linked lists should be used when you know the correct position and need to insert and remove elements efficiently.

collections framework - Several standard implementations

LinkedList, HashSet, and TreeSet,

The ArrayList class implements the ___.

List interface.

Which statement creates a list from a stream of Student objects, given by the variable studentStream?

List<Student> students = studentStream.collect(Collectors.toList());

Which Android control displays a vertical listing of items?

ListView

What is the dessert name that starts with an "L" to describe an Android version?

Lollipop

Polymorphism

Makes object behave as you expect them to and allows you to focus on the specifications of those behaviors

getAllByName

Many hosts have multiple IP addresses. To accommodate this, the InetAddress class provides a method named _____ that can be used to get an array of references to InetAddress objects representing all (or at least some) of the IP addresses assigned to the host.

Map

Maps keys to values

input output

Once you have a URL object connected to a server, you can open _____ and _____ streams that will be connected to the server software that is monitoring the port of interest.

another example would be like a public speaker for an event of some sort. anyone that is interested and wants an update can come and be updated. otherwise the rest who are not interested will not recieve the update

One example of the Observer pattern from outside of software is a radio station: It broadcasts its signal; anyone who is interested can tune in and listen when they want to. What is another example from "real-life"?

Given a single CPU and four threads, how many of the threads can execute in parallel?

Only 1 can execute at a time.

Constructors

Only execute the time when the instance is created.

When does a compilation check apply for instanceof operator?

Only for instanceof aClass - you will always be able to tell if a class is an instance of another class since there is single inheritance with classes Doesn't apply to instanceof anInterface - compiler can't know if a class implements an interface later on (since a subtype of the class can implement an interface early on) page 8

Queue

Only the "head" (next out) is available.

An example of a fatal error that rarely occurs and is beyond your control is the ____.

OutOfMemoryError

One of the steps in deploying a JSF application is to _______ of the web application:

Place JSF pages (such as index.xhtml) in the root directory

Initializes, minimum

Placing numbers in a bracket after the assignment operator ______ an array so that the length is set to the ______ that will hold the values.

Instance

Points to the address that holds the instance variables of the ____and gives access to the method of the class

unbuffered text writing definition

PrintWriter out = new PrintWriter( new FileWriter("mydata.txt"))

d

QN=11 (7145) What would be the best directory in which to store a supporting JAR file for a web application? Note that in the list below, all directories begin from the context root. a. \WEB-INF b. \WEB-INF\classes c. \jars d. \WEB-INF\lib

"SQL injection attacks" have been responsible for many cases of data theft. One of the solutions is:

Never add a string to a query that you didn't type yourself.

Does 2 == Season.SUMMER compile?

No - enum is not an int

Default Constructor

No arguments are passed to it ; assigns every instance variable with a null value; should be overrided

a

QN=11 (9435) Which is NOT a technique that can be used to implement 'sessions' if the client browser does not support cookies? a. Using Http headers. b. Using https protocol. c. Hidden form fields. d. URL rewriting

b

QN=20 Which Java technology provides a unified interface to multiple naming and directory services? a. JNI b. JNDI c. EJB d. JDBC e. JavaMail

to create & work with *random access files* in Java, you must use the _____ class, in the *java.io package*

RandomAccessFile class (719 , 721) ~allows for reading, writing, and moving the file pointer

Which class is used for input of text data?

Reader

A stack is a collection that ___.

Remembers the order of elements, and allows elements to be added and removed only at one end.

For Loops

Repeatedly run a block of code

visitor

Represent an operation to be performed on the elements of an object structure.____ lets you define a new operation without changing the classes of the elements on which it operates.

this

Represents the object that called the method

The ______ class has a next method to visit the next row of a query result.

ResultSet

toString

Returns a string of all the values of the instance variables of the instance that callled the method

toString

Returns the memory address of the instance that called the method

Getters

Returns variable, always public, Control access to the variable

To start a thread, you should first construct an object from a class that implements the ____ interface.

Runnable

Switch statement

Runs code is block = so value

_____ serves as a superclass for exceptions that result from programming errors, such as an out-of-bounds array subscript

RuntimeException (703)

three types of Exception

RuntimeException (unchecked), InternalException (checked), IOException (checked)

Consider the following code snippet: public class SailBoat extends Vessel { private Engine[] engines; private Sail mainsail; . . . } Which of the following statements is NOT correct?

Sail depends on Sailboat.

Scanner object definition

Scanner aScanner = new Scanner( source )

Consider the following code snippet. File hoursFile = new File("hoursWorked.txt"); Your program must read the contents of this file using a Scanner object. Which of the following is the correct syntax for doing this?

Scanner in = new Scanner(hoursFile);

a

Select the correct directive statement insert into the first line of following lines of code (1 insert code here): a. <%@page import='java.util.*' %> b. <%@import package='java.util.*' %> c. <%@ package import ='java.util.*' %> d. <%! page import='java.util.*' %>

builder

Separate the construction of a complex object from its representation so that the same construction process can create different representations.

Which interface allows classes to be written to an ObjectOutputStream?

Serializable

a

Servlet methods are executed automatically. a. True b. False

interfaces within the Collection interface

Set interface (unordered, unique, HashSet subclass) and List interface (ordered in some way)

Method

Set of instructions called on object

Select an appropriate declaration to complete the following code segment, which is designed to read strings from standard input and display them in increasing alphabetical order, excluding any duplicates. _________________________________________ Scanner input = new Scanner(System.in); while (input.hasNext()) { words.add(input.next()); } System.out.print(words);

Set<String> words = new TreeSet<>();

Which two key combinations can you press to run an Android app in Android Studio?

Shift + F10

A list is a collection that ___.

Should be used when you need to remember the order of elements in the collection.

0

Show the output of the following code public class Test1 { public static void main(String[] args) { System.out.println(f2(2, 0)); } public static int f2(int n, int result) { if (n == 0) return 0; else return f2(n - 1, n + result); } }

D. 2 1 Explanation: Invoking increase(x) passes the reference of the array to the method. Invoking increase(y[0]) passes the value 1 to the method. The value y[0] outside the method is not changed.

Show the output of the following code: public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4, 5}; increase(x); int[] y = {1, 2, 3, 4, 5}; increase(y[0]); System.out.println(x[0] + " " + y[0]); } public static void increase(int[] x) { for (int i = 0; i < x.length; i++) x[i]++; } public static void increase(int y) { y++; } }

Why are the methods of the Math class static?

So they can be invoked as if they are a mathematical code library.

client server

Socket programming makes it possible for you to cause data to flow in a full-duplex mode between a _____ and a _____.

Write a code fragment that connects to a server running on gorge.divms.uiowa.edu at port 2345 and sends the message "Hello server" to the server and then reads the one-line response from the server.

Socket sock = new Socket(gorge.divms.uiowa.edu, 2345); PrintWriter pw = new PrintWriter(sock.getOutputStream()); pw.println("Hello server"); pw.flush(); Scanner scan = new Scanner(sock.getInputStream()); String line = scan.nextLine();

What does SDK stand for?

Software Development Kit

Which Math method is used to calculate the absolute value of a number?

The abs() method is used to calculate absolute values.

In an attribute definition in a DTD, a #FIXED V declaration means ____________.

The attribute must be either unspecified or contain v.

sort, ascending

The class Arrays in java.util package has a static method, ____, in which if anArray is an array of either primitive values/objects, the statement: Arrays.sort(anArray); sorts the elements into _______order

Consider the following code snippet: class MouseClickedListener implements ActionListener { public void mouseClicked(MouseEvent event) { int x = event.getX(); int y = event.getY(); component.moveTo(x,y); } }

The class has implemented the wrong interface.

Consider the following code snippet written in Java 7: try (PrintWriter outputFile = new PrintWriter(filename)) { writeData(outputFile); } Which of the following statements about this Java 7 code is correct?

The close method of the outputFile object will be automatically invoked when the try block ends, but only if no exception occurred.

When does the compiler supply a default constructor for a class?

The compiler supplies a default constructor for a class if no other constructors are provided.

localhost

The computer that you are using to read this module online also has an IP address and a name. The IP address, the name, and perhaps some other things as well are grouped together under something commonly referred to as _____.

To what value is a variable of the String type automatically initialized?

The default value of an String type is null.

extends;base class;superclass

The derived class _______ the _________ which is called the __________ or ___________.

Which characters may be used as the second character of an identifier, but not as the first character of an identifier?

The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

A. To determine whether the file exists. B. To obtain the properties of the file such as whether the file can be read, written, or is hidden. C. To rename the file. D. To delete the file.

What are the reasons to create an instance of the File class?

It creates a FileInputStream for test.dat if test.dat exists.

What does the following code do? FileInputStream fis = new FileInputStream("test.dat");

ClassCastException

What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = new Object(); String d = (String)o; } }

No exception

What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = null; System.out.println(o); } }

NullPointerException

What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = null; System.out.println(o.toString()); } }

StringIndexOutOfBoundsException

What exception type does the following program throw? public class Test { public static void main(String[] args) { String s = "abc"; System.out.println(s.charAt(3)); } }

ArithmeticException

What exception type does the following program throw? public class Test { public static void main(String[] args) { System.out.println(1 / 0); } }

ArrayIndexOutOfBoundsException

What exception type does the following program throw? public class Test { public static void main(String[] args) { int[] list = new int[5]; System.out.println(list[5]); } }

The program compiles, but throws IOException because the file test.dat doesn't exist. The program displays IO exception. Explanation: The problem is in line: new RandomAccessFile('test.dat', 'r'); Because the file does not exist, you cannot open it for reading.

What happens if the file test.dat does not exist when you attempt to compile and run the following code? import java.io.*; class Test { public static void main(String[] args) { try { RandomAccessFile raf = new RandomAccessFile("test.dat", "r"); int i = raf.readInt(); } catch(IOException ex) { System.out.println("IO exception"); } } }

Welcome to Java followed by The finally clause is executed in the next line Explanation: The return statement exits the method, but before exiting the method, the finally clause is executed.

What is displayed on the console when running the following program? class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); return; } finally { System.out.println("The finally clause is executed"); } } }

Welcome to Java followed by The finally clause is executed in the next line

What is displayed on the console when running the following program? class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); } finally { System.out.println("The finally clause is executed"); } } }

The program displays three lines: Welcome to Java, Welcome to HTML, The finally clause is executed.

What is displayed on the console when running the following program? class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; double y = 2.0 / i; System.out.println("Welcome to HTML"); } finally { System.out.println("The finally clause is executed"); } } }

Welcome to Java followed by The finally clause is executed in the next line, then an error message.

What is displayed on the console when running the following program? class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2 / i; System.out.println("Welcome to HTML"); } finally { System.out.println("The finally clause is executed"); } } }

Consider the following code snippet: public static void reverse(List<?> list) { . . . } Which of the following statements about this code is correct?

This is an example of an unbounded wildcard.

The Collection Interfaces : The Enumeration

This is legacy interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Iterator.

What is virtual method invocation? Does this apply to variables too?

This is where a method's implementation is determined at runtime - overriden methods. When a super class reference to a subclass object has a method called on it, Java will look for overriden methods that may exist in the subclass. No, variables do not work this way. With a superclass reference to a subclass object, an attempt to access a variable will always choose the superclass variable since the reference is of the parent class. If the reference were of the subclass, the subclass variable would be used.

The Collection Interfaces : The Map

This maps unique keys to values. A key is an object that you use to retrieve a value at a later date.

Why do threads block on I/O?

Threads block on I/O (that enters the waiting state) so that other threads may execute while the I/O Operation is performed.

URL date last modified content

Three methods can be called on a URLConnection object to obtain the following three informational aspects of the URL: _____ _____ _____

Which method(s) will this line from a JSF page call? <h:inputText value="#{timeZoneBean.city}"/>

TimeZoneBean.getCity() and TimeZoneBean.setCity()

Write a line of code that creates an instance of the Timer class with the object named stopwatch.

Timer stopwatch = new Timer();

Write a line of code that creates an instance of the TimerTask class with the object named welcome.

TimerTask welcome = new TimerTask(){@Override public void run() {}};

Which of the following statements about generic programming is NOT correct?

To achieve genericity through inheritance, you must include type parameters to specify the type of object to be processed.

new FileOutputStream("out.dat", true)

To append data to an existing file, use _____________ to construct a FileOutputStream for file out.dat.

What is one reason why you need a finally clause after a try/catch sequence that accesses a database?

To close the connection

True or False: A ListActivity is a class that displays a list of items within an app.

True

True or False: A scroll bar appears in a list when the list exceeds the size of the window.

True

True or False: Gravity is a tool that changes the linear alignment of a control.

True

True or False: The default layout for an Android screen is Relative.

True

True or False: The default option in the switch decision structure is used if none of the cases match the testing condition.

True

True or False: Typically, the onCreate() method begins an Activity.

True

True or False: You can use the Image Asset Wizard to display a custom icon.

True

Boolean

True/False statements

What restrictions are placed on method overloading?

Two methods may not have the same name and argument list but different return types.

To open a connection, which of the following statements can you use?

URL u = new URL("http://www.yahoo.com"); URLConnection conn = u.openConnection();

What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

What does URI stand for?

Uniform Resource Identifier

named constants

Use __________ instead of literals to define the number of rows and columns

fly weight

Use sharing to support large numbers of fine-grained objects efficiently.

2.1, 3.1, 2.5, 6.4, 3.1

Use the selectionSort method presented in this section to answer this question. Assume list is {3.1, 3.1, 2.5, 6.4, 2.1}, what is the content of list after the first iteration of the outer loop in the method?

list1 is 2.5 3.1, 3.1, 6.4

Use the selectionSort method presented in this section to answer this question. What is list1 after executing the following statements? double[] list1 = {3.1, 3.1, 2.5, 6.4}; selectionSort(list1);

Creational Patterns

Used to construct objects such that they can be decoupled from their implementing system.

Structural Patterns

Used to form large object structures between many disparate objects.

behavorial patterns

Used to manage algorithms, relationships, and responsibilities between objects.

super

Using ______ as an object calls a base-class method ____.writeOutput()

Parameter

Values to be specified when creating object/calling method

indexed variables

Variables that have an integer expression in square brackets are called _______

legacy classes defined by java.util

Vector Stack Dictionary Hashtable Properties Bitset to store and manipulate groups of objects. Although these classes were quite useful, they lacked a central, unifying theme. Thus, the way that you used Vector was different from the way that you used Properties.

What is known for certain about Visualizer when a method constrains its type parameter as follows? <E extends Visualizer>

Visualizer can refer to either an interface or a class

When deploying a JSF application, all class files must be placed in the _______ directory:

WEB-INF/classes/

n <= 0

What are the base cases in the following recursive method? public static void xMethod(int n) { if (n > 0) { System.out.print(n % 10); xMethod(n / 10); } }

What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.

does not, references

When an array of objects is created, Java _______ create instances of any of the _____________ must first be created to the object.

class; is not

When an overridden method is invoked, its action is the one defined in the _____ used to create the object using the new operator. It _____ determined by the type of the variable naming the object

Null pointer

When base type of the array name is a class type and does not reference any object of the class.

Dynamic binding; late binding

When the method associated with a class used to create an object is invoked *The variable name/type does not matter

memory address, indexes

When using = between arrays you assign the ______________ of one array to the other so they are the same array with different names. Use arrays with _________ to retain the arrays with the same values.

Which of the following statements about converting between types is true?

When you cast object types, you take a risk that an exception will occur.

C. the reference of the array

When you pass an array to a method, the method receives __________.

the reference of the array

When you return an array from a method, the method returns __________.

base type, length

When you specify an array parameter, you give the _______ of the array, but you do not fix the ________ of the array. (i.e. public static void showArray(char[] a)

When is a semi-colon required when listing enum values?

Whenever an enum type defines more than just enum values - instance variables - constructors - methods

File

Which class contains the method for checking whether a file exists?

Scanner

Which class do you use to read data from a text file?

PrintWriter

Which class do you use to write data into a text file?

b

Which directory is legal location for the deployment descriptor file? Note that all paths are shown as from the root of the web application directory. a. \WEB-INF\xml b. \WEB-INF c. \WEB-INF\classes

a

Which element defined within the taglib element of taglib descriptor file is required? Select one correct answer. a. Tag b. Description c. Validator d. Name

a

Which interface can you use to retrieve a resource that belongs to the current web application? a. ServletContext b. HttpServletRequest c. HttpServletResponse d. HttpServlet

a

Which interface you CANNOT use to obtain a RequestDispatcher Object? a. ServletContext b. HttpServletResponse c. ServletRequest

a

Which is NOT Enterprise Beans? a. Business Beans b. Entity Beans c. Session Beans d. Message-Driven Beans

c

Which is NOT a correct statement about entity beans? a. They are used to store persistent data b. They are used to share data among clients c. They are used to implement business processes d. They are used to represent data stored in a RDBMS

a

Which is NOT a scope of implicit objects of JSP file? a. application b. page c. request d. session e. response

a

Which is NOT associated with the business tier in a JEE (J2EE) web-based application? a. JSP b. Entity Beans c. Stateless Session Beans

c

Which is NOT true about stateless session beans? a. They are CANNOT hold client state b. They are used to implement business logic c. They are used to represent data stored in a RDBMS d. They are an Enterprises Beans

c

Which is a valid PostConstruct method in a message-driven bean class? a. @PostConstruct a. public boolean init() { return true; } b. @PostConstruct b. private static void init() {} c. @PostConstruct c. private void init() {} d. @PostConstruct d. public static void init() {}

new Scanner(new File("temp.txt"))

Which method can be used to create an input object for file temp.txt?

A. new PrintWriter("temp.txt") C. new PrintWriter(new File("temp.txt"))

Which method can be used to create an output object for file temp.txt?

nextLine

Which method can be used to read a whole line from the file?

print

Which method can be used to write data?

available()

Which method can you use to find out the number of the bytes in a file using InputStream?

init(), preprocess(), prerender(), destroy()

Which of the following are JSF life-cycle methods?

a

Which of the following are correct JSP expressions a. <%= new Date() %> b. <% "Hello World"; %> c. <%= "Hello World"; %> d. <%= out.println("hello"); %>

Can a for statement loop indefinitely?

Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

Can an exception be rethrown?

Yes, an exception can be rethrown.

Can an equals() override access private member variables?

Yes, though they are private, the equals() method is written in the same class the private instance variables are declared. Therefore the equals() method has access to them

If a class has an abstract method, which of the following statements is NOT true?

You can construct an object from this class.

Which of the following is true regarding a class and interface types?

You can convert from a class type to any interface type that the class implements.

Which of the following statements about interfaces is true?

You can define an interface variable that refers to an object only if the object belongs to a class that implements the interface.

extends; inheritance

You can define another interface that builds on or __________ the first one using a kind of ______.

Which of the following most likely indicates that you have chosen a good name for your class?

You can tell by the name what an object of the class is supposed to represent.

Java Servlet, JSP, JSF

You can use NetBeans 6 to develop _______ applications.

repeat the use of

You cannot ________ super to invoke an overridden method from some ancestor class other than a direct parent.

Derived class

You define a ______ by starting with another already defined class and adding/changing methods and instance variables.

when overriding interface methods, what trick should we watch out for?

access modifier MUST be public

An _____ provides a data model for the layout of a list and for converting the data from the array into list items.

adapter

collection interface

add(), clear(), contains(), size(), etc...

ArrayList methods

add(obj) add(idx, obj) set(idx, obj) remove(idx) get(idx) size() isEmpty() clear()

c

You need to make sure that the response stream of your web application is secure. Which factor will you look at? (Choose one) a. authentication b. authorization c. data integrity

elements, capacity

You should keep track of the __________ you have used out of the array's __________ to avoid meaningless values

What should the database.properties file contain so you can connect to a database?

a database URL, user name, password

binary file

a file that contains raw binary data (712)

API (application-programming interface)

a group of pre-defined classes that can be used to build a program. The Java API organizes Java's classes by package

What is an anonymous inner class?

a local inner class that doesn't have a name

instance method

a message that must be sent to an instance of a class.

no-op or null method

a method that doesn't do anything; empty {}

increment operator

adds one to the value of a variable.

add(idx, obj)

adds specified obj to specified idx

add(obj)

adds specified object to end of ArrayList

In a UML diagram, the relationship symbol shown below denotes ___. <>-

aggregation

NOTE

all exception objects have a *printStackTrace* method, inherited from the *Throwable* class, that prints a *stack trace* (700)

type Throwable

all exceptions are of this type

What will the following expression match to? Name LIKE '_e%'

all strings in the Name column whose second letter is an "e".

What is hidden instead of overriden?

all variables (regardless of access modifier) static methods private methods

polymorphism

allows object of one type to be used as reference to objects of different types

Which tween effect changes the transparency of the image?

alpha

Name four tween effects.

alpha, rotate, scale, translate

floating-point literals

alternative representations of a single number using scientific notation. For example, 0.2998e9 and 29.98e7 are equivalent representations of one number. To account for the difference in the value of the exponent, the decimal "floats" two places.

Write the code that sets an attribute to play a Frame animation for three seconds.

android:duration="3000"

Write the attribute for a rotation that repeats 10 times.

android:repeatCount="9"

Write a single line of XML code that changes the size of the text of a TextView control to 39 scaled-independent pixels.

android:textSize="39sp"

What is the root element of a Frame animation within the XML file?

animation-list

boolean operator

another term for a logical operator

handle

another term for the name of a reference type.

what access modifier can be applied to a static nested class?

any of them

Database tables store rows that contain the following except

arbitrary objects

Classes ObjectInputStream and ObjectOutputStream

are high-level streams that contain the methods for serializing and deserializing an object.

binary files use

binary streams

the FileOutputStream constructor takes an optional second argument which must be a _____ value

boolean (718)

Write a statement that is needed to change the text on a button named btnJazz to the text "Pause Unforgettable."

btnJazz.setText("Pause Unforgettable.");

Which type of animation displays a slide show type of presentation?

frame

Write an If statement to compare if a string variable named company is equal to AT&T with empty braces.

if(company.equals("AT&T")) { }

implements keyword

implements an interface in a class

Which measurement is more preferred for text size?

sp

What is the name of the initial window that typically displays a company logo for a few seconds?

splash screen

A collection that remembers the order of items, and allows items to be added and removed only at one end is called a ____.

stack

The JSF tags are dynamically translated into HTML tags and text. In this context, dynamic means:

the translation depends on the current state of Java objects.

if outer and inner classes define variables with the same name, what does x, or this.x refer to in an inner class?

the variable defined within the class that x or this.x is called from. ex: if x or this.x called from inner class, will refer to inner class values.

An Android _____ is a style applied to an Activity or an entire application.

theme

FACT

there are many error conditions that can occur while a Java app is running that will cause it to halt execution (681)

FACT

there are some types of data that should be stored only in its raw binary format (713) ~*images, audio, & video* are an example

if x.equals(y) = false, what does this tell you about the hashcode for each?

they can be the same or can be different

What are examples of what enums are used for?

things that never change/have a finite set - days of the week - months of the year

void writeChar(int c) [DataOutputStream method]

this method accepts an int which is assumed to be a character code. The character it represents is written to the file as a 2-byte Unicode character (714)

A ______ is a single sequential flow of control within a program.

thread

A(n) __ uses a small number of threads to execute a large number of runnables.

thread pool

*EOFException* object

thrown when an app attempts to read beyond the end of the file (683)

*FileNotFoundException* object

thrown when an app tries to open a file that does not exist (683)

the _____ clause informs the compiler of the exceptions that could get thrown from a method

throws clause (703)

Each thread runs for a short amount of time, called a ____.

time slice

FACT

to meet the needs of a specific class or app, you can create your own exception classes by extending the Exception class or 1 of its subclasses (708)

FACT

to open a binary file for input, you wrap a *DataInputStream object* around a *FileInputStream object* (715)

CONCEPT

to prevent *exceptions* from crashing your program, you must write code that detects and handles them (681)

FACT

to serialize an object and write it to the file, use the *ObjectOutputStream* class's *writeObject* method (725)

FACT

to write *bytes to a file*, use an output stream object, such as *FileOutputStream* (725)

Object

toString is inherited from the class ______ through the generations

What does ADS refer to as a message that appears as an overlay on a user's screen, often displaying a validation warning?

toast

Using the layout:margin property, in which text box would you type 18dp to move a control 18 density pixels down from the upper edge of the emulator?

top

try-catch block for writing a text file

try () catch (IOException e) {}

a _____ is 1 or more statements that are executed & can potentially throw an exception

try block (684)

Which code fragment creates a stream of lines from a file named "data.txt"?

try(Stream<String> linesData = Files.lines(Paths.get("data.txt"))) { ... };

Which type of animation is applied to a single image?

tween

___________ effects are transitions that change objects from one state to another.

tween

Which can a generic class be parameterized for?

type

constant definition in interface

type UPPERCASE = #

int

type that uses 32 bits to store integer values.

double

type that uses 64 bits to represent real numbers. A double type has greater capacity than a float type.

What are the advantages of enum?

type-safe since type is checked at compile time cannot input an invalid enum - don't have to wait until runtime to find out the type isn't right

primitive type

types that are used to store various kinds of numbers and can be used as "building blocks" to build other types. These types include boolean, char, int, double, and others.

reference types

types that store references to objects, or instances of classes. Reference types are sometimes called class types because they are the names of classes. String, Scanner, and System are all examples of reference types.

the 2 categories of exceptions include:

unchecked & checked (703)

_____ inherit from the *Error* class or the *RuntimeException* class

unchecked exceptions (703)

Object class

universal superclass of all objects, all classes are subclass of Object

Equality Operators

Equal/Not Equal to

Final Modifier

Syntax for: public final void specialMethod()

Can a double value be cast to a byte?

Yes, a double value can be cast to a byte.

Reader class

abstract base class used to read text input streams

Writer class

abstract class for writing text to output streams

InputStream

abstract super class for reading all binary input streams

The ___ method of the ServerSocket class waits for a client connection.

accept()

void close() [DataInputStream method]

closes the file (716)

A(n) _____ is a computer technology used to compress and decompress audio and video files.

codec

interfaces

collection of abstract methods/constants used to provide consistent way to invoke similar behaviors within objects and achieve polymorphism without inheritance

equals()

compares whether two objects reference same memory area (not same values)

Consider the following code snippet: public class Box<E> { private E data; public Box(){ . . . } public void insert(E value) { . . . } public E getData(){ . . . } } What will result from executing the following code? Box<String> box = new Box<>(); . . . box.insert("blue Box"); String b = (Object) box.getData();

compiler error

FileReader class

connects an input stream with a file

FileOutputStream

connects output stream to a file

what are 2 things to watch for in enums?

constructors must be private missing semi-colon in enum declaration of values consist of more than just the enum value itself

collections

containers that allow us to efficiently store and process data. Vectors, trees, linked list are collections.

printf(formatString, args)

contains format control string and list of args

as soon as exception thrown in try block

control transferred to catch block, will not go back to finish the try block

autoboxing

converting between primitives and wrapper classes as needed. Automatic in Java. Performance hits when used

exception handling

creates an object called an exception object

mkdir() createNewFile()

creates directory, creates new file

Your program uses a Map structure to store a number of user ids and corresponding email addresses. Although each user must have a unique id, two or more users can share the same email address. Assuming that all entries in the map have valid email addresses, select an appropriate expression to complete the method below, which adds a new id and email address to the map only if the id is not already in use. If the id is already in use, an error message is printed. public static void addUserID(Map<String, String> users, String id, String email) { String currentEmail = users.get(id); if (___________________) { users.put(id, email); } else { System.out.println(id + " is already in use."); } }

currentEmail == null

Use the ____ layout manager when you need to add components that are displayed one at a time. a. BorderLayout b. GridLayout c. GridBagLayout d. CardLayout

d. CardLayout

Each JMenu can contain options, called JMenuItems, or can contain submenus that are ____. a. JMenuBars b. JMenuChildren c. JSubMenus d. JMenus

d. JMenus

When components in a Swing UI require more display area than they have been allocated, you can use a ____ container to hold the components and allow the user to display the components using scroll bars. a. JScrollingPane b. ScrollLayout c. JPanel d. JScrollPane

d. JScrollPane

Clicking a component results in a(n) ____. a. ItemEvent b. WindowEvent c. ActionEvent d. MouseEvent

d. MouseEvent

A(n) ____ implements all methods in an interface and provides an empty body for each method. a. action key b. viewport c. mnemonic d. adapter class

d. adapter class

The state of a JCheckBoxMenuItem or JRadioButtonMenuItem can be determined with the ____ method. a. state() b. getState() c. getSelected() d. isSelected()

d. isSelected()

FACT

data can be stored in a file in its *raw binary format* (713)

when program writes to buffered stream

data sent to buffer and not directly to output device

text files

data stored typically with one byte per character, often delimited using /t or /n

_____ deals with *thrown exceptions*

default exception handler (682)

generate random number using Random

define Random a = new Random() and then rn.nextInt(30) + 1 will generate random from 1-30

How is an anonymous inner class defined and what is it assigned to?

defined using the new keyword with the class or interface that the anonymous class will implement/extend public class Test { abstract SomeClass { abstract void someMethod(); } public testSomeClass() { SomeClass sc = new SomeClass() { void someMethod() { System.out.prinln(""); }}; } } NOTE: Semi colon after anonymous class definition

Which method is NOT part of the ListIterator interface?

delete

overridden method/subclass visibility cannot be

more restrictive than base method/class

A(n) ___ is used to capture mouse events.

mouse listener

the ability to catch multiple types of exceptions with a single catch clause is known as _____ and was introduced in Java 7

multi-catch (701)

what is common practice when combining instance variables to generate hashCode() for an object?

multiplying by a prime number and adding the hashCode() results together

java.util package

must import for Scanner class

Which phrase best describes the purpose of a lock used in an object in one or more of its methods?

mutual exclusion

Assume that you have declared a set named mySet to hold String elements. Which of the following statements will correctly insert an element into mySet?

mySet.add("apple");

Assume that you have declared a set named mySet to hold String elements. Which of the following statements will correctly remove an element from mySet?

mySet.remove("apple");

Assuming that the variable myStringArrayList has been populated to contain a collection of String objects, which expression finds the number of elements in a stream created from the myStringArrayList collection?

myStringArrayList.stream().count()

Complete the following code, which is intended to add an element to the top of a stack implemented as a linked list. Node newNode = new Node(); newNode.data = element; _________________ _________________

newNode.next = first; first = newNode;

nsert the missing code in the following code fragment. This fragment is intended to add a new node to the head of a linked list: public class LinkedList { . . . public void addFirst(Object element) { Node newNode = new Node(); newNode.data = element; _________ _________ } . . . }

newNode.next = first; first = newNode;

Scanner methods

nextByte() etc for all primitive types next() nextLine() hasNext()

Can a local inner class define static members?

no

Can you compare an enum to an int in a switch statement?

no

Is a static nested class considered an inner class?

no

does hashCode() have to return unique results for unequal objects?

no

should you handle unchecked exceptions including *Error* or *RuntimeException*?

no (703)

Can an enum be extended?

no - they cannot be extended enum ExtendedSeason extends Season {} is not allowed

within the same program, can an object's hashcode change?

no, it must not change. variables that change a lot should not be included in the hash code. For example - a person's name is ok, but their weight flucuates constantly (don't include).

is an enum an int?

no, it's a type

Is it common to use all instance variables in a hash code?

no, typically char and boolean values are not included. primitive values can be used as is or divided into a smaller number

if (anInterface instanceOf concreteClass) - can this ever NOT compile?

no, will always compile - a subclass of concreteClass could implement anInterface even if concreteClass does not - no way for compiler to know

does an enum default method definition need the default key word?

no, written like a normal method

What access modifiers can be applied to a local inner class?

none, they do not have one

Can a member inner class contain static variables and methods?

nope

What's the difference between how an anonymous inner class would implement an interface vs. an abstract class?

not much! almost the same, just remember when overriding an interface method, all methods must be the public (since all interface methods are public). public keyword NOT required for abstract methods if they aren't already public

unchecked exceptions

not required to be checked

Write the following variable in camel case: NUMBEROFDELAYS.

numberOfDelays

collection

object that can hold one or more other objects

Which method follows an onPause( ) method?

onResume() onStop() also accepted

Java arrays

once created, cant be resized. Can store anything, including objects (normaly use a list instead)

How many .class files are generated for a class with inner classes defined?

one for each class, outer or inner

relational operator

one of six operators used in a boolean expression that compares two operands. The list of relational operators includes !=, ==, <. <=, >, and >=.

logical operator

one of three operators used to compare boolean expressions. The list of logical operators includes &&, ||, and !.

Write the code that sets an attribute to play a Frame animation until the app ends.

oneshot="false"

not including polymorphic references, a try statement can have _____ catch clause(s) for each specific type of exception

only 1 (696)

Can a local inner class access local variables defined within the same method?

only if they are final or effectively final

Which is not a method available in the RandomAccessFile class?

open

to serialize class yourself, must implement

private writeObject() and private readObject()

The ____ property of the Spinner control adds text at the top of the control such as instructions.

prompt

A(n) _______________ is a set of instructions and rules that the client and server follow to allow communication between them. Each will know what to send and what to expect to receive from its partner in the communication.

protocol in network programming

Generics

provide compile-time type safety that allows programmers to catch invalid types at compile time.

The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes

provide skeletal implementations of the core collection interfaces, to minimize the effort required to implement them.

How can you use Apache Commons Lang library to quickly print out all instance variables in an object?

public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } // prints out something like Hippo[name=Harry, weight=3100.0] other styles available

abstract method definition

public abstract return name( args)

interface methods are implicitly

public and abstract

What are the 3 Object methods that are often overriden in Java classes?

public boolean equals(Object o) public String toString() hashCode()

How can you use Apache Commons Lang library to quickly compare all instance variables in an object?

public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, obj); }

Generic Classes Example

public class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); Box<String> stringBox = new Box<String>(); integerBox.add(new Integer(10)); stringBox.add(new String("Hello World")); System.out.printf("Integer Value :%d\n\n", integerBox.get()); System.out.printf("String Value :%s\n", stringBox.get()); } }

Which type of pictures can be used for free fair use without copyright?

public domain

How do you define an enum?

public enum Season { WINTER, SPRING, FALL, SUMMER }

constants in an interface are implicitly

public final static

extend an interface

public interface MoreDraw extends Draw

method definition for subclass

public return name(args) (no static keyword)

conditions for serializing a class

public visibility, implements Serializable, base class must have default constructor

Which of the following code snippets about exceptions is correct?

public void read(String filename) throws IOException, ClassNotFoundException

What access modifiers can be applied to a member inner class?

public, protected, default ( no modifier), private

bit

the smallest unit of memory, which can store a value of 0 or 1

when is an *exception thrown*?

when the code does *not handle* an exception (682)

B. 120 200 14 Explanation: 016 is an octal number. The prefix 0 indicates that a number is in octal.

(Tricky) What is output of the following code: public class Test { public static void main(String[] args) { int[] x = {120, 200, 016}; for (int i = 0; i < x.length; i++) System.out.print(x[i] + " "); } }

The program displays 2.5 3.0 4.0

(for-each loop) Analyze the following code: public class Test { public static void main(String[] args) { double[] x = {2.5, 3, 4}; for (double value: x) System.out.print(value + " "); } }

interface definition

(public) interface InterfaceName

Product

*

Interface

*Contains no instance variables *No complete method definitions (no bodies) *methods must be public *can define any number of public named constants *a reference type(can write a method that has a parameter of this type)

if there is no reason to reference the *FileOutputStream object*, these statements can be combined into 1 as follows: [code]

*DataOutputStream outputFile =* -->*new DataOutputStream(new* -->*FileOutputStream("MyInfo.dat"));* (713)

list the classes that inherit from the *IOException* class:

*EOFException* & *FileNotFoundException* (683) ~examples of classes that exception objects are created from

if the *file pointer* refers to a byte number that is beyond the end of the file, a(n) _____ is thrown when a read operation is performed

*EOFException* (721)

just below the *Throwable* class are the classes _____ & _____

*Error* & *Exception* (683)

open a binary file for input [code]

*FileInputStream fstream =* -->*new FileInputStream("MyInfo.dat");* *DataInputStream inputFile =* -->*new DataInputStream(fstream);* (715)

list the exceptions that are instances of classes that inherit from *Exception*

*IOException* & *RuntimeException* (683) ~also serve as superclasses

to write a *serialized object to a file*, use the _____ object

*ObjectOutputStream* output (725)

general format of *RandomAccessFile* class constructor [code]

*RandomAccessFile(String filename, String mode)* (719)

hashmap vs hashset

- HashSet allows only one null key, but HashMap can allow one null key + multiple null values.

NOTE

-do not confuse the *throw statement* with the *throws clause* -*throw statement*: causes an exception to be thrown -*throws clause*: informs the compiler that a method throws 1 or more exceptions (705)

a class to be serialized successfully, two conditions must be met

- The class must implement the java.io.Serializable interface. - All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

*DataInputStream*

-class that allows you to *read data* of any primitive type, or String objects, from a binary file -the class itself cannot directly access a file -it is used in conjunction with a *FileInputStream object* that has a connection to a file (715)

Generic Methods

- can write a single generic method declaration that can be called with arguments of different types. - Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately.

Generic Classes

- declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section. -can have one or more type parameters separated by commas. -are known as parameterized classes or parameterized types because they accept one or more parameters.

ObjectInputStream class

-deserializing an object -retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type. public final Object readObject() throws IOException, ClassNotFoundException

What are the four types of nested classes?

- non-static inner class defined at same level as instance variables - static nested class defined at same level as static variables - local nested class - class defined inside a method - anonymous nested class - class defined inside a method with no name

What are the properties of equals(Object o)?

- symmetric (x = y, y = x) - reflexive (x = x) - transitive (x = y, y = z, x = z) - consistent (two objects (not modified) should always equal each other or always not equal each other) - x.equals(null) returns false instead of NPE

collections : Summary

-The Java collections framework gives the programmer access to prepackaged data structures as well as to algorithms for manipulating them. -A collection is an object that can hold references to other objects. The collection interfaces declare the operations that can be performed on each type of collection. -The classes and interfaces of the collections framework are in package java.util.

treemap vs treeset

-TreeSet implements Set interface while TreeMap implements Map interface in Java -the way they store objectsTreeSet stores only one object while TreeMap uses two objects called key and Value.

*FileInputStream*

-class that allows you to *open a file* for reading binary data & establish a connection with it -it provides only the basic functionality for reading bytes from the file (715)

important points to know about *RandomAccessFile modes*:

-if you open a file in *r mode* & the file does not exist, a *FileNotFoundException* is thrown -if you open a file in *r mode* & try to write to it, an *IOException* is thrown -if you open an existing file in *rw mode*, it will not be deleted. The file's existing contents will be preserved -if you open a file in *rw mode* & the file does not exist, it will be created (719)

char readChar() [DataInputStream method]

-reads a char value from the file and returns it -the character is expected to be stored as a two-byte Unicode character, as written by the DataOutputStream class's writeChar method (716)

String readUTF() [DataInputStream method]

-reads a string from the file and returns it as a String object -the string must have been written with the DataOutputStream class's writeUTF method (716)

maps

-store key/value pairs. -not collections in the proper use of the term, but they are fully integrated with collections.

*FileOutputStream* class

-this class allows you to *open a file* for writing binary data and establish a connection with it -it provides only basic functionality for writing bytes to the file (713)

*DataOutputStream*

-this class allows you to *write data* of any primitive type or String objects to a binary file -the class by itself cannot directly access a file -it is used with the *FileOutputStream object* that has a connection to a file (713)

FACT

-when the *DataInputStream* class's *readUTF* method reads from the file, it expects the first 2 bytes to contain the number of bytes that the string occupies -then it reads that many bytes and returns them to a String (717)

Which picture file types are acceptable for an ImageView control?

.jpg, .png, and .gif

Complete the following code snippet that returns a stream of String objects representing the majors of the students in the honors college, assuming that honorsStream is a stream of Student objects and the method getMajor returns a String. Stream<String> honorsMajors = honorsStream ________________________________;

.map(s -> s.getMajor())

What is the most common extension for a song played on an Android device?

.mp3

What is the preferred file extension of the launcher icon?

.png

Which picture file type is preferred for an ImageView control?

.png

Division

/

Single line comment

//

When you create a Tween XML file, which folder is the file automatically saved in?

/res/anim folder

How many methods are required to implement the Serializable interface?

0

How many bytes does the read method in the FileInputStream class actually get from the file?

1

if the code in a method can potentially throw a *checked exception*, then that method must meet 1 of the requirements including:

1. must handle the exception or 2. must have a *throws* clause listed in the method header (703)

Answer the question below about the following initialized array: String[] pizzaToppings = new String[10]; How many toppings can this array hold?

10

Given the following code, what will the XPath /items/item[2]/product/price generate? <items> <item> <product> <description>Ink Jet Refill Kit</description> <price>29.95</price> </product> <quantity>8</quantity> </item> <item> <product> <description>4-port Mini Hub</description> <price>19.95</price> </product> <quantity>4</quantity> </item> </items>

19.95

Assuming that path is properly instantiated object of type XPath and doc is the document below, what is the value of result in the statement String result = path.evaluate("count(/items/*", doc); <items> <item> <product> <description>Ink Jet Refill Kit</description> <price>29.95</price> </product> <quantity>8</quantity> </item> <item> <product> <description>4-port Mini Hub</description> <price>19.95</price> </product> <quantity>4</quantity> </item> </items>

2

If we want a create a doubly-linked list data structure so that we can move from a node to the next node as well as to a previous node, we need to add a previous reference to the Node class. Each such DNode (doubly-linked Node) will have a data portion and two DNode references, next and previous. How many references need to be updated when we remove a node from the middle of such a list? Consider the neighboring nodes.

2

A binary search tree is made up of a collection of nodes organized with smaller keys on the left and greater keys on the right relative to any node. Which of the following Node references must be attributes of any implementation of Node class? I root II left III right

2 and 3

What is the solution to the following arithmetic expression? 3 + 4 * 2 + 9

20

How long (identify units) does this statement schedule a pause in the execution? logo.schedule(task, 3000);

3 seconds

What is the solution to the following arithmetic expression? 16 / 2 * 4 + 4

36

What is the solution to the following arithmetic expression? 40 - (6 + 2) / 8

39

Which Android version is Kit Kat?

4.4

A page not found has status code _______________.

404 not found.

When you post an Android app at Google Play, what percentage of the app price does the developer keep?

70%

What is the solution to the following arithmetic expression? 3 + 68 % 9

8

Which type of drawable image stretches across different screen sizes?

9-patch

What character is placed at the end of most lines of Java code?

;

Less than

<

For price elements that must contain currency, the attribute list is:

<!ATTLIST price currency CDATA "USD">

Less than or equal to

<=

In an app, suppose you want to use the theme with a grey title bar and a white background. What entire line of code is needed in the styles.xml file to support this theme?

<style name="AppTheme" parent="Base.Theme.AppCompat.Light">

Using the grammar notation in your textbook, which rule means that a verb can be either jumps over or eats?

<verb> ::= jumps over | eats

Equal to

==

Consider the following code snippet: public class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("I was clicked."); } } public class ButtonTester { public static void main(String[] args) { JFrame frame = new JFrame(); JButton button = new JButton("Click me!"); frame.add(button); ActionListener listener = new ClickListener(); button.addActionListener(listener); ... } } Which of the following statements is correct?

A ClickListener object listens for the action events that buttons generate.

Which of the following is an event source?

A JButton object.

d

A Java developer needs to be able to send email, containing XML attachments, using SMTP. Which JEE (J2EE) technology provides this capability? a. JSP b. EJB c. Servlet d. JavaMail

Throwable

A Java exception is an instance of __________.

How are Java source code files named?

A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.

What is the difference between a Linear layout and a Relative layout?

A Linear Layout organizes layout components in a linear fashion vertically or horizontally. A Relative Layout organizes layout controls in relation to each other. This provides more flexibility of control positioning than Linear Layouts.

Consider the following code snippet: public class Vehicle { private String manufacturer; . . . public void setVehicleClass(double numberAxles) { . . . } } If a Motorcycle class is created as a subclass of the Vehicle class, which of the following statements is correct?

A Motorcycle object inherits and can directly use the method setVehicleClass but cannot directly use the instance variable manufacturer.

proxy server

A _____ _____ is often used to improve the communication speed of computers inside of a company with the Internet at large outside the company. For example, if ten people inside the company attempt to connect to the same Internet server and download the same web page within a (hopefully) short period of time, that page may be saved on the _____ _____ on the first attempt and then delivered to the next nine people without re-acquiring it from the outside web server. This can significantly improve delivery time and reduce network traffic into and out of the company.

firewall

A _____ is the common name given to the equipment and associated software that is used to insulate the network inside of a company from the Internet at large outside the company. Typically, the _____ will restrict the degree to which computers inside the company can communicate with the Internet for security and other reasons.

Static

A ______ method may be called nameOfTheClassInWhichTheMethodResides.methodName(required arguments); or instanceOfTheClassInWhichTheMethodResides.methodName(required arguments);

Final

A ___________ method CANNOT be overridden.

a

A bean present in the page and identified as 'mybean' has a property named 'name'. Which of the following is a correct way to print the value of this property? a. <jsp:getProperty name="mybean" property="name"/> b. <%out.println(mybean.getName())%> c. <%=out.println(mybean.getName())%> d. <%=jsp:getProperty name="mybean" property="name"%>

What classes of exceptions may be caught by a catch clause?

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

Which of the following statements about interfaces is NOT true?

A class can implement only one interface type.

Derived class

A class defined by adding instance variables and methods to an existing class

Is a class a subclass of itself?

A class is a subclass of itself.

How does a UML diagram denote classes and their attributes and methods?

A class rectangle contains the class name in the top, attributes

If a class is declared without any access modifiers, where may the class be accessed?

A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

URL object

A common way to get a URLConnection object is to call a method on a _____ _____ that returns an object of a subclass of the URLConnection class.

Suppose we create a deque (double-ended queue) data structure. It is basically a queue, with its addLast and removeFirst operations, but we also add the addFirst and removeLast operations. Which of the following is best modeled by the deque data structure?

A computer keyboard typing buffer.

How can a dead thread be restarted?

A dead thread cannot be restarted.

does not

A derived class __________ inherit any constructors from the base class.

a

A developer is working on a project that includes both EJB 2.1 and EJB 3.0 session beans. A lot of business logic has been implemented and tested in these EJB 2.1 session beans. Some EJB 3.0 session beans need to access this business logic. Which design approach can achieve this requirement? a. Add adapted home interfaces to EJB 3.0 session beans to make EJB 3.0 and EJB 2.1 session beans interoperable. b. Add EJB 3.0 business interfaces to existing EJB 2.1 session beans and inject references to these business interfaces into EJB 3.0 session beans. c. No need to modify existing EJB 2.1 session beans. Use the @EJB annotation to inject a reference to the EJB 2.1 home interface into the EJB 3.0 bean class.

In a UML diagram an interface implementation is denoted by ___.

A dotted line with a closed arrow tip.

final

A entire class can be declared _____ so you cannot derive from it as a bass class other classes.

What is the difference between a field variable and a local variable?

A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.

rules to define Generic Methods : can represent only reference types

A generic method's body is declared like that of any other method. Note that type parameters ________ , not primitive types (like int, double and char).

What modifiers can be used with a local inner class?

A local inner class may be final or abstract.

checked exceptions

A method must declare to throw ________.

stub

A method whose definition can be used for testing but is not yet the final definition

What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution?

A method's throws clause must declare any checked exceptions that are not caught within the body of the method.

True

A multidimensional array can also be a method parameter. (True/False)

exchanging data

A network is a group of computers and other devices that are connected in some fashion for the purpose of_____ _____.

What is the difference between a static and a non-static inner class?

A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.

What restrictions are placed on the location of a package statement within a source code file?

A package statement must appear as the first line in a source code file (excluding blank lines and comments).

Ancestor class

A parent of a parent of another class (or some # of "parent of" is often called the __________

If a variable is declared as private, where may the variable be accessed?

A private variable may only be accessed within the class in which it is declared.

Java interface

A program component that contains the headings for a number of public methods *including public named constants *comments describing the methods so a programmer will have the necessary info to use them

What is the argument type of a program's main() method?

A program's main() method takes an argument of the String[] type.

What is a transient variable?

A transient variable is a variable that may not be serialized.

2,3,4

A two-dimensional array would require _____ for loops to step through all the index variables, A three-dimensional would need ______, four-dimensional ____ and etc.

If a method is declared as protected, where may the method be accessed?

A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

Can an object be garbage collected while it is still reachable?

A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.

Is-a relationship

A relationship in between two classes in which the derived can be identified as the bass class.

Array

A special kind of object used to store data that all must be of the same type; Collection of items of the same type

Object

A specific instance of a class or a thing that fulfills the definition that all other things of that definition fulfill (i.e. A specific string = specific instance)

What is the difference between static and non-static variables?

A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

Which of the following is true regarding subclasses?

A subclass inherits methods and instance variables from its superclass.

What is a task's priority and how is it used in scheduling?

A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.

What are three ways in which a thread can enter the waiting state?

A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

What are the two basic ways in which classes that can be run as threads may be defined?

A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.

When a thread blocks on I/O, what state does it enter?

A thread enters the waiting state when it blocks on I/O.

When is a thread created and started, what is its initial state?

A thread is in the ready state after it has been created and started.

What classes of exceptions may be thrown by a throw statement?

A throw statement may throw any expression that may be assigned to the Throwable type.

Which of the following operations is performed more efficiently by doubly linked list than by singly linked list? A. Deleting a node whose location is given B. Searching of an unsorted list for a given item C. Inserting a node after the node with given location D. Traversing a list to process each node

A. Deleting a node whose location is given

Consider a singly linked list of n elements. What is the time taken to insert an element after an element pointed by some pointer? A. O (1) B. O (log n) C. O (n) D. O (n log n)

A. O (1)

Recursively visiting the root node, left subtree and then the right subtree describes: A. preorder processing B. inorder processing C. postorder processing

A. preorder processing

A linear list in which the pointer points only to the next node is a _____________ A. singly linked list B. circular linked list C. doubly linked list

A. singly linked list

The ____________________ manager is the default manager class for all content panes.

ANSWER: BorderLayout

A(n) ____________________ is a plain, borderless surface that can hold lightweight GUI components.

ANSWER: JPanel

You use the ____________________ interface when you are interested in actions the user initiates from the keyboard.

ANSWER: KeyListener

____________________ are lists of user options; they are commonly added features in GUI programs.

ANSWER: Menus

A(n) _________________________ is a tree of components that has a top-level container as its root (that is, at its uppermost level).

ANSWER: containment hierarchy

legacy classes : BitSet

A_______ class creates a special type of array that holds bit values. This array can increase in size as needed.

What is the name of the icon that appears at the top-left of the opening bar across the opening screen (Activity) of the app?

Action bar icon

Arithmetic Operators

Add,Sub,Mult,Div

What invokes a thread's run() method?

After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

2 bytes

After the following program is finished, how many bytes are written to the file t.dat? import java.io.*; public class Test { public static void main(String[] args) throws IOException { DataOutputStream output = new DataOutputStream( new FileOutputStream("t.dat")); output.writeChar('A'); output.close(); } }

8 bytes

After the following program is finished, how many bytes are written to the file t.dat? import java.io.*; public class Test { public static void main(String[] args) throws IOException { DataOutputStream output = new DataOutputStream( new FileOutputStream("t.dat")); output.writeChars("ABCD"); output.close(); } }

4 bytes

After the following program is finished, how many bytes are written to the file t.dat? import java.io.*; public class Test { public static void main(String[] args) throws IOException { DataOutputStream output = new DataOutputStream( new FileOutputStream("t.dat")); output.writeShort(1234); output.writeShort(5678); output.close(); } }

6 bytes

After the following program is finished, how many bytes are written to the file t.dat? import java.io.*; public class Test { public static void main(String[] args) throws IOException { DataOutputStream output = new DataOutputStream( new FileOutputStream("t.dat")); output.writeUTFString("ABCD"); output.close(); } }

Consider the code snippet shown below. Assume that employeeNames is an instance of type LinkedList<String>. for (String name : employeeNames) { // Do something with name here } Which element(s) of employeeNames does this loop process?

All elements

rules to define Generic Methods : a type parameter section

All generic method declarations have a ______ delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example).

A. the Cloneable interface B. the Serializable interfaces

All the concrete classes in the Java Collections Framework implement _____________.

one memory address

All the contents of an array are stored in _______________--

Inheritance

Alllows you to use an existing class to define new classes

state

Allow an object to alter its behavior when its internal state changes.The object will appear to change its class.

Interface

Allow you to specify the methods that a class must implement

Inheritance

Allows class to use functionality of another

observer

Allows objects to be notified when state changes

If/else/if

Allows separate blocks of code to run

Inhertiance

Allows you to define a very general class and them later define more specialized classes that add some new details to the existing general class

Polymorphism

Allows you to make changes to the method definition in the derived class and apply those changes to the base class(happens automatically in Java)

List

Allows you to put elements in a specific order. Each element is associated with an index.

Comparable Interface

Allows you to specify how one object compares to another in terms of when one should "come before" "come after" or "equal" the other

public method;private

Although a derived class cannot access a private method in the base class, it can call a __________ that in turn calls a ____ method when both methods are in the base class.

client servers servers client

Although the distinction between client and server is becoming less clear each day, there is one fundamental distinction that is inherent in the Java programming language. The _____ initiates conversations with _____, while _____ block and wait for a _____ to initiate a conversation.

What an I/O filter?

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

Which of the following statements about abstract methods is true?

An abstract method has a name, parameters, and a return type, but no code in the body of the method.

What is an abstract method?

An abstract method is a method whose implementation is deferred to a subclass.

Can an anonymous class be declared as implementing an interface and extending a class?

An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

retrieved, added to, erased

An array as a list can only be _________ from, ________, or completely _________

Ragged array

An array in which different rows have different number of columns

What state is a thread in when it is executing?

An executing thread is in the running state.

argument

An indexed variable can be used as a(n) __________ anywhere a variable of the array's base type can be used by a method.

Which of the following statements about an inner class is true?

An inner class may be anonymous.

A. RuntimeException C. Error E. NumberFormatException Explanation: NumberFormatException is a subclass of RuntimeException

An instance of _________ are unchecked exceptions.

RuntimeException

An instance of _________ describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors..

Error

An instance of _________ describes system errors. If this type of error occurs, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

Exception

An instance of _________ describes the errors caused by your program and external circumstances. These errors can be caught and handled by your program.

Index

An integer expression that indicates an array element

When is an object subject to garbage collection?

An object is subject to garbage collection when it becomes unreachable to the program in which it is used.

descendant;ancestor

An object of a(n) __________ class can do the same things as an object of a(n) _________________ class.

When can an object reference be cast to an interface reference?

An object reference can be cast to an interface reference when the object implements the referenced interface.

How many times may an object's finalize() method be invoked by the garbage collector?

An object's finalize() method may only be invoked once by the garbage collector.

What is an object's lock and which object's have locks?

An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

What is a soft keyboard? Be sure to include its location in your answer.

An on-screen keyboard positioned at the bottom of the screen.

What happens if an exception is not caught?

An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

Can an unreachable object become reachable again?

An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

C. The code can compile and run fine. The second line assigns a new array to list.

Analyze the following code. int[] list = new int[5]; list = new int[6];

The program runs fine and displays x[0] is 0.

Analyze the following code. public class Test { public static void main(String[] args) { int[] x = new int[3]; System.out.println("x[0] is " + x[0]); } }

You should not declare a class that extends Error, because Error raises a fatal error that terminates the program.

Analyze the following code: class Test { public static void main(String[] args) throws MyException { System.out.println("Welcome to Java"); } } class MyException extends Error { }

The program has a compilation error. Explanation: catch (RuntimeException ex) should be specified before catch (Exception ex).

Analyze the following code: class Test { public static void main(String[] args) { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; } catch (Exception ex) { System.out.println("NumberFormatException"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } } }

A good programming practice is to avoid nesting try-catch blocks, because nesting makes programs difficult to read. You can rewrite the program using only one try-catch block. Explanation: The best answer is b. This question does not ask you what happens when you run the program. If you run the program, a RuntimeException would occur and it would be caught be the last catch clause.

Analyze the following code: class Test { public static void main(String[] args) { try { int zero = 0; int y = 2/zero; try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException } catch(Exception e) { } } catch(RuntimeException e) { System.out.println(e); } } }

C. The program displays a[1] is 0. Explanation: After executing the statement a = new int[2], a refers to int[2]. The default value for a[0] and a[1] is 0.

Analyze the following code: public class Test { public static void main(String[] args) { int[] a = new int[4]; a[1] = 1; a = new int[2]; System.out.println("a[1] is " + a[1]); } }

The program displays 1 2 3 4 5.

Analyze the following code: public class Test { public static void main(String[] args) { int[] oldList = {1, 2, 3, 4, 5}; reverse(oldList); for (int i = 0; i < oldList.length; i++) System.out.print(oldList[i] + " "); } public static void reverse(int[] list) { int[] newList = new int[list.length]; for (int i = 0; i < list.length; i++) newList[i] = list[list.length - 1 - i]; list = newList; } }

The program displays 5 4 3 2 1 and then raises an ArrayIndexOutOfBoundsException. Explanation: xMethod(x, 5) is invoked, then xMethod(x, 4), xMethod(x, 3), xMethod(x, 2), xMethod(x, 1), xMethod(x, 0). When invoking xMethod(x, 0), a runtime exception is raised because System.out.print(' '+x[0-1]) causes array out of bound.

Analyze the following code: public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4, 5}; xMethod(x, 5); } public static void xMethod(int[] x, int length) { System.out.print(" " + x[length - 1]); xMethod(x, length - 1); } }

C. The program has a compile error on the statement x = new int[2], because x is final and cannot be changed. Explanation: The value stored in x is final, but the values in the array are not final.

Analyze the following code: public class Test { public static void main(String[] args) { final int[] x = {1, 2, 3, 4}; int[] y = x; x = new int[2]; for (int i = 0; i < y.length; i++) System.out.print(y[i] + " "); } }

The program has a runtime error because the last statement in the main method causes ArrayIndexOutOfBoundsException. Explanation: After the for loop i is 5. x[5] is out of bounds.

Analyze the following code: public class Test { public static void main(String[] args) { int[] x = new int[5]; int i; for (i = 0; i < x.length; i++) x[i] = i; System.out.println(x[i]); } }

B. The program displays 0 0

Analyze the following code: public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4}; int[] y = x; x = new int[2]; for (int i = 0; i < x.length; i++) System.out.print(x[i] + " "); } }

A. The program displays 1 2 3 4

Analyze the following code: public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4}; int[] y = x; x = new int[2]; for (int i = 0; i < y.length; i++) System.out.print(y[i] + " "); } }

The program has a compile error because xMethod(new double[3]{1, 2, 3}) is incorrect. Explanation: new double[3]{1, 2, 3} should be replaced by new double[]{1, 2, 3}) (anonymous array).

Analyze the following code: public class Test1 { public static void main(String[] args) { xMethod(new double[]{3, 3}); xMethod(new double[5]); xMethod(new double[3]{1, 2, 3}); } public static void xMethod(double[] a) { System.out.println(a.length); } }

f2 is tail recursion, but f1 is not

Analyze the following functions; public class Test1 { public static void main(String[] args) { System.out.println(f1(3)); System.out.println(f2(3, 0)); } public static int f1(int n) { if (n == 0) return 0; else { return n + f1(n - 1); } } public static int f2(int n, int result) { if (n == 0) return result; else return f2(n - 1, n + result); } }

An exception is raised due to Integer.parseInt(s);

Analyze the following program. class Test { public static void main(String[] args) { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (Exception ex) { System.out.println(ex); } } }

The method runs infinitely and causes a StackOverflowError.

Analyze the following recursive method. public static long factorial(int n) { return n * factorial(n - 1); }

Program A produces the output 4 3 2 1 and Program B prints 4 3 2 1 1 1 .... 1 infinitely. Explanation: In Program B, xmethod(5) invokes xmethod(4), xmethod(4) invokes xmethod(3), xmethod(3) invokes xmethod(2), xmethod(2) invokes xmethod(1), xmethod(1) returns control to xmethod(2), xmethod(2) invokes xmethod(1) because of the while loop. This continues infinitely.

Analyze the following two programs: A: public class Test { public static void main(String[] args) { xMethod(5); } public static void xMethod(int length) { if (length > 1) { System.out.print((length - 1) + " "); xMethod(length - 1); } } } B: public class Test { public static void main(String[] args) { xMethod(5); } public static void xMethod(int length) { while (length > 1) { System.out.print((length - 1) + " "); xMethod(length - 1); } } }

Boolean Operators

And or not

Object

Every class is derived from the "Eve" class, __________

When reading words with a Scanner object, a word is defined as ___.

Any sequence of characters that is not white space.

Interchange sorting algorithm

Any sorting algorithm that swaps or interchanges values

What is the name of the default theme?

App Theme

Non-default constructor

Arguments are passed to it; Helps to construct an instance of the class

Sorting

Arranging a collection of items into a particular order in ascending or descending order.

List interface has two classes

ArrayList, LinkedList

No Explanation: The JVM loads just one ArrayList.

ArrayList<String> and ArrayList<Integer> are two types. Does the JVM load two classes ArrayList<String> and ArrayList<Integer>?

String ArrayList definition

ArrayList<String>productCode = new ArrayList<String>()

ArrayList constructors

ArrayList<Type>() ArrayList<Type>(int n) ArrayList<Type>(Collection obj)

value

ArrayName[n] = 32 is The ____of indexed variable

Polymorphism

Associating many meanings to one method name through dynamic binding.

true false

Assume int[] list1 = {3, 4, 1, 9, 13}, int[] list2 = {3, 4, 1, 9, 13}, and int[] list3 = {4, 3, 1, 9, 13}, what is System.out.println(java.util.Arrays.equals(list1, list2) + " " + java.util.Arrays.equals(list1, list3));

-2 Explanation: The binarySearch method returns the index of the search key if it is contained in the list. Otherwise, it returns ?insertion point - 1. The insertion point is the point at which the key would be inserted into the list. In this case the insertion point is 1. Note that the array index starts from 0

Assume int[] scores = {1, 20, 30, 40, 50}, what value does java.util.Arrays.binarySearch(scores, 3) return?

2

Assume int[] scores = {1, 20, 30, 40, 50}, what value does java.util.Arrays.binarySearch(scores, 30) return?

System.out.println(java.util.Arrays.toString(scores));

Assume int[] scores = {3, 4, 1, 9, 13}, which of the following statement displays all the element values in the array?

4

Assume int[] t = {1, 2, 3, 4}. What is t.length?

decorator

Attach additional responsibilities to an object dynamically._____ provide a flexible alternative to subclassing for extending functionality.

Chain of Responsibility

Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.

If you do not need efficient random access but need to efficiently move sequentially through the list, then use the _____________ class. A. Vector<T> B. LinkedList<T> C. HashSet<T> D. TreeSet<T>

B. LinkedList<T>

The Collection class or interface that allows only unique elements is the ___________ class or interface. A.List<T> B. Set<T> C. Vector<T> D. all of the above

B. Set<T>

The _________ node is the first node in the tree data structure. A. leaf B. root C. sibling D. branch

B. root

Declares an array of integers

Base_Type[] Array_Name

Parent class; child class

Bass class is often called a ____________ and a derived class is called a _________

If Bear class's equals(Bear b) is overloaded instead of overriden, would this use the Bear.equals(Bear b) method be used or Object.equals(Object o) be used? Bear b = new Bear(); Bear c = new Bear(); b.equals(c)

Bear's even though it's not overridden, when looking for a matching method, equals(Bear b) is exact and therefore matched before equals(Object o) bad practice, but legal!!

ancestor type; ancestor

Because an object of a derived class has the types of all of its ____________, you can assign an object of a class to a variable of any ___________ type, but not the other way around.

Why is sp the preferred measurement for text size?

Because you can scale it to fit a device.

Comparator

Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines precisely what sorted order means. -sort a given collection any number of different ways. Also this interface can be used to sort any instances of any class (even classes we cannot modify). - defines two methods: compare( ) and equals( ). The compare( ) method https://www.tutorialspoint.com/java/java_using_comparator.htm

Consider the following code snippet: public class Box<E> { private E data; public Box(){ . . . } } Which of the following is a valid Box<E> object instantiation?

Box<Double> box = new Box<>();

top-down design

Breaking down the task to be performed into substasks

Ternary

Breaks down if/else

OutputStream subclasses

BufferedOutputStream, DataOutputStream, FileOutputStream

buffered text file reading definition

BufferedReader in = new BufferedReader(new FileReader("mydata.txt"))

Write one line of code that declares a Button control with the variable name btn that references a button in the XML layout with the Id property of btnStarWars.

Button btn = (Button)findViewById(R.id.btnStarWars);

Write one line of code that declares a Button control with the variable named btn that references a button in the XML layout with the Id property of btnStarWars.

Button btn = (Button)findViewById(R.id.btnStarWars);

The time required to delete a node x from a doubly linked list having n nodes is A. O (n) B. O (log n) C. O (1) D. O (n log n)

C. O (1)

What does the left node reference get set to in a newly inserted binary tree node? A. depends where the node is inserted B. it gets set to the left child of the new node, if one exists C. always null D. it gets set to the left child of the root, if it exists

C. always null

The hasNext() method of the Iterator interface has a return value of: A. Object B. int C. boolean D. none of the above

C. boolean

A ____________ linked list has nodes that contain two references to Nodes. A. circular B. sequential C. doubly D. one-way

C. doubly

A _________________ maps a data value such as a String into a number: A. recursive function B. key function C. hash function

C. hash function

Recursively visiting the left subtree, right subtree and then the root describes: A. preorder processing B. inorder processing C. postorder processing

C. postorder processing

The method ___________ can be used to determine the number of elements in an ArrayList. A. length() B. vectorLength() C. size() D. vectorSize()

C. size()

A node of binary tree has exactly _________ link instance variables. A. zero B. one C. two D. three

C. two

path name examples

C:/MyJavaPrograms/myprog.java or MyFiles/anyfile.txt

Which two keys are pressed to auto complete a line of Java code?

CTRL + Spacebar

Static Method

Can be called directly by choosing the name of the class and method name

Methods

Can be public/private, static/non-static, and have a variables with scope within it, and have a return type (primitive/class) returning only one thing.

Instance Variables

Can be public/private, static/non-static, and of a certain type(primitive/class)

b

Can we use the annotation @PrePassivate for more than one method in a Entity bean? a. Yes b. No

char

Character

The Java compiler requires that your program handle which type of exceptions?

Checked.

A class(ClassOne) is considered to have a dependency on another class(ClassTwo) under which of the following conditions?

ClassOne uses objects of ClassTwo.

How are commas used in the intialization and iteration parts of a for statement?

Commas are used to separate multiple statements within the initialization and iteration parts of a statement.

equals

Compares values stored in instance variables of calling and passed instances of a class *Public *Returns a boolean *Expects an argument *Inherited from Object class *Should be overriden in every class

composite

Compose objects into tree structures to represent part-whole hierarchies.Clients treat collections of objects and individual objects uniformly.

Consider the following code snippet. public interface Measurable { double getMeasure(); } public class Coin implements Measurable { public double getMeasure() { return value; } ... } public class DataSet { ... public void add() { ... } } public class BankAccount { ... public void add() { ... } } Which of the following statements is correct?

Con dime = new Coin(0.1, "dime"); Measurable x = dime;

For Each Loops

Concise for loop

To query a database, a JavaBean needs a(n) ____________ object.

Connection

Which Java statement connects to a database using a Connection object?

Connection conn = DriverManager.getConnection(url, username, password);

a

Consider the following HTML code. Which method of MyFirstServlet will be invoked when you click on the url shown by the page? a. doGet b. doPost c. GET d. POST e. doGET f. doPOST

adapter

Convert the interface of a class into another interface clients expect.

One of the steps in deploying a JSF application is to ______ of the web application:

Create a WEB-INF subdirectory in the application directory

Constructors

Create the instance.

In a binary search tree, where the root node key = 34, what do we know about the keys of all the descendents in the left subtree of the root? A. the root's left child key < 34, but the right child of the root's left child key is > 34 B. some keys will be < 34, but there may be a few keys > 34 C. approximately half the keys are < 34, the other half are > 34 D. all will be < 34

D. all will be < 34

The method contains(Object o) of the ArrayList class returns a value of type: A. int B. Object C. ArrayList D. boolean

D. boolean

All of the following methods are part of the Collection<T> interface except: A. contains() B. toArray() C. retainAll() D. toString()

D. toString()

The operation of processing each element in the list is known as ...... A. sorting B. merging C. inserting D. traversal

D. traversal

What happens if you use the enum type prefix on an enum value in a switch case statement?

DOES NOT COMPILE Season s = Season.SUMMER switch (s) { case Season.SUMMER: case Season.WINTER: default: break; }

buffered binary writing stream definition

DataOutputStream out = new DataOutputStream(newBufferedOutputStream(new FileOutputStream("file.dat")))

class scope

Deals with class relationships that can be changed at compile time

object scope

Deals with object relationships that can be changed at runtime

bridge

Decouple an abstraction from its implementation so that the two can vary independently.

strategy

Define a family of algorithms, encapsulate each one, and make them interchangeable._____ lets the algorithm vary independently from clients that use it.

observer

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

factory method

Define an interface for creating an object, but let subclasses decide which class to instantiate.____ lets a class defer instantiation to subclasses.

template method

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses._____ lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

System.out.println

Defining a suitable toString method for your classes allows you to use _________________ to output the toString of the class.

Class

Definition of a type ; a plan or blueprint( i.e. Strings - defines anything that is a string)

Yes

Do the following two programs produce the same result? Program I: public class Test { public static void main(String[] args) { int[] list = {1, 2, 3, 4, 5}; reverse(list); for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); } public static void reverse(int[] list) { int[] newList = new int[list.length]; for (int i = 0; i < list.length; i++) newList[i] = list[list.length - 1 - i]; list = newList; } } Program II: public class Test { public static void main(String[] args) { int[] oldList = {1, 2, 3, 4, 5}; reverse(oldList); for (int i = 0; i < oldList.length; i++) System.out.print(oldList[i] + " "); } public static void reverse(int[] list) { int[] newList = new int[list.length]; for (int i = 0; i < list.length; i++) newList[i] = list[list.length - 1 - i]; list = newList; } }

Yes

Does <? super Number> represent a superclass of Number?

polymorphic definition (dog, poodle)

Dog aDog = new Poodle(); (less specific to more specific)

What restrictions are placed on the values of each case of a switch statement?

During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

the exceptions that inherit from _____ are thrown when a critical error occurs, such as running out of memory

Error (703)

unique address

Each of the devices on the network can be thought of as a node, and each node has a _____ _____.

ports port 80

Each server computer that you may connect to will be logically organized into _____. For example, if you want to connect with a public server that communicates using the HTTP protocol, you would normally connect to _____ on the server of interest.

rules to define Generic Methods : contains one or more type parameters separated by commas

Each type parameter section ________________ . A type parameter, also known as a type variable, is an identifier that specifies a generic type name.

observer

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

strategy

Encapsulates inter-changeable behavior and uses delegation to decide which to use

singleton

Ensure a class only has one instance, and provide a global point of access to it.

singleton

Ensures one and only one instance of an object is created

four bytes or 32 bits 128-bit

Every computer attached to an IP network has a unique address, typically consisting of ______. Efforts are underway to expand the number of possible unique addresses to a much larger number. The planned number is the number of unique addresses that can be represented with a _____ address.

unique IP address domain name

Every computer on the Internet must have a _____ _____ _____, but multiple computers can have (or can respond to) the same _____ _____.

The Collection Classes : AbstractList

Extends AbstractCollection and implements most of the List interface.

The Collection Classes : AbstractSet

Extends AbstractCollection and implements most of the Set interface.

The Collection Classes : AbstractSequentialList

Extends AbstractList for use by a collection that uses sequential rather than random access of its elements.

The Collection Classes : IdentityHashMap

Extends AbstractMap and uses reference equality when comparing documents. -designed for use only in rare cases wherein reference-equality semantics are required.

The Collection Classes : WeakHashMap

Extends AbstractMap to use a hash table with weak keys. -Storing only weak references allows a key-value pair to be garbage-collected when its key is no longer referenced outside of the WeakHashMap.

The Collection Classes : HashMap

Extends AbstractMap to use a hash table. -uses a hashtable to implement the Map interface. -allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets.

The Collection Classes : TreeMap

Extends AbstractMap to use a tree. -provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval -guarantees that its elements will be sorted in an ascending key order.

The Collection Classes : HashSet

Extends AbstractSet for use with a hash table. -A hash table stores information by using a mechanism called hashing. -In hashing, the informational content of a key is used to determine a unique value, called its hash code. -The hash code is then used as the index at which the data associated with the key is stored. -The transformation of the key into its hash code is performed automatically.

The Collection Classes : LinkedHashMap

Extends HashMap to allow insertion-order iterations.

The Collection Classes : LinkedHashSet

Extends HashSet to allow insertion-order iterations. -extends HashSet, but adds no members of its own. -maintains a linked list of the entries in the set, in the order in which they were inserted. This allows insertion-order iteration over the set. -will be returned in the order in which they were inserted. -The hash code is then used as the index at which the data associated with the key is stored. -The transformation of the key into its hash code is performed automatically.

What does XML stand for?

Extensible Markup Language

sort(list, list.length - 1)

Fill in the code to complete the following method for sorting a list. public static void sort(double[] list) { ___________________________; } public static void sort(double[] list, int high) { if (high > 1) { // Find the largest number and its index int indexOfMax = 0; double max = list[0]; for (int i = 1; i <= high; i++) { if (list[i] > max) { max = list[i]; indexOfMax = i; } } // Swap the largest with the last number in the list list[indexOfMax] = list[high]; list[high] = max; // Sort the remaining list sort(list, high - 1); } }

(1) Comparable<MyInt> / (2) MyInt

Fill in the most appropriate code in the place (1) and (2) in the MyInt class? public class MyInt implements ___(1)____ { int id; public MyInt(int id) { this.id = id; } public String toString() { return String.valueOf(id); } public int compareTo(___(2)____ arg0) { if (id > arg0.id) return 1; else if (id < arg0.id) return -1; else return 0; } }

If

First part of conditional expression

Which keys change the orientation of the emulator on a PC?

Fn + left Ctrl + F12

rows, columns

For a two-dimensional array b, the value of b.length is the number of ______, (integer in 1st bracket pair). The value of b[i].length is the number of _______ (integer in 2nd bracket pair)

unsigned decimal

For human consumption, we usually convert the value of each of the IP address bytes to an _____ _____ value and display them connected by periods to make them easier to remember. For example, a typical IP address might be 206.77.150.222.

If an outer class and an inner class have the same instance variable, how can they each be accessed?

For instance variables, the reference type determines which variable is used. public class LongTail() { private String name="longtail"; public class Fox implements LongTail() { private String name="fox"; } public static void main(String[] args) { LongTail lt = new Fox(); Fox f = new Fox(); System.out.println(lt.name); // prints longtail System.out.println(f.name); // prints fox } }

low is 4 and high is 6

For the binarySearch method in Section 6.9.2, what is low and high after the first iteration of the while loop when invoking binarySearch(new int[]{1, 4, 6, 8, 10, 15, 20}, 11)?

Consider the following code snippet in the LinkedList<E> class: public void addAll(LinkedList<? extends E> other) { ListIterator<E> iter = other.listIterator(); while (iter.hasNext()) { add(iter.next()); } } Which of the following statements about this code is correct?

For the element type of other, you must supply a type that is a subtype of E.

Base_Type[] Array_Name = new Base_Type[Length];

Format for creating an array:

What is Gang of Four (GOF)?

Four authors of Book 'Design Patterns - Elements of Reusable Object-Oriented Software' are known as Gang of Four (GOF).

What are the two types of built-in Android animation?

Frame and Tween Animation

Does garbage collection guarantee that a program will not run out of memory?

Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

Interpreter

Given a language, define a represention for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

Rational Operators

Greater/Less than or equal to

Which color is represented by the hexadecimal code of #00FF00?

Green (yellow is #FFFF00, red is #FF0000, blue is #0000FF)

a

HTTP is a "stateless" protocol: each time a client retrieves a Web page, it opens a separate connection to the Web server, and the server does not automatically maintain contextual information about a client. a. True b. False

Map interface has two classes

HashMap and TreeMap

C. char[] charArray = {'a', 'b'}; D. char[] charArray = new char[]{'a', 'b'};

How can you initialize an array of two characters to 'a' and 'b'?

5

How many elements are in array double[] list = new double[5]?

6

How many times is the factorial method in Listing 20.1 invoked for factorial(5)?

B. 15 Explanation: Hint: number of time fib is invoked in fib(5) = 1 + number of time fib is invoked in fib(3) + number of time fib is invoked in fib(4) = 1 + 5 + 9 = 15

How many times is the fib method in Listing 20.2 invoked for fib(5)?

7

How many times is the recursive moveDisks method invoked for 3 disks?

15

How many times is the recursive moveDisks method invoked for 4 disks?

a

HttpSession objects have a built-in data structure that lets you store any number of keys and associated values. a. True b. False

We might choose to use a linked list over an array list when we will not require frequent ____. I random access II inserting new elements III removing of elements

I

Which of the following does not create an object that can run in a thread, assuming the following MyRunnable class declaration? public class MyRunnable implements Runnable { . . . } I Runnable runnable = new Runnable(); II Runnable runnable = new MyRunnable(); III MyRunnable runnable = new MyRunnable();

I

Which statement is true regarding the following code, assuming reader is a FileInputStream object? char ch = (char) reader.read(); I you cannot determine if you have reached the end of input II this code will throw an exception if we are at the end of input III read returns an int, so the cast is illegal

I

Which of these classes access sequences of characters? I readers II writers III streams

I and II

Consider the following code snippet: public interface MyInterface<E> { . . . } public interface YourInterface<E, T> extends MyInterface<E> { . . . } Which of these are legal class declarations? I public class SomeClass implements YourInterface<String, Double> { . . . } II public class SomeClass implements YourInterface { . . . } III public class SomeClass implements YourInterface<String> { . . . }

I and II only

Which of the following necessitates the type erasure process? I The Java virtual machine does not work with generic types II To maintain backward compatibility to older versions of Java III Generics do not work with primitives

I and II only

What is included in a linked list node? I a reference to its neighboring nodes II an array reference III a data element

I and III

Which of the following classes are related through inheritance? I InputStream II InputStreamReader III ObjectInputStream

I and III

Consider the following code snippet. PrintWriter outputFile = new PrintWriter("payrollReport.txt"); Which of the following statements about the PrintWriter object is correct?

If a file named "payrollReport.text" already exists, existing data will be deleted before new data is added to the file.

-(insertion point + 1)

If a key is not in the list, the binarySearch method returns _________.

What happens when a thread cannot acquire a lock on an object?

If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

is-a;has-a

If an __ relationship does not exist b/w two proposed classes, do not use inheritance to derive one class from the other but define an object of one class as an INSTANCE variable WITHIN the OTHER CLASS. This is called _____

What is the difference between the Boolean & operator and the && operator?

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

Out of bounds

If an index expression evaluates to an integer outside of the possible integers it is said to be ____________

has a

If class A has an object of class B as an instance variable, the relationship between A and B is _______

If/else

If or else

2.0

If you declare an array double[] list = {3.4, 2.0, 3.5, 5.5}, list[1] is ________.

3

If you declare an array double[] list = {3.4, 2.0, 3.5, 5.5}, the highest index in array list is __________.

report warning and generate a class file

If you use the javac ?Xlint:unchecked command to compile a program that contains raw type, what would the compiler do?

report warning and generate a class file if no other errors in the program. Explanation: For javac, a class file is generated even if the program has compile warnings.

If you use the javac command to compile a program that contains raw type, what would the compiler do?

b

If you want to send an entity object as the pass by value through a remote interface, which of the following statements are valid? (Choose one) a. @Entity a. public class Employees implements SessionSynchronization{ a. ... a. } b. @Entity b. public class Employees implements Serializable{ b. ... b. } c. public class Employees implements Serializable{ c. ... c. } d. @entity d. public class Employees implements Serializable{ d. ... d. }

One of the required steps in designing a JavaBean is:

Implement the get and set methods for all properties.

guarantee; defines

Implementing an interface is a way for a programmer to __________ that a class ______ certain methods.

The Collection Classes : ArrayList

Implements a dynamic array by extending AbstractList. -ArrayList supports dynamic arrays that can grow as needed. -are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

Which of the following would be an appropriate name for a game-related class?

InitialLevel

If you store information in binary form, as a sequence of bytes, you will use the ___ class(es) and their subclasses.

InputStream and OutputStream

Object

Instance of class that stores state of class

Class

Instructions that describe data behavior

Constructor

Instructs the classing trial state of object

Data types

Int, Boolean, char

int

Integer

Which arithmetic operations can result in the throwing of an ArithmeticException?

Integer / and % can result in the throwing of an ArithmeticException.

In Java, ___ can be used for callbacks.

Interfaces

All collections frameworks contain

Interfaces Implementations Algorithms

The ___ occurs when a thread that is not running is interrupted.

InterruptedException

The sleep method is terminated with a(n) ___ whenever a sleeping thread is interrupted.

InterruptedException

Which exception must be caught or declared when calling the sleep method?

InterruptedException

Yes

Is ArrayList<?> same as ArrayList<? extends Object>?

Yes

Is ArrayList<Integer> a subclass of ArrayList<? extends Number>?

Yes

Is ArrayList<Integer> a subclass of ArrayList<?>?

No

Is ArrayList<Integer> a subclass of ArrayList<Object>?

Yes

Is ArrayList<Number> a subclass of ArrayList<? extends Number>?

How can a static nested class be instantiated in the class in which is defined?

It can be instantiated stand alone like any other type - no need for an instance of the enclosing type this also means without an enclosing type instance, the stand alone static class instance can't access instance variables of the enclosing class

What does the following if statement do? if (code == HttpURLConnetion.HTTP_OK)

It checks if the code is 200.

What is hashCode() used for?

It defines how to store an object with a key in a map

In which subfolder is the activity_main.xml file storage?

It is in a subfolder of the res folder named layout

What is the % operator?

It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.

What is the purpose of the throw statement?

It is used to pass control to an error handler when an error situation is detected.

Since a member inner class isn't static, how can it be instantiated?

It must be instantiated from an instance of the outer class. Outer outer = new Outer(); Inner inner = outer.new Inner(); //inner can now be used as an instance NOTE THE WEIRD SYNTAX

What must a class do to implement an interface?

It must provide all of the methods in the interface and identify the interface in its implements clause.

How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

A(n) ___ has an instance method addActionListener() for specifying which object is responsible for implementing the action associated with the object.

JButton

Java : Exceptions & Advanced File I/O (10) (681-729)

Java : Exceptions & Advanced File I/O (10) (681-729)

Which two languages are used in creating an Android app in Android Studio?

Java and XML

The Collection Classes

Java provides a set of standard collection classes that implement Collection interfaces. Some of the classes provide full implementations that can be used as-is and others are abstract class, providing skeletal implementations that are used as starting points for creating concrete collections.

Socket , DatagramSocket , ServerSocket URL, URLEncoder, URLConnection

Java provides at least two different approaches for doing network programming (and possibly more) , insofar as the web is concerned. The two approaches are associated with the _____ _____ and _____ classes and the _____ _____ and _____ classes.

socket URL

Java provides at least two different ways to do network programming. The two ways are associated with _____ classes and _____ classes.

address

Java stores what part of the objects in an array?

this

Method that calls a constructor of the same class

Which of the following statements is correct?

Methods of an inner class can access instance variables from the surrounding scope.

Private

Methods that can only be called from the class in which it resides in.

packet switching

Modern networks transfer data using a concept known as _____ ____.

domain name

Most IP addresses have a corresponding name known as a _____ _____.

Consider the following code snippet: public class Motorcycle extends Vehicle { . . . } Which of the following statements correctly describes the relationship between the Motorcycle and Vehicle classes?

Motorcycle exhibits the is-a relationship with regard to Vehicle.

Non-static Method

Must be called by an instance of the class in which it resides

Overriding

Must be declared in this way: public String toString();//no arguments passed and public boolean equals(ObjectType alias);//you must pass an object of the same type as the class in which it resides

Can an anonymous inner class implement an interface an extend a class?

NO! can only do one or the other UNLESS extending from Object class (special case)

Suppose that sock refers to a TCP socket connected to another machine, and in is aScanner. Which code sends the string "Who is there?" to the other machine, receives the return answer, and then prints it?

PrintWriter pw = new PrintWriter(sock.getOutputStream()); pw.println("Who is there?"); pw.flush(); InputStream instream = sock.getInputStream(); Scanner in = new Scanner(instream); System.out.println(in.nextLine());

Writer class subclasses

PrintWriter, BufferedWriter, FileWriter

Set

Prohibits duplicate elements. Easy test for membership. You can't order the elements.

flushing flush

Proper _____ is an important aspect of socket programming. Use the true parameter to _____ the output stream automatically.

proxy

Provide a surrogate or placeholder for another object to control access to it.

facade

Provide a unified interface to a set of interfaces in a subsystem._____ defines a higher-level interface that makes the subsystem easier to use.

iterator

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

composite

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

a

QN=1 (10082) If you want the same Servlet to handle both GET and POST and to take the same action for each, you can simply have doGet call doPost, or vice versa. a. True b. False

a

QN=1 (10130) ________ is the well-known host name that refers to your own computer. a. localhost b. computer name c. DNS d. ip

b

QN=10 (7155) Which of these is a correct fragment within the web-app element of deployment descriptor? Select the one correct answer a. <exception> <exception-type> mypackage.MyException</exception-type> <location> /error.jsp</location> </exception> b. <error-page> <exception-type> mypackage.MyException</exception-type> <location> /error.jsp</location> </error-page> c. <error-page> <exception> mypackage.MyException </exception-type> <location> /error.jsp </location> </error-page> d. <error-page> <exception-type> mypackage.MyException</exception-type> </error-page> e. <error-page> <servlet-name> myservlet</servlet-name> <exception-type> mypackage.MyException</exception-type> </error-page> f. <exception> <servlet-name> myservlet</servlet-name> <exception-type> mypackage.MyException</exception-type> </exception>

d

QN=10 (9431) Which of the following is NOT a standard technique for providing a sense of "state" to HTTP? a. Cookies b. URL rewriting c. SSL Sessions d. HTTP is already a stateful protocol.

c

QN=12 (7275) What gets printed when the following code snippet is compiled? Select the one correct answer. <% int y = 0; %> <% int z = 0; %> <% for(int x=0;x<3;x++) { %> <% z++;++y;%> <% }%> <% if(z<y) {%> <%= z%> <% } else {%> <%= z - 1%> <% }%> a. 0 b. 1 c. 2 d. 3 e. The program generates compilation error.

d

QN=12 (9418) Identify the method used to get an object available in a session. (Choose one) a. getAttribute of Session b. getValue of HttpSession c. get of Session d. getAttribute of HttpSession

a

QN=13 (7178) For application and session JSP scopes, what class of object is used to store the attributes? (Choose one) a. ServletContext and HttpSession respectively. b. HttpSession for both. c. ServletContext for both. d. HttpSession and ServletContext respectively

a

QN=13 (7292) What is output to the web page on the second access to the same instance of the following JSP? <html> <body> <% int x = 0; %> <%= x++ %> </body> </html> a. 0 b. 1 c. 2 d. 3

a

QN=14 (7257) A JSP page called test.jsp is passed a parameter name in the URL using http://localhost/Final/test.jsp?name=John. The test.jsp contains the following code. <% String myName=request.getParameter("name");%> <% String test= "Welcome " + myName; %> <%=test%> What is the output? a. The page display "Welcome John" b. The program gives a syntax error because of the statement <% String myName=request.getParameter("name");%> c. The program gives a syntax error because of the statement <% String test= "Welcome " + myName; %> d. The program gives a syntax error because of the statement <%=test%>

a

QN=14 (9440) Identify the method used to get an object available in a session.(Choose one) a. getAttribute of HttpSession b. getAttribute of Session c. getValue of HttpSession d. getValue of Session

a

QN=15 (10156) Each page has its own instances of the page-scope implicit objects. a. True b. False

d

QN=15 (7180) Which of the following method calls can be used to retrieve an object from the session that was stored using the name "userid"? a. getObject("userid"); b. getValue("userid"); c. get("userid"); d. getAttribute("userid"); e. getParameter("userid");

a

QN=16 (7286) JavaServer Pages (JSP) technology enables you to mix regular, static HTML with dynamically generated content from servlets. You simply write the regular HTML in the normal manner, using familiar Web-page-building tools. a. True b. False

a

QN=16 (9455) Select the correct directive statement insert into the first line of following lines of code (1 insert code here): a. <%@page import='java.util.*' %> b. <%@import package='java.util.*' %> c. <%@ package import ='java.util.*' %> d. <%! page import='java.util.*' %>

a

QN=17 (7260) A JSP page needs to generate an XML file. Which attribute of page directive may be used to specify that the JSP page is generating an XML file? a. <%@page contentType ="text/xml"> b. <%@page contentType ="xml"> c. <%@page contentType ="text/html"> d. <%@page contentType ="html/xml">

b

QN=17 (7263) Which of the following correctly represents the following JSP statement? Select one correct answer. <%=x%> a. <jsp:expression=x/> b. <jsp:expression>x</jsp:expression> c. <jsp:statement>x</jsp:statement> d. <jsp:declaration>x</jsp:declaration> e. <jsp:scriptlet>x</jsp:scriptlet>

d

QN=18 (7278) Which of the following is correct? Select one correct answer a. JSP scriptlets and declarations result in code that is inserted inside the _jspService method b. The JSP statement <%! int x; %> is equivalent to the statement <jsp:scriptlet>int x;</jsp:scriptlet%>. c. The following are some of the predefined variables that maybe used in JSP expression - httpSession, context. d. To use the character %> inside a scriptlet, you may use %\> instead.

e

QN=18 (7284) Which of the following JSP variable is not available within a JSP expression? Select one correct answer a. out b. session c. request d. response e. httpsession f. page

c

QN=19 (7252) Which of the following constitute valid ways of importing Java classes into JSP page source? a. <%! import java.util.*; %> b. <%@ import java.util.* %> c. <%@ page import="java.util.*" %> d. None of the others

a

QN=2 (10098) Which of the following is correct statement? a. The getRequestDispatcher method of ServletContext class takes the full path of the servlet, whereas the getRequestDispatcher method of HttpServletRequest class takes the path of the servlet relative to the ServletContext. b. The include method defined in the RequestDispatcher class can be used to access one servlet from another. But it can be invoked only if no output has been sent to the server. c. The getNamedDispatcher(String) defined in HttpServletRequest class takes the name of the servlet and returns an object of RequestDispatcher class

c

QN=2 (10110) Following is the code for doGet() and doPost() method of TestServlet. Which of the statement is correct? image a. This will only work for HTTP GET requests b. This will only work for HTTP POST requests c. This will work for HTTP GET as well as POST requests. d. It'll throw an exception at runtime, as you cannot call doGet() from doPost(). e. It'll throw an exception at runtime only if a POST request is sent to it.

e

QN=20 (10152) Which statements are BEST describe request implicit object of jsp file? a. This javax.servlet.jsp.JspWriter object writes text as part of the response to a request. This object is used implicitly with JSP expressions and actions that insert string content in a response. b. This java.lang.Object object represents the this reference for the current JSP instance. c. This javax.servlet.jsp.PageContext object hides the implementation details of the underlying servlet and JSP container and provides JSP programmers with access to the implicit objects discussed in this table. d. This object represents the response to the client. The object normally is an instance of a class that implements HttpServletResponse (package javax.servlet.http). If a protocol other than HTTP is used, this object is an instance of a class that implements javax.servlet.ServletResponse. e. This object represents the client request. The object normally is an instance of a class that implements HttpServletRequest (package javax.servlet.http). If a protocol other than HTTP is used, this object is an instance of a subclass of javax.servlet.ServletRequest.

b

QN=20 (10153) An object with page scope exists in every JSP of a particular Web application. a. True b. False

d

QN=21 (7280) <html> <body> <form action="loginPage.jsp"> Login ID:<input type= "text" name="loginID"><br> Password:<input type="password" name="password"><br> <input type="submit" value="Login"> <input type="reset" value="Reset"> </form> </body> <html> Study the above html code. Assume that user clicks button Login. Which is the correct statement? a. The form intputs are submitted by GET method. b. The loginPage.jsp is called. c. The value of two text inputs appended to the requested URL. d. All of the others

a

QN=21 (7288) <html> <body> <form action="loginPage.jsp"> Login ID:<input type= "text" name="loginID"><br> Password:<input type="password" name="password"><br> <input type="submit" value="Login"> <input type="reset" value="Reset"> </form> </body> <html> Study the above html code. Assume that user clicks button Reset. What is the correct statement? a. All inputs are cleared. b. All inputs are submitted to server. c. Nothing changes.

c

QN=21 Which is true about JEE ( or J2EE)? a. JEE applications depend on web servers b. JEE runs on consumer and embedded devices c. JEE includes servlet APIs and EJB APIs d. JEE can be run only on tomcat web servers

b

QN=22 (10149) Which statements are BEST describe page implicit object of jsp file? a. This javax.servlet.jsp.JspWriter object writes text as part of the response to a request. This object is used implicitly with JSP expressions and actions that insert string content in a response. b. This java.lang.Object object represents the this reference for the current JSP instance. c. This javax.servlet.jsp.PageContext object hides the implementation details of the underlying servlet and JSP container and provides JSP programmers with access to the implicit objects discussed in this table. d. This object represents the response to the client. The object normally is an instance of a class that implements HttpServletResponse (package javax.servlet.http). If a protocol other than HTTP is used, this object is an instance of a class that implements javax.servlet.ServletResponse. e. This object represents the client request. The object normally is an instance of a class that implements HttpServletRequest (package javax.servlet.http). If a protocol other than HTTP is used, this object is an instance of a subclass of javax.servlet.ServletRequest.

a

QN=22 (9456) Which of the following is equivalent <%! ? (Choose one) a. <jsp:declaration b. <%= c. <%

d

QN=22 What is the purpose of JNDI? a. To parse XML documents b. To access native code from Java application c. To register Java Web Start applications with a web server d. To access various directory services using a single interface

d

QN=23 (10151) Which statements are BEST describe response implicit object of jsp file? a. This javax.servlet.jsp.JspWriter object writes text as part of the response to a request. This object is used implicitly with JSP expressions and actions that insert string content in a response. b. This java.lang.Object object represents the this reference for the current JSP instance. c. This javax.servlet.jsp.PageContext object hides the implementation details of the underlying servlet and JSP container and provides JSP programmers with access to the implicit objects discussed in this table. d. This object represents the response to the client. The object normally is an instance of a class that implements HttpServletResponse (package javax.servlet.http). If a protocol other than HTTP is used, this object is an instance of a class that implements javax.servlet.ServletResponse. e. This object represents the client request. The object normally is an instance of a class that implements HttpServletRequest (package javax.servlet.http). If a protocol other than HTTP is used, this object is an instance of a subclass of javax.servlet.ServletRequest.

d

QN=23 (7282) Which of these is true about include directive? Select the one correct answer. a. The included file must have jsp extension. b. The XML syntax of include directive in <jsp:include file="fileName"/> . c. The content of file included using include directive, cannot refer to variables local to the original page. d. When using the include directive, the JSP container treats the file to be included as if it was part of the original file.

a

QN=23 Which is NOT Enterprise Beans? a. Business Beans b. Entity Beans c. Session Beans d. Message-Driven Beans

a

QN=24 (10168) Which statements are BEST describe name attribute of <jsp:setProperty name=.... /> action? a. The ID of the JavaBean for which a property (or properties) will be set. b. The name of the property to set. Specifying "*" for this attribute causes the JSP to match the request parameters to the properties of the bean. c. If request parameter names do not match bean property names, this attribute can be used to specify which request parameter should be used to obtain the value for a specific bean property. d. The value to assign to a bean property. The value typically is the result of a JSP expression.

c

QN=24 (9467) Which of the following are valid iteration mechanisms in jsp? a. <% int i = 0; while(i<5) { "Hello World" i++; } %> b. <jsp:for loop='5'> "Hello World" </jsp:for> c. <% int i = 0; for(;i<5; i++) { %> "Hello World"; <% i++; } %>

a

QN=24 Which is NOT associated with the business tier in a JEE (J2EE) web-based application? a. JSP b. Entity Beans c. Stateless Session Beans

e

QN=25 (10177) Which is NOT a scope of implicit objects of JSP file? a. application b. page c. request d. session e. response

b

QN=25 (7291) Assume that you need to write a JSP page that adds numbers from one to ten, and then print the output. <% int sum = 0; for(j = 0; j < 10; j++) { %> // XXX --- Add j to sum <% } %> // YYY --- Display the sum Which statement when placed at the location XXX can be used to compute the sum? a. <% sum = sum + j %> b. <% sum = sum + j; %> c. <%= sum = sum + j %> d. <%= sum = sum + j; %>

d

QN=25 Which is NOT responsibility of the business tier in a multitier web-based application with web, business, and EIS tiers? a. To provided business logic b. To participate in transactions c. To integrate with the legacy applications d. To generate dynamic content

a

QN=25 Which statement is NOT true about JMS? a. JMS does NOT depend on MOM (Messaging-Oriented Middleware) products b. JSM support an event oriented approach to message reception. c. JMS support both synchronous and asynchronous message passing d. JMS provides common way for Java programs to access an enterprise messaging system's message

Implementing an interface

Syntax for: implements Interface_Name, Another_Interface_Name...etc

a

QN=26 (10163) Which statements are BEST describe id attribute of <jsp:useBean id=..... /> Action? a. The name used to manipulate the Java object with actions <jsp:setProperty> and <jsp:getProperty>. A variable of this name is also declared for use in JSP scripting elements. The name specified here is case sensitive. b. The scope in which the Java object is accessible—page, request, session or application. The default scope is page. c. The fully qualified class name of the Java object. d. The name of a bean that can be used with method instantiate of class java.beans.Beans to load a JavaBean into memory. e. The type of the JavaBean. This can be the same type as the class attribute, a superclass of that type or an interface implemented by that type. The default value is the same as for attribute class. A ClassCastException occurs if the Java object is not of the type specified with attribute type.

a

QN=26 (10175) Action _______has the ability to match request parameters to properties of the same name in a bean by specifying "*" for attribute property. a. <jsp:setProperty> b. <jsp:getProperty> c. <jsp:useBean> d. <jsp:include>

d

QN=26 A Java programmer wants to develop a browser-based multitier application for a large bank. Which Java edition (or editions) should be used to develop this system? a. Only J2SE b. Only J2EE c. Only J2ME d. J2SE and J2EE e. J2SE and J2ME

b

QN=26 Which is disadvantage of using JEE ( or J2EE) server-side technologies in a web-based application? a. Scalability b. Complexity c. Maintainability d. Support for many different clients

b

QN=26 Which is true about RMI? a. RMI is used to create thin web client b. RMI allows objects to be send from one computer to another c. RMI is the Java API used for executing queries on a database d. RMI is the transport protocol used by web servers and browsers

b

QN=27 (10158) Which statements are BEST describe <jsp:include> Action? a. Specifies the relative URI path of the resource to include. The resource must be part of the same Web application. b. Dynamically includes another resource in a JSP. As the JSP executes, the referenced resource is included and processed. c. Forwards request processing to another JSP, servlet or static page. This action terminates the current JSP's execution. d. Specifies that the JSP uses a JavaBean instance. This action specifies the scope of the bean and assigns it an ID that scripting components can use to manipulate the bean.

a

QN=27 (9473) Consider the following java code: //in file Book.java package com.bookstore; public class Book { private long isbn; public Book(){ isbn = 0; } public long getIsbn(){ return isbn; } public void setIsbn(long value){ this.isbn = value; } } Code for browse.jsp: <jsp:useBean class="com.bookstore.Book" id="newbook" /> LINE 1 : <jsp:setProperty name="newbook" property="isbn" value="1000"/> Which of the following statements are correct? a. The isbn property of newbook will be set to 1000. b. It will throw an exception at request time because "1000" is a string and isbn is a long. c. It will not compile. d. The isbn property of newbook will be set to 1000 if&nbsp;&nbsp;'value' attribute of 'setProperty' tag is given as: value=1000

d

QN=27 A Java developer needs to be able to send email, containing XML attachments, using SMTP. Which JEE (J2EE) technology provides this capability? a. JSP b. EJB c. Servlet d. JavaMail

b

QN=27 Which is true about JDBC? a. All JDBC drivers are pure Java. b. The JDBC API is included in J2SE c. The JDBC API is an extension of the ODBC API d. JDBC is used to connect to MOM (Message-Oriented Middleware Product)

a

QN=28 (7251) Which of the following is a valid standard action that can be used by a jsp page to import content generated by another JSP file named another.jsp? a. <jsp:include page='another.jsp'/> b. <jsp:import page='another.jsp'/> c. <jsp:include file='another.jsp'/> d. <jsp:import file='another.jsp'/>

b

QN=28 (9472) Which of the following defines the class name of a tag in a TLD? a. tag-class-name b. tag-class c. class-name d. class

a

QN=28 Which statement is true about EJB 3.0 containers? a. javax.naming.initialContext is guaranteed to provide a JNDI name space b. Java Telephony API is guaranteed to be available for session and message beans c. The Java 2D API is guaranteed to be available for session beans

b

QN=28 Which technology is used for processing HTTP requests and mapping those requests to business objects a. EJB b. JMS c. MOM (Message-Oriented Middleware Product) d. Servlets

d

QN=28 Which technology is used for processing HTTP requests and mapping those requests to business objects a. EJB b. JMS c. MOM (Message-Oriented Middleware Product) d. Servlets

b

QN=29 (10173) Which statements are BEST describe isErrorPage attribute of <%@ page isErrorPage=....%> directive? a. Any exceptions in the current page that are not caught are sent to the error page for processing. The error page implicit object exception references the original exception. b. Specifies if the current page is an error page that will be invoked in response to an error on another page. If the attribute value is true, the implicit object exception is created and references the original exception that occurred. c. Specifies the MIME type of the data in the response to the client. The default type is text/html. d. Specifies the class from which the translated JSP will be inherited. This attribute must be a fully qualified package and class name.

a

QN=29 (9446) Which HTTP method is used in FORM based Authentication? a. POST b. GET c. FORM d. HEAD

c

QN=29 EJB 3.0 specifications are first implemented in ________ a. Java EE 3 b. Java EE 4 c. Java EE 5 d. Java EE 6

b

QN=29 Which Java technology provides a standard API for publish-subscribe messaging model? a. JSP b. JMS c. JNDI d. UDDI

a

QN=3 (10116) You have to send a gif image to the client as a response to a request. Which of the following calls will you have to make? (Choose one) a. response.setContentType("image/gif"); b. response.setType("application/gif"); c. response.setContentType("application/bin"); d. response.setType("image/gif");

b

QN=3 (10123) Given that a servlet has been mapped to /account/*. Identity the HttpServletRequest methods that will return the /account segement for the URI: /myapp/account/*. a. getContextPath b. getServletPath c. getPathInfo

a

QN=30 (7182) Review the following scenario; then identify which security mechanisms would be important to fulfill the requirement. (Choose one.) An online magazine company wishes to protect part of its website content, to make that part available only to users who pay a monthly subscription. The company wants to keep client, network, and server processing overheads down: Theft of content is unlikely to be an issue, as is abuse of user IDs and passwords through network snooping. a. Authorization and Authentication b. Indication c. Client certification d. Data integrity e. Confidentiality

a

QN=30 (7244) Which of the following techniques would correctly put a bean into application scope? (You can assume that any necessary page directives are present and correct elsewhere in the JSP page.) (Choose one.) a. <jsp:useBean id="app1" class="webcert.ch07.examp0701.AddressBean" scope="application" /> b. <% AddressBean ab5 = new AddressBean(); pageContext.setAttribute("app5", ab5); %> c. <jsp:useBean name="app6" class="webcert.ch07.examp0701.AddressBean" scope="application" />

d

QN=30 Which is NOT associated with the web tier in a JEE (J2EE) web-based application? a. HTML b. JSP c. JavaBeans d. Message-driven beans

a

QN=30 Which is NOT belonging to basic three types of EJB? a. Transfer object b. Session bean c. Message-driven bean d. Entity bean

b

QN=31 (10184) Which statements are BEST describe prefix attribute of <%@ taglib prefix=...%>directive of JSP file? a. Specifies the relative or absolute URI of the tag library descriptor. b. Specifies the required prefix that distinguishes custom tags from built-in tags. The prefix names jsp, jspx, java, javax, servlet, sun and sunw are reserved. c. Allows programmers to include their own new tags in the form of tag libraries. These libraries can be used to encapsulate functionality and simplify the coding of a JSP. d. The scripting language used in the JSP. Currently, the only valid value for this attribute is java.

b

QN=31 (7185) Which security mechanism proves that data has not been tampered with during its transit through the network? a. Data validation b. Data integrity c. Authentication d. Packet sniffing e. Data privacy f. Authorization

a

QN=31 Which act as a proxy to an EJB? a. Remote instance b. Home instance c. Bean instance

b

QN=31 Which statement describe about JMS is NOT true? a. JMS supports Publish/Subcribe b. JMS enhances access to email services c. JMS use JNDI to locate the destination

a

QN=32 (9444) In which of the following Authentication mechanism, the browser transmits the username and password to the server without any encryption? (Choose one) a. HTTP BASIC Authentication b. HTTP DIGEST Authentication c. CLIENT-CERT Authentication

e

QN=32 (9487) Identify the correct element is required for a valid <taglib> tag in web.xml (Choose one) a. <uri> b. <tag-uri> c. <uri-name> d. <uri-location> e. <taglib-uri>

d

QN=32 A developer wants to create a Java Persistence query that returns valid US phone numbers (formatted as 123-456-7890) from a collection of differently formatted international phone numbers. The developer needs only those numbers that begin with 303. Which WHERE clause is correct? a. WHERE addr.phone LIKE '303_' b. WHERE addr.phone LIKE '303%' c. WHERE addr.phone LIKE '303-%-%' d. WHERE addr.phone LIKE '303-___-____'

b

QN=32 Which statement describe about Message-Driven Beans is correct? (Choose one) a. Message-Driven Beans are stateful b. An EJB 3.0 message-driven beans can itself be the client of another message-driven beans c. The bean mediates between the client and the other components of the application, presenting a simplified view to the client.

a

QN=32 Which statement is true about management of an EJB's resources? a. The reference to home object is obtained through JNDI to improve maintainability and flexibility. b. The reference to the remote object is obtained through JNDI to improve maintainability and flexibility.

a

QN=33 (11421) Which is NOT belonging to basic three types of EJB? a. Transfer object b. Session bean c. Message-driven bean d. Entity bean

a

QN=33 (7305) Which of the elements defined within the taglib element of taglib descriptor file are required? Select one correct answer. a. taglib-location b. info c. taguri d. display-name

c

QN=33 Which is NOT true about stateless session beans? a. They are CANNOT hold client state b. They are used to implement business logic c. They are used to represent data stored in a RDBMS d. They are an Enterprises Beans

a

QN=33 Which statement is correct about Java EE client of a message-driven beans? a. The client can use JNDI to obtain a reference to a message destination b. The client can use JNDI to obtain a reference to a dependency injection c. The client can use JNDI to obtain a reference to a message-driven bean instance

c

QN=33 Which type of JEE (or J2EE) component is used to store business data persistently? a. Java Server Pages b. Java Beans c. Entity Bean d. Stateful session beans e. Stateles session beans

c

QN=34 (11420) EJB 3.0 specifications are first implemented in ________ a. Java EE 3 b. Java EE 4 c. Java EE 5 d. Java EE 6

a

QN=34 (9479) Which of the following methods will be invoked if the doStartTag() method of a tag returns Tag.SKIP_BODY? a. doEndTag() b. skipBody() c. doAfterBody() d. None of these.

c

QN=34 A developer must implement a "shopping cart" object for a web-based application. The shopping cart must be able to maintain the state of the cart, but the state is not stored persistently. Which JEE (J2EE) technology is suited to this goal? a. JMS b. Entity beans c. Stateful session beans d. Stateless session beans

c

QN=34 Which is a valid PostConstruct method in a message-driven bean class? a. @PostConstruct public boolean init() { return true; } b. @PostConstruct private static void init() {} c. @PostConstruct private void init() {} d. @PostConstruct public static void init() {}

b

QN=34 Which is true about the relationship "A keyboard has 101 keys"? a. This is a one-to-one relationship b. This is a one-to-may relationship c. This is a many-to-many relationship d. This is NOT a composition relationship

c

QN=35 (10182) Which statements are BEST describe taglib directive of JSP file? a. Defines page settings for the JSP container to process b. Causes the JSP container to perform a translation-time insertion of another resource's content. As the JSP is translated into a servlet and compiled, the referenced file replaces the include directive and is translated as if it were originally part of the JSP. c. Allows programmers to include their own new tags in the form of tag libraries. These libraries can be used to encapsulate functionality and simplify the coding of a JSP. d. The scripting language used in the JSP. Currently, the only valid value for this attribute is java.

a

QN=35 (11422) Which act as a proxy to an EJB? a. Remote instance b. Home instance c. Bean instance

a

QN=35 Which statement about JMS is true? a. JMS supports Publish/Subcribe b. JMS enhances access to email services c. JMS uses JMX to create a connectionFactory

a

QN=35 Which statement is true about the EJB 3.0 stateful session beans? a. Its conversational state is retained across method invocations and transactions b. Its conversational state is lost after passivation unless the bean class saves it to a database c. Its conversational state is retained across method invocations but NOT across transaction boundaries

d

QN=36 (10360) A Java developer needs to be able to send email, containing XML attachments, using SMTP. Which JEE (J2EE) technology provides this capability? a. JSP b. EJB c. Servlet d. JavaMail

a

QN=36 (11423) Which statement is true about management of an EJB's resources? a. The reference to home object is obtained through JNDI to improve maintainability and flexibility. b. The reference to the remote object is obtained through JNDI to improve maintainability and flexibility.

b

QN=36 Which is NOT provided by the EJB tier in a multitier JEE (J2EE) application? a. Security b. XML Parsing c. Concurrency control d. Transaction management

a

QN=36 Which is the CORRECT statement about JMS? a. JMS uses JNDI to find destination b. JMS enhances access to email services c. JMS uses JMX to create a connectionFactory

a

QN=36 Which statement is true about EJB 3.0 stateful session beans and stateless session beans? (Choose one) a. Both can have multiple remote and local business interfaces b. Only the stateful session bean class is required to implement java.io.Serializable interface c. Both can be passivated by the EJB container to preserve resource d Only the stateless session bean class is required to implement java.io.Serializable interface

c

QN=37 (10353) Which is true about JEE ( or J2EE)? a. JEE applications depend on web servers b. JEE runs on consumer and embedded devices c. JEE includes servlet APIs and EJB APIs d. JEE can be run only on tomcat web servers

c

QN=37 (11418) A developer is working on a project that includes both EJB 2.1 and EJB 3.0 session beans. A lot of business logic has been implemented and tested in these EJB 2.1 session beans. Some EJB 3.0 session beans need to access this business logic. Which design approach can achieve this requirement? a. Add adapted home interfaces to EJB 3.0 session beans to make EJB 3.0 and EJB 2.1 session beans interoperable. b. Add EJB 3.0 business interfaces to existing EJB 2.1 session beans and inject references to these business interfaces into EJB 3.0 session beans. c. No need to modify existing EJB 2.1 session beans. Use the @EJB annotation to inject a reference to the EJB 2.1 home interface into the EJB 3.0 bean class.

b

QN=37 A stateful session bean must commit a transaction before a business method a. True b. False

c

QN=37 Which is NOT represented in a UML class diagram? a. Operations of classed and interfaces b. Relationships between classes and interfaces c. The interaction between objects in sequential order

a

QN=38 (10356) Which is NOT associated with the business tier in a JEE (J2EE) web-based application? a. JSP b. Entity Beans c. Stateless Session Beans

a

QN=38 (11416) What is the implementation specification of EJB 3 session bean classes? a. a session bean class must be marked with @Stateless or @Stateful b. a session bean class must be final or abstract c. a session bean class can't extend other classes

c

QN=38 Which is NOT a correct statement about entity beans? a. They are used to store persistent data b. They are used to share data among clients c. They are used to implement business processes d. They are used to represent data stored in a RDBMS

a

QN=38 Which statement is true about both stateful and stateless session beans about bean instances? a. Bean instances are NOT require to survive container crashes b. Bean instances are require to survive container crashes c. A bean with bean-managed transactions must commit or rollback any transaction before returning from a business method

b

QN=39 (10359) Which is disadvantage of using JEE (or J2EE) server-side technologies in a web-based application? a. Scalability b. Complexity c. Maintainability d. Support for many different clients

c

QN=39 (11415) What do you need to create a EJB3 session bean? a. Annotate the session bean with @Session b. Annotate the session bean with @SessionBean c. Annotate the session bean with @Stateful or @Stateless

c

QN=39 The requirement for an online shopping application are: It must support millions of customers. The invocations must be transactional. The shopping cart must be persistent. Which technology is required to support these requirements? a. JNI b. JMS c. EJB d. JMX

c

QN=39 What do you need to create a EJB3 session bean? a. Annotate the session bean with @Session b. Annotate the session bean with @SessionBean c. Annotate the session bean with @Stateful or @Stateless

a

QN=4 (10093) To read the cookies that come back from the client, you call getCookies on the HttpServletRequest. a. True b. False

a

QN=43 Given a stateless session bean with container-managed transaction demarcation, from which method can a developer access another enterprise bean? a. business method from the business interface b. bean constructor c. PreDestroy lifecycle callback method

a

QN=4 (10119) Which method of ReportGeneratorServlet will be called when the user clicks on the URL shown by the following HTML. Assume that ReportGeneratorServlet does not override the service(HttpServletRequest, HttpServletResponse) method of the HttpServlet class. (Choose one) a. doGet(HttpServletRequest, HttpServletResponse); b. doPost(HttpServletRequest, HttpServletResponse); c. doHead(HttpServletRequest, HttpServletResponse); d. doOption(HttpServletRequest, HttpServletResponse);

a

QN=40 (10367) Which statement is true about both stateful and stateless session beans about bean instances? a. Bean instances are NOT require to survive container crashes b. Bean instances are require to survive container crashes c. A bean with bean-managed transactions must commit or rollback any transaction before returning from a business method

d

QN=40 (11417) A developer is working on a user registration application using EJB 3.0. A business method registerUser in stateless session bean RegistrationBean performs the user registration. The registerUser method executes in a transaction context started by the client. If some invalid user data causes the registration to fail, the client invokes registerUser again with corrected data using the same transaction. Which design can meet this requirement? a. Have registerUser method call EJBContext.setRollbackOnly() method after registration fails. b. Have registerUser method throw javax.ejb.EJBTransactionRequiredException after registration fails. c. Have registerUser method throw EJBException without marking the transaction for rollback, after registration fails. d. Create an application exception with the rollback attribute set to false and have registerUser method throw it after registration fails.

a

QN=40 What is the implementation specification of EJB 3 session bean classes? a. a session bean class must be marked with @Stateless or @Stateful b. a session bean class must be final or abstract c. a session bean class can't extend other classes

b

QN=40 Which statement is correct about the Java Persistence API support for the SQL queries? a. SQL queries are NOT allowed to use parameters. b. The result of a SQL query is not limited to entities c. Only SELECT SQL queries are required to be supported d. SQL queries are expected to be portable across database

c

QN=41 (10362) Which is NOT true about stateless session beans? a. They are CANNOT hold client state b. They are used to implement business logic c. They are used to represent data stored in a RDBMS d. They are an Enterprises Beans

a

QN=41 (11412) Which statement about entity manager is true? a. A container-managed entity manager must be a JTA entity manager. b. An entity manager injected into session beans can use either JTA or resource-local transaction control. c. An entity manager created by calling the EntityManagerFactory.createEntityManager method always uses JTA transaction control.

d

QN=41 A developer is working on a user registration application using EJB 3.0. A business method registerUser in stateless session bean RegistrationBean performs the user registration. The registerUser method executes in a transaction context started by the client. If some invalid user data causes the registration to fail, the client invokes registerUser again with corrected data using the same transaction. Which design can meet this requirement? a. Have registerUser method call EJBContext.setRollbackOnly() method after registration fails. b. Have registerUser method throw javax.ejb.EJBTransactionRequiredException after registration fails. c. Have registerUser method throw EJBException without marking the transaction for rollback, after registration fails. d. Create an application exception with the rollback attribute set to false and have registerUser method throw it after registration fails.

c

QN=41 Which statement is true about the use of a persist operation in a transaction of an Entity Beans a. If a user persists a detached object it always becomes managed b. The persist operation on an entity always cascades to its related entities c. If a user persists a new entity with an existing primary key the transaction will fail d. If a user persists a managed entity an exception may be thrown by the persist operation

a

QN=42 (10365) Which statement is true about EJB 3.0 stateful session beans and stateless session beans? (Choose one) a. Both can have multiple remote and local business interfaces b. Only the stateful session bean class is required to implement java.io.Serializable interface c. Both can be passivated by the EJB container to preserve resource d. Only the stateless session bean class is required to implement java.io.Serializable interface

e

QN=42 (11409) Which is NOT a state in the EJB 3 Entity beans life cycle states? a. New b. Managed c. Detached d. Removed e. Exit

c

QN=42 A developer is working on a project that includes both EJB 2.1 and EJB 3.0 session beans. A lot of business logic has been implemented and tested in these EJB 2.1 session beans. Some EJB 3.0 session beans need to access this business logic. Which design approach can achieve this requirement? a. Add adapted home interfaces to EJB 3.0 session beans to make EJB 3.0 and EJB 2.1 session beans interoperable. b. Add EJB 3.0 business interfaces to existing EJB 2.1 session beans and inject references to these business interfaces into EJB 3.0 session beans. c. No need to modify existing EJB 2.1 session beans. Use the @EJB annotation to inject a reference to the EJB 2.1 home interface into the EJB 3.0 bean class.

d

QN=42 A developer wants to use the Java Persistence query language. Which statement is true? a. A WHERE clause is required in every query b. The WHERE clause can be used to order the results returned by the query. c. The WHERE clause is used to determine the types of objects to be retrieved from persistent store d. The WHERE clause is used to restrict the contents of a collection of objects that are returned from a query.

c

QN=43 (10373) Which is NOT a correct statement about entity beans? a. They are used to store persistent data b. They are used to share data among clients c. They are used to implement business processes d. They are used to represent data stored in a RDBMS

d

QN=43 (11411) Which statement about an entity instance lifecycle is correct? a. A new entity instance is an instance with a fully populated state. b. A detached entity instance is an instance with no persistent identity. c. A removed entity instance is NOT associated with a persistence context. d. A managed entity instance is the instance associated with a persistence context.

a

QN=43 The Java Persistent API defines the Query interface. Which statement is true about the Query.executeUpdate method ? a. It must always be executed within a transaction b. It throws a PersistenceException if no entities were updated. c. All managed entity objects corresponding to database rows affected by the update will have their state changed to correspond with the update

c

QN=44 (10372) Which is NOT represented in a UML class diagram? a. Operations of classed and interfaces b. Relationships between classes and interfaces c. The interaction between objects in sequential order

a

QN=44 (11410) Which class type must be implicitly or explicitly denoted in the persistence.xml descriptor as managed persistence classes to be included within a persistence unit? a. Entity classes b. Entity listener classes c. Interceptor classes

b

QN=44 Which component can use a container-managed entity manager with an extended persistent context? a. Any EJB component b. Only stateful session beans c. Only stateless session beans d. Session beans and web components

b

QN=45 (10382) Can we use the annotation @PrePassivate for more than one method in a Entity bean? a. Yes b. No

a

QN=45 (11414) A developer wants to achieve the following two behaviors for an EJB 3.0 session bean: (1) If the client calls a business method with a transaction context, the container will invoke the enterprise bean's method in the client's transaction context. (2) If the client calls a business method without a transaction context, the container will throw the javax.ejb.EJBTransactionRequiredException. Which transaction attribute should be used? a. MANDATORY b. SUPPORTS c. NOT_SUPPORTED

b

QN=45 Which of the following lines of code are correct? a. @EntityBean public class Employees{ ... } b. @Entity public class Employees{ ... } c. class Employees{ @Entity private class Address{ ... } ... }

c

QN=46 (10376) Which statement is true about the use of a persist operation in a transaction of an Entity Beans a. If a user persists a detached object it always becomes managed b. The persist operation on an entity always cascades to its related entities c. If a user persists a new entity with an existing primary key the transaction will fail d. If a user persists a managed entity an exception may be thrown by the persist operation

a

QN=46 (11413) Which option can be used to predefine Java Persistence queries for easy use? a. @NamedQuery annotation b. @NamedNativeQuery annotation c. using the named-native-query element in the XML descriptor

b

QN=46 If you want to send an entity object as the pass by value through a remote interface, which of the following statements are valid? (Choose one) a. @Entity public class Employees implements SessionSynchronization{ ... } b. @Entity public class Employees implements Serializable{ ... } c. public class Employees implements Serializable{ ... } d. @entity public class Employees implements Serializable{ ... }

b

QN=47 (10383) What should be the return type of the method using @PrePassivate? a. Object b. void c. String d. boolean

b

QN=47 (10389) Which Java technology provides a standard API for publish-subscribe messaging model? a. JSP b. JMS c. JNDI d. UDDI

b

QN=47 Can we use the annotation @PrePassivate for more than one method in a Entity bean? a. Yes b. No

d

QN=48 (10390) Which is NOT associated with the web tier in a JEE (J2EE) web-based application? a. HTML b. JSP c. JavaBeans d. Message-driven beans

c

QN=48 (11406) Which is a valid PostConstruct method in a message-driven bean class? a. @PostConstruct public boolean init() { return true; } b. @PostConstruct private static void init() {} c. @PostConstruct private void init() {} d. @PostConstruct public static void init() {}

b

QN=48 What should be the return type of the method using @PrePassivate? a. Object b. void c. String d. boolean

b

QN=49 (10387) Which is true about JDBC? a. All JDBC drivers are pure Java. b. The JDBC API is included in J2SE c. The JDBC API is an extension of the ODBC API d. JDBC is used to connect to MOM (Message-Oriented Middleware Product)

a

QN=49 (11408) Which is the CORRECT statement about JMS? a. JMS uses JNDI to find destination b. JMS enhances access to email services c. JMS uses JMX to create a connectionFactory

d

QN=49 Which of the following lines of code are correct? (Choose one) a. @Entity public class Company{ ... } public class Employee extends Company{ ... } b. @Entity public class Company{ ... } @Entity public class Employee extends Company{ ... } c. public class Company{ ... } @Entity public class Employee extends Company{ ... } d. All of others

a

QN=5 (10088) Which of the following methods can be used to add cookies to a servlet response? a. HttpServletResponse.addCookie(Cookie cookie) b. ServletResponse.addCookie(Cookie cookie) c. HttpServletResponse.addCookie(String contents) d. ServletResponse.addCookie(String contents) e. ServletResponse.addHeader(String name, String value)

b

QN=5 (10099) To send binary outptut in a response, the following method of HttpServletResponse may be used to get the appropriate Writer/Stream object. a. getStream b. getOutputStream c. getBinaryStream d. getWriter

b

QN=50 (10391) Which statement describe about JMS is NOT true? a. JMS supports Publish/Subcribe b. JMS enhances access to email services c. JMS use JNDI to locate the destination

a

QN=50 (11407) Which statement about JMS is true? a. JMS supports Publish/Subcribe b. JMS enhances access to email services c. JMS uses JMX to create a connectionFactory

e

QN=50 Which is NOT a state in the EJB 3 Entity beans life cycle states? a. New b. Managed c. Detached d. Removed e. Exit

a

QN=51 Which class type must be implicitly or explicitly denoted in the persistence.xml descriptor as managed persistence classes to be included within a persistence unit? a. Entity classes b. Entity listener classes c. Interceptor classes

path name

String variable or literal String that represents path to file

d

QN=52 Which statement about an entity instance lifecycle is correct? a. A new entity instance is an instance with a fully populated state. b. A detached entity instance is an instance with no persistent identity. c. A removed entity instance is NOT associated with a persistence context. d. A managed entity instance is the instance associated with a persistence context.

a

QN=52 Which statement about entity manager is true? a. A container-managed entity manager must be a JTA entity manager. b. An entity manager injected into session beans can use either JTA or resource-local transaction control. c. An entity manager created by calling the EntityManagerFactory.createEntityManager method always uses JTA transaction control.

a

QN=53 Which option can be used to predefine Java Persistence queries for easy use? a. @NamedQuery annotation b. @NamedNativeQuery annotation c. using the named-native-query element in the XML descriptor

a

QN=54 A developer wants to achieve the following two behaviors for an EJB 3.0 session bean: (1) If the client calls a business method with a transaction context, the container will invoke the enterprise bean's method in the client's transaction context. (2) If the client calls a business method without a transaction context, the container will throw the javax.ejb.EJBTransactionRequiredException. Which transaction attribute should be used? a. MANDATORY b. SUPPORTS c. NOT_SUPPORTED

a

QN=6 (10137) The HttpSession method getAttribute returns the object associated with a particular name. a. True b. False

a

QN=6 (7142) _________________ provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. a. Session management b. Cookie c. Hidden Field d. URL Rewrite

a

QN=7 (10141) GET requests and POST requests can both be used to send form data to a web server. a. True b. False

a

QN=7 (7158) The same servlet class can be declared using different logical names in the deployment descriptor. a. True b. False

a

QN=8 (7143) See the extract from web.xml of web application "mywebapp" on server named myserver, runs on port 8080: <servlet-mapping> <servlet-name>ServletA</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ServletB</servlet-name> <url-pattern>/bservlet.html</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ServletC</servlet-name> <url-pattern>*.servletC</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ServletD</servlet-name> <url-pattern>/dservlet/*</url-pattern> </servlet-mapping> Given that a user enters the following into her browser, which (if any) of the mapped servlets will execute? (Choose one.) http://myserver:8080/mywebapp/Bservlet.html a. ServletA b. ServletB c. ServletC d. ServletD

a

QN=8 (7149) Study the statements: 1) The context path contains a special directory called WEB-INF, which contains the deployment descriptor file, web.xml. 2) A client application may directly access resources in WEB-INF or its subdirectories through HTTP. a. Only statement 1 is true b. Only statement 2 is true c. Both 1 and 2 are true d. Both 1 and 2 are not true

c

QN=9 (7138) Given the following deployment descriptor: <web-app> <servlet> <servlet-name>InitParams</servlet-name> <servlet-class>com.osborne.c02.InitParamsServlet</servlet-class> <init-param> <param-name>initParm</param-name> <param-value>Final Test</param-value> </init-param> </servlet> </web-app> What is the outcome of running the following servlet? public class InitParamsServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext sc = this.getServletContext(); PrintWriter out = response.getWriter(); out.write("Initialization Parameter is: " + sc.getInitParameter("initParm")); } } a. A runtime error b. "Initialization Parameter is: Final Test" returned to the requester c. "Initialization Parameter is: null" returned to the requester d. "Initialization Parameter is: null" written to the console

b

QN=9 (9437) How can you ensure the continuity of the session while using HttpServletResponse.sendRedirect() method when cookies are not supported by the client? a. By using hidden parameters. b. By enconding the redirect path with HttpServletResponse.encodeRedirectURL() method. c. By using HttpServletRequest.encodeURL() method.

___ occur(s) if the effect of multiple threads on shared data depends on the order in which the threads are scheduled.

Race conditions

___ access allows file access at arbitrary locations, without first reading the bytes preceding the access location.

Random

Which of the following operations is least efficient in a LinkedList?

Random access of an element

Use a ___ object to access a file and move a file pointer.

RandomAccessFile

Return value

Specified data type method will return

Prototype

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Hashmap

Stores Keys and associated values

Variable

Stores a value

ArrayList

Stores list of data

Which statement creates an infinite stream of even numbers?

Stream<Integer> evens = Stream.iterate(2, n -> n + 2);

Which statement creates a stream from an explicit specification of integers?

Stream<Integer> myStream = Stream.of(0, 1, 1, 2, 3, 5, 8, 13, 21, 34);

Which statement creates a stream from an explicit specification of words?

Stream<String> words = Stream.of("The","quick","brown","fox","jumped","over","the","lazy","dog");

What statement will return the value of a given key from the configuration file? Assume props is of type Properties.

String driver = props.getProperty("jdbc.driver");

FileWriter(String, boolean)

String is File name, boolean value sets to true so if file exists, program should add output to file

What is the difference between the String and StringBuffer classes?

String objects are constants. StringBuffer objects are not constants.

Answer the question below about the following initialized array: String[]pizzaToppings = new String[10]; Rewrite this statement to initially be assigned the following four toppings only: extra cheese, black olives, mushrooms, and bacon.

String[] pizzaToppings = { "extra cheese", "black olives", mushrooms, "bacon" };

Which statement creates an array from a stream of Student objects, given by the variable studentStream?

Student[] students = studentStream.toArray(Student[]::new);

a

Study the statements: <question>1) The context path contains a special directory called WEB-INF, which contains the deployment descriptor file, web.xml. <question>2) A client application may directly access resources in WEB-INF or its subdirectories through HTTP. a. Only statement 1 is true b. Only statement 2 is true c. Both 1 and 2 are true d. Both 1 and 2 are not true

A. list.add(5.5); // 5.5 is automatically converted to new Double(5.5) B. list.add(3.0); // 3.0 is automatically converted to new Double(3.0) C. Double doubleObject = list.get(0); // No casting is needed D. double d = list.get(1); // Automatically converted to double

Suppose ArrayList<Double>list = new ArrayList<>(). Which of the following statements are correct?

A. list.add("Red"); B. list.add(new Integer(100)); C. list.add(new java.util.Date()); D. list.add(new ArrayList());

Suppose List list = new ArrayList(). The following operations are correct.

list.add("Red");

Suppose List<String> list = new ArrayList<>(). Which of the following operations are correct?

return new int[]{1, 2, 3};

Suppose a method p has the following heading: public static int[] p() What return statement may be used in p()?

A. i B. (int)(Math.random() * 100)) C. i + 10

Suppose int i = 5, which of the following can be used as an index for array double[] t = new double[100]?

System.out.println(GenericStack.getNumberOfObjects());

Suppose you add the following code in the GenericStack class in Listing 21.3. private static int numberOfObjects = 0; public GenericStack() { numberOfObjects++; } public static int getNumberOfObjects() { return numberOfObjects; } Which of the following statements can be inserted into line 5 of Listing 21.9?

After the last statement is executed, line contains characters ' ', '7', '8', '9'.

Suppose you enter 34.3 57.8 789, then press the ENTER key. Analyze the following code. Scanner input = new Scanner(System.in); double v1 = input.nextDouble(); double v2 = input.nextDouble(); String line = input.nextLine();

The program has a runtime error because 34.3 is not an integer.

Suppose you enter 34.3 57.8 789, then press the ENTER key. Analyze the following code. Scanner input = new Scanner(System.in); int v1 = input.nextInt(); int v2 = input.nextInt(); String line = input.nextLine();

A. After line 2 is executed, v1 is 34.3. B. After line 3 is executed, v2 is 57.8. C. After line 4 is executed, line contains an empty string.

Suppose you enter 34.3, the ENTER key, 57.8, the ENTER key, abc, the Enter key. Analyze the following code. 1 Scanner input = new Scanner(System.in); 2 double v1 = input.nextDouble(); 3 double v2 = input.nextDouble(); 4 String line = input.nextLine();

A. After line 2 is executed, v1 is 34.3. B. After line 3 is executed, v2 is 57.8. C. After line 4 is executed, line contains an empty string.

Suppose you enter 34.3, the ENTER key, 57.8, the ENTER key. Analyze the following code. 1 Scanner input = new Scanner(System.in); 2 double v1 = input.nextDouble(); 3 double v2 = input.nextDouble(); 4 String line = input.nextLine();

What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Interface

Syntax for beginning a(n)__________; public interface Interface_Name { Public_Named_Constant_Definitions .... Public_Method_Heading_1; ... Public_Method_Heading_n; }

Name three widgets mentioned in chapter 1, "Meet the Android".

TextView, Button, and CheckBox

Which Java operator is right associative?

The = operator is right associative.

How is it possible for two String objects with identical values not to be equal under the == operator?

The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

What is the Collection interface?

The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.

What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of objects.

What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs.

What is the difference between the File and RandomAccessFile classes?

The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

What is the purpose of the File class?

The File class is used to create objects that provide access to the files and directories of a local file system.

What is the GregorianCalendar class?

The GregorianCalendar class provides support for traditional Western calendars.

ENTERED EXITED ACTIVATED

The HyperlinkEvent object encapsulates information identifying the event as being one of the following three types: _____ _____ _____

What is an Iterator interface?

The Iterator interface is used to step through the elements of a Collection.

heap

The JVM stores the array in an area of memory, called _______, which is used for dynamic memory allocation where blocks of memory are allocated and freed in an arbitrary order.

InetAddress

The Java _____ class can be used to find the IP address corresponding to a domain name

InetAddress

The Java _____ class can often be used to find the domain name corresponding to an IP address, and to find the IP address corresponding to a domain name.

What class of exceptions are generated by the Java run-time system?

The Java runtime system generates RuntimeException and Error exceptions.

Which of the following statements about the Java virtual machine is correct?

The Java virtual machine replaces type parameters with their bounds or with type Object.

What is the List interface?

The List interface provides support for ordered collections of objects.

B. An instance of Foo cannot be serialized because Foo contains a non-serializable instance variable v3. C. If you mark v3 as transient, an instance of Foo is serializable.

The Loan class given in the text does not implement java.io.Serializable. Analyze the following code. public class Foo implements java.io.Serializable { private int v1; private static double v2; private Loan v3 = new Loan(); }

What class allows you to read objects directly from a stream?

The ObjectInputStream class supports the reading of objects from input streams.

Serializing an Object

The ObjectOutputStream class is used -When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.

java.util.Arrays.sort(scores)

The __________ method sorts the array scores of the double[] type.

What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

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

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

What is the Set interface?

The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

TCP UDP

The Socket and DatagramSocket classes represent _____ and _____ communications respectively.

Is "abc" a primitive value?

The String literal "abc" is not a primitive value. It is a String object.

getURL

The URL to be displayed is obtained by calling the _____ method on the incoming HyperlinkEvent object.

cannot

The URLConnection class _____ be instantiated directly.

What is the Vector class?

The Vector class provides the capability to implement a growable array of objects

User Datagram Protocol (UDP)

The ____ _____ _____ is often referred to as an unreliable protocol because there is no guarantee that a series of packets will arrive in the right order, or that they will arrive at all.

HTTP SMTP

The ____ protocol defines how web browsers and servers communicate and the ____ protocol defines how some email is transferred

numeric IP address

The _____ _____ _____ is encapsulated into the data packets and used by the internet protocol to route those packets from the source to the destination.

Domain Name System (DNS)

The _____ _____ _____ was developed to translate between IP addresses and domain names.

Transmission Control Protocol TCP

The _____ ______ ______ was added to IP to give each end of a connection the ability to acknowledge receipt of IP packets and to request retransmission of corrupted or lost packets. Also ____ makes it possible to put the packets back together at the destination in the same order that they were sent. (one answer for both)

URLConnection

The _____ class is an abstract class that can be extended . It has a protected constructor that takes a URL object as a parameter.

HyperlinkListener hyperlinkUpdate HyperlinkEvent

The _____ interface declares only one method and it is named _____. The method receives one incoming parameter of type _____.

getByName

The _____ method of the InetAddress class returns a reference to an InetAddress object representing the host whose domain name is passed as a parameter to the method.

getLocalHost

The _____ method of the InetAddress class returns a reference to an InetAddress object representing the local host computer.

URLEncoder

The ______ class is provided to help deal with problems arising from spaces, special characters, non-alphanumeric characters, etc. , that some operating systems may allow in file names but which may not be allowed in a URL.

instanceof

The _______ operator can be used to check whether an object is of a particular type. Object ______ Class_Name

try/catch block

The ________ tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException.

D. System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

The __________ method copies the sourceArray to the targetArray.

What is the meaning of the type parameter E, in the LinkedList<E> code fragment?

The elements of the linked list are any type supplied to the constructor.

How are case statements written for a switch when using enums?

The enum type doesn't need to be used, since Java knows you are switching on an enum and the only matches can be enum values within the same enum type, you just type the name of the enum value: Season s = Season.SUMMER switch (s) { case SUMMER: case WINTER: default: break; }

Consider the following code fragment: public String checkCity() { zone = getTimeZone(city); if (zone == null) { return "error"; } return "next"; } What is the result of executing the following JSF statement if zone is null? <h:commandButton value="Submit" action="#{timeZoneBean.checkCity}"/>

The error.html page is displayed.

What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?

The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.

What is the purpose of the finally clause of a try-catch-finally statement?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

When is the finally clause of a try-catch-finally statement executed?

The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause.

no exceptions Explanation: At present, Java does not throw integer overflow exceptions. The future version of Java may fix this problem to throw an over flow exception.

The following code causes Java to throw _________. int number = Integer.MAX_VALUE + 1;

g

The following program draws squares recursively. Fill in the missing code. import javax.swing.*; import java.awt.*; public class Test extends JApplet { public Test() { add(new SquarePanel()); } static class SquarePanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); int width = (int)(Math.min(getWidth(), getHeight()) * 0.4); int centerx = getWidth() / 2; int centery = getHeight() / 2; displaySquares(g, width, centerx, centery); } private static void displaySquares(Graphics g, int width, int centerx, int centery) { if (width >= 20) { g.drawRect(centerx - width, centery - width, 2* width, 2 * width); displaySquares(_________, width - 20, centerx, centery); } } } }

a

The following statement is true or false? "If the isThreadSafe attribute of the page directive is true, then the generated servlet implements the SingleThreadModel interface." a. True b. False

The methods in an object are serialized.

The following statements are not true.

A. All files are stored in binary format. So, all files are essentially binary files. B. Text I/O is built upon binary I/O to provide a level of abstraction for character encoding and decoding. C. Encoding and decoding are automatically performed by text I/O. D. For binary input, you need to know exactly how data were written in order to read them in correct type and order.

The following statements are true.

A. ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings. B. Since ObjectInputStream/ObjectOutputStream contains all the functions of DataInputStream/DataOutputStream, you can replace DataInputStream/DataOutputStream completely by ObjectInputStream/ObjectOutputStream. C. To write an object, the object must be serializable. D. The Serializable interface does not contain any methods. So it is a mark interface. E. If all the elements in an array is serializable, the array is serializable too.

The following statements are true.

A. A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing. B. You can use the PrintWriter class for outputting text to a file. C. You can use the Scanner class for reading text from a file. D. An input object is also called an input stream. E. An output object is also called an output stream.

The following statements are true:

A. Text I/O is built upon binary I/O to provide a level of abstraction for character encoding and decoding. B. Text I/O involves encoding and decoding. C. Binary I/O does not require conversions. D. Binary I/O is more efficient than text I/O, because binary I/O does not require encoding and decoding. E. Binary files are independent of the encoding scheme on the host machine and thus are portable.

The following statements are true:

What value does readLine() return when it has reached the end of a file?

The readLine() method returns null when it has reached the end of a file.

danger of malicious programmers

The reason why private instance variables cannot be access in a derived class is because of the _________________ that creates a problem.

A. All methods in FileInputStream/FileOutputStream are inherited from InputStream/OutputStream. B. You can create a FileInputStream/FileOutputStream from a File object or a file name using FileInputStream/FileOutputStream constructors. C. The return value -1 from the read() method signifies the end of file. D. A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file.

The following statements are true?

public boolean equals(classType alias)

The format for equals is:________

public String toString()

The format for toString is: ________-

Type name = new Type();

The format of making a constructor.

collections framework - goals : different types of collections at a high degree of interoperability

The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability.

collections framework - goals : extend and/or adapt easily

The framework had to extend and/or adapt a collection easily.

Reading values into the array

The function of this code: System.out.println("Enter 7 temperatures:"); for (int index = 0;index < 7; index++) temperature[index] = keyboard.nextDouble();

Under what conditions is an object's finalize() method invoked by the garbage collector?

The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable.

What are the high-level thread states?

The high-level thread states are ready, running, waiting, and dead.

collections framework - goals : high-performance

The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hashtables) were to be highly efficient.

What are the legal operands of the instanceof operator?

The left operand is an object reference or null value and the right operand is a class, interface, or array type.

addItem

The method _________ adds a string to end of a list.

D. public static void print(Object[] list) E. public static <E> void print(E[] list)

The method header is left blank in the following code. Fill in the header. public class GenericMethodDemo { public static void main(String[] args ) { Integer[] integers = {1, 2, 3, 4, 5}; String[] strings = {"London", "Paris", "New York", "Austin"}; print(integers); print(strings); } __________________________________________ { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); } }

list1 is 6 5 4 3 2 1

The reverse method is defined in the textbook. What is list1 after executing the following statements? int[] list1 = {1, 2, 3, 4, 5, 6}; list1 = reverse(list1);

list1 is 1 2 3 4 5 6

The reverse method is defined in this section. What is list1 after executing the following statements? int[] list1 = {1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1);

openConnection

The method named _____ can be called on a URL object to get a reference to an object of a class that is a subclass of the URLConnection class.

will not work;overridden

The methods equals and toString inherited form "Object" ______ correctly for almost any class you define and need to be ______ with new definitions

What does a method expression consist of?

The name of a bean and the name of a method.

How does multithreading take place on a computer with a single CPU?

The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

What is one reason to have the DOM parser ignore white space in an XML document?

The parser will otherwise make unneeded nodes of the white space.

What is the preferred size of a component?

The preferred size of a component is the minimum component size that will allow the component to display normally.

Consider the following code snippet: PrintWriter outputFile = new PrintWriter(filename); writeData(outputFile); outputFile.close(); How can the program ensure that the file will be closed if an exception occurs on the writeData call?

The program should place the outputFile.clos() statement within a finally clause of a try block to ensure that the file is closed.

What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system.

What is the purpose of the System class?

The purpose of the System class is to provide access to system resources.

What value does read() return when it has reached the end of a file?

The read() method returns -1 when it has reached the end of a file.

b

The sendRedirect method defined in the HttpServlet class is equivalent to invoking the setStatus method with they following parameter and a Location header in the URL. Select one correct answer. a. SC_OK b. SC_MOVED_TEMPORARILY c. SC_NOT_FOUND d. SC_INTERNAL_SERVER_ERROR e. ESC_BAD_REQUEST

What method is invoked to cause an object to begin executing as a separate thread?

The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.

What must a subclass do to modify a private superclass instance variable?

The subclass must use a public method of the superclass (if it exists) to update the superclass's private instance variable.

TCP UDP

The two socket classes named Socket and DatagramSocket represent _____and _____ communications respectively.

rules to define Generic Methods : actual type arguments

The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as ____________ .

transient

The value of the SSN field was 11122333 when the object was serialized, but because the field is_____ , this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0. (Look for the example on the https://www.tutorialspoint.com/java/java_serialization.htm)

What is the purpose of the wait(), notify(), and notifyAll() methods?

The wait(), notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.

What is casting?

There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

one-to-one many-to-one

There is not necessarily a _____ correspondence between IP addresses and domain names. In fact there can be a _____ correspondence between the two.

collections frameworks - Interfaces

These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.

collections frameworks - Implementations, i.e., Classes

These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.

collections frameworks - Algorithms

These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface.

behavorial design patterns

These design patterns are specifically concerned with communication between objects.

Which of the following is correct about Creational design patterns.

These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new opreator.

Consider the following code snippet: Scanner in = new Scanner(. . .); while (in.hasNextLine()) { String input = in.nextLine(); System.out.println(input); } Which of the following statements about this code is correct?

This code will read in an entire line from the file in each iteration of the loop.

Consider the following code snippet. Scanner inputFile = new Scanner("hoursWorked.txt"); Which of the following statements is correct?

This code will treat the string "hoursWorked.txt" as an input value.

The Collection Interfaces : The Map.Entry

This describes an element (a key/value pair) in a map. This is an inner class of Map. -The entrySet( ) method declared by the Map interface returns a Set containing the map entries. Each of these set elements is a Map.Entry object.

The Collection Interfaces : Collection interface

This enables you to work with groups of objects; it is at the top of the collections hierarchy. -is the foundation upon which the collections framework is built. -declares the core methods that all collections will have.

The Collection Interfaces : The List Interface

This extends Collection and an instance of List stores an ordered collection of elements. -Elements can be inserted or accessed by their position in the list, using a zero-based index. -may contain duplicate elements.

The Collection Interfaces : The Set

This extends Collection to handle sets, which must contain unique elements. -is a Collection that cannot contain duplicate elements. -It models the mathematical set abstraction.

The Collection Interfaces : SortedMap

This extends Map so that the keys are maintained in an ascending order. -It ensures that the entries are maintained in an ascending key order.

The Collection Interfaces :The SortedSet

This extends Set to handle sorted sets. -extends Set and declares the behavior of a set sorted in an ascending order.

A. FileOutputStream B. FileWriter C. RandomAccessFile D. All of the above.

To create a file, you can use __________.

<E extends Number>

To create a generic type bounded by Number, use

ArrayList<Integer> list = new ArrayList<Integer>();

To create a list to store integers, use

openStream();

To create an InputStream to read from a file on a Web server, you use the method __________ in the URL class.

public class A<E> { ... }

To declare a class named A with a generic type, use

public class A<E, F> { ... }

To declare a class named A with two generic types, use

public interface A<E> { ... }

To declare an interface named A with a generic type, use

public interface A<E, F> { ... }

To declare an interface named A with two generic types, use

return type

To have a method return a whole array, you specify the ___________ the same way you specify the type of an array parameter.

first, last

To sort only with the index first, and ending with the index last, you would write Arrays.sort(anArray, _________, __________)

Initializing, int

To step through a list begin by *__________ an _____ variable to the first position on the list

Write a warning message that would display the comment "The maximum credits allowed is 18" with a long interval.

Toast.makeText(MainActivity.this,"The maximum credits allowed is 18", Toast.LENGTH_LONG).show();

When overriding a static method, does the method have to be static as well?

Trick question - a static method is not overriden - but instead hidden. Yes, it must also be static

Most Android phones and tablets automatically rotate the display from portrait to landscape orientation when the user turns the device 90 degrees.

True

The program displays Welcome to Java two times followed by End of the block two times.

What is displayed on the console when running the following program? class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2/i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } System.out.println("End of the block"); } }

The program displays Welcome to Java two times followed by End of the block.

What is displayed on the console when running the following program? class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2/i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } } }

The program displays Welcome to Java and End of the block, and then terminates because of an unhandled exception.

What is displayed on the console when running the following program? class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2/i; System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } System.out.println("End of the block"); } }

The program displays NumberFormatException.

What is displayed on the console when running the following program? class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (NumberFormatException ex) { System.out.println("NumberFormatException"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } } static void method() { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } }

The program displays NumberFormatException followed by RuntimeException.

What is displayed on the console when running the following program? class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } static void method() throws Exception { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (NumberFormatException ex) { System.out.println("NumberFormatException"); throw ex; } catch (RuntimeException ex) { System.out.println("RuntimeException"); } } }

The program displays RuntimeException followed by After the method call.

What is displayed on the console when running the following program? class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } static void method() throws Exception { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } }

D. 1 1 1 1 1 1

What is output of the following code: public class Test { public static void main(String[] args) { int list[] = {1, 2, 3, 4, 5, 6}; for (int i = 1; i < list.length; i++) list[i] = list[i - 1]; for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); } }

a

What is the consequence of attempting to access the following JSP page? <question><html> <question><body> <question><%! <question> public void _jspService(HttpServletRequest request, HttpServletResponse response) { <question> out.write("A"); <question> } <question> %> <question><% out.write("B"); %> <question></body> <question></html> a. Duplicate method compilation error. b. "A" is output to the response. c. "B" is output to the response. d. "A" is output to the response before "B".

indexed variable

What is the correct term for numbers[99]?

D. 1 1 2 3 4 5

What is the output of the following code? int[] myList = {1, 2, 3, 4, 5, 6}; for (int i = myList.length - 2; i >= 0; i--) { myList[i + 1] = myList[i]; } for (int e: myList) System.out.print(e + " ");

1

What is the output of the following code? double[] myList = {1, 5, 5, 5, 5, 1}; double max = myList[0]; int indexOfMax = 0; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) { max = myList[i]; indexOfMax = i; } } System.out.println(indexOfMax);

a[2]

What is the representation of the third element in an array called a?

a

What is the result of attempting to access the following JSP page? <question><html> <question><body> <question><%! public String methodA() { <question> return methodB(); <question>} <question>%> <question><%! public String methodB() { <question> return "JAD Final Test"; <question>} <question>%> <question><h2><%= methodA() %></h2> <question></body> <question></html> a. "JAD Final Test" is output to the resulting web page. b. A translation error occurs. c. A runtime error occurs. d. The web page is blank.

10 Explanation: 4 + 3 + 2 + 1 = 10

What is the return value for xMethod(4) after calling the following method? static int xMethod(int n) { if (n == 1) return 1; else return n + xMethod(n - 1); }

You cannot have a try block without a catch block or a finally block.

What is wrong in the following program? class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); } } }

C. 0 1 2

What will be displayed by the following code? class Test { public static void main(String[] args) { int[] list1 = {1, 2, 3}; int[] list2 = {1, 2, 3}; list2 = list1; list1[0] = 0; list1[1] = 1; list2[2] = 2; for (int i = 0; i < list1.length; i++) System.out.print(list1[i] + " "); } }

C. 0 1 2

What will be displayed by the following code? class Test { public static void main(String[] args) { int[] list1 = {1, 2, 3}; int[] list2 = {1, 2, 3}; list2 = list1; list1[0] = 0; list1[1] = 1; list2[2] = 2; for (int i = 0; i < list2.length; i++) System.out.print(list2[i] + " "); } }

Explanation: new double[]{1, 2, 3} is correct. This is the syntax I have not covered in this edition, but will be covered in the future edition. In this question, double[] x = new double[]{1, 2, 3} is equivalent to double[] x = {1, 2, 3};

What would be the result of attempting to compile and run the following code? public class Test { public static void main(String[] args) { double[] x = new double[]{1, 2, 3}; System.out.println("Value is " + x[1]); } }

overriding; change;overrides; signature;return type

When ______ a method definition, you CANNOT _____ the return type of the method. When one method ______ another, both method must have the same __________ and _______

implements the interface

When a class defines a body for every method specified in an interface. *Not needed to declare every method but can _______ of more than one interface

Final

When a constructor calls a public method, a derived class could override that method. To avoid it declare such methods as _______/

What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

What happens when you invoke a thread's interrupt method while it is sleeping or waiting?

When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.

B. add(GenericStack<? extends T> stack1, GenericStack<T> stack2) C. add(GenericStack<T> stack1, GenericStack<? super T> stack2)

Which of the following can be used to replace YYYYYYYY in the following code? public class WildCardDemo3 { public static void main(String[] args) { GenericStack<String> stack1 = new GenericStack<String>(); GenericStack<Object> stack2 = new GenericStack<Object>(); stack2.push("Java"); stack2.push(2); stack1.push("Sun"); add(stack1, stack2); WildCardDemo2.print(stack2); } public static <T> void YYYYYYYY { while (!stack1.isEmpty()) stack2.push(stack1.pop()); } }

? super T

Which of the following can be used to replace YYYYYYYY in the following code? public class WildCardDemo3 { public static void main(String[] args) { GenericStack<String> stack1 = new GenericStack<String>(); GenericStack<Object> stack2 = new GenericStack<Object>(); stack2.push("Java"); stack2.push(2); stack1.push("Sun"); add(stack1, stack2); WildCardDemo2.print(stack2); } public static <T> void add(GenericStack<T> stack1, GenericStack<YYYYYYYY> stack2) { while (!stack1.isEmpty()) stack2.push(stack1.pop()); } }

D. public static void print(double... numbers) E. public static void print(int n, double... numbers) Explanation: Only one variable-length parameter may be specified in a method and this parameter must be the last parameter. The method return type cannot be a variable-length parameter.

Which of the following declarations are correct?

ArrayList list = new ArrayList();

Which of the following declarations use raw type?

c

Which of the following deployment descriptor snippets would you use to declare the use of a tag library? a. <tag-lib> a. <uri>http://abc.net/ourlib.tld</uri> a. <location>/WEB-INF/ourlib.tld</location> a. </tag-lib> b. <taglib> b. <uri>http://abc.net/ourlib.tld</uri> b. <location>/WEB-INF/ourlib.tld</location> b. </taglib> c. <taglib> c. <taglib-uri>http://abc.net/ourlib.tld</taglib-uri> c. <taglib-location>/WEB-INF/ourlib.tld</taglib-location> c. </taglib> d. <taglib> d. <tagliburi>http://abc.net/ourlib.tld</uri> d. <tagliblocation>/WEB-INF/ourlib.tld</location> d. </taglib>

a

Which of the following element are required for a valid <taglib> tag in web.xml?(Choose one) a. <taglib_uri> b. <taglib-location> c. <tag-uri> d. <taglib-name>

a

Which of the following elements defines the properties of an attribute that a tag needs? a. attribute b. tag-attribute c. tag-attribute-type d. attribute-type

a

Which of the following is a correct JSP declaration for a variable of class java.util.Date? a. <%! Date d = new Date(); %> b. <%! Date d = new Date() %> c. <%@ Date d = new Date() %> d. <% Date d = new Date() %>

Creational, Structural and Behavioral patterns.

Which of the following is correct list of classifications of design patterns.

C. int[] a = new int(2); D. int a = new int[2]; E. int a() = new int[2];

Which of the following is incorrect?

"rw"

Which of the following is the legal mode for creating a new RandomAccessFile stream?

a

Which of the following lines of code, in the doPost() method of a servlet, uses the URL rewriting approach to maintaining sessions? (Choose one) a. out.println("<a href=' "+response.encodeURL("/servlet/XServlet")+" '>Click here</a>")); b. out.println("<a href=' "+request.rewrite("/servlet/XServlet")+" '>Click here</a>")); c. out.println(response.rewrite("<a href='/servlet/XServlet'>Click here</a>")); d. request.useURLRewriting();

File.pathSeparatorChar

Which of the following returns the path separator character?

a

Which of the following statement correctly store an object associated with a name at a place where all the servlets/jsps of the same webapp participating in a session can access it? Assume that request, response, name, value etc. are references to objects of appropriate types.(Choose one) a. request.getSession().setAttribute(name, value); b. response.setAttribute(name, value); c. request.setAttribute(name, value); d. request.setParameter(name, value)

a

Which of the following statement is a correct JSP directive?(Choose one) a. <%@ tagliburi="http://www.abc.com/tags/util" prefix="util" %> b. <%! page import='java.util.*' %> c. <% include file="/copyright.html"%> d. <%! tagliburi="http://www.abc.com/tags/util" prefix="util" %>

A. printMax(1, 2, 2, 1, 4); B. printMax(new double[]{1, 2, 3}); C. printMax(1.0, 2.0, 2.0, 1.0, 4.0);

Which of the following statements are correct to invoke the printMax method in Listing 6.5 in the textbook?

None of the above.

Which of the following statements are true? A. If a file (e.g., c:\temp.txt) does not exist, new File("c:\\temp.txt") returns null. B. If a directory (e.g., c:\liang) does not exist, new File("c:\liang") returns null. C. If a file (e.g., c:\temp.txt) does not exist, new File("c:\\temp.txt") creates a new file named c:\temp.txt. D. If a directory (e.g., c:\liang) does not exist, new File("c:\liang") creates a new directory named c:\liang.

new File("c:\\temp.txt")

Which of the following statements creates an instance of File on Window for the file c:\temp.txt?

DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat"));

Which of the following statements is correct to create a DataOutputStream to write to a file named out.dat?

Consider the following code snippet: ArrayList<Double> arr = new ArrayList<>(); String element = arr.get(0); Is there an error in this code?

Yes, a compile-time error will occur because you cannot assign a Double value to a String variable.

a

Which of the following statements is true? (Choose one) a. Session data is shared across multiple webapps in the same webserver/servlet container. b. Any serializable object can be put into a session. c. A session can only be invalidated after "session-timeout" minutes of inactivity. d. To use session, the client browser must support cookies.

B. double d[] = new double[30]; C. int[] i = {3, 4, 3, 2}; Explanation: e would be corrected if it is char[] c = new char[]{'a', 'b', 'c', 'd'};

Which of the following statements is valid?

a

Which of the following task may happen in the translation phase of JSP page? (Choose one) a. Creation of the servlet class corresponding to the JSP file. b. Execution of _jspService() method. c. Instantiation of the servlet class. d. None of the others

a

Which of the following xml fragments correctly define a security constraint in web.xml? (Choose one) a. <security-constraint> a. <web-resource-collection> a. <web-resource-name>Info</web-resource-name> a. <url-pattern>/info/*</url-pattern> a. <http-method>GET</http-method> a. </web-resource-collection> a. <user-data-constraint> a. <transport-guarantee>CONFIDENTIAL</transport-guarantee> a. </user-data-constraint> a. </security-constraint> b. <security-constraint> b. <web-resource-collection> b. <web-resource-name>Info</web-resource-name> b. <url-pattern>/info/*</url-pattern> b. <http-method>GET</http-method> b. </web-resource-collection> b. <auth-constraint> b. <role-name>manager</role-name> b. </auth-constraint> b. </security-constraint> c. <security-constraint> c. <web-resource> c. <web-resource-name>Info</web-resource-name> c. <url-pattern>/info/*</url-pattern> c. <http-method>GET</http-method> c. </web-resource> c. <auth-constraint> c. <role-name>manager</role-name> c. </auth-constraint> c. <user-data-constraint> c. <transport-guarantee>CONFIDENTIAL</transport-guarantee> c. </user-data-constraint> c. </security-constraint>

c

Which of these is legal attribute of page directive?. a. include b. scope c. errorPage d. debug

d

Which statement about an entity instance lifecycle is correct? a. A new entity instance is an instance with a fully populated state. b. A detached entity instance is an instance with no persistent identity. c. A removed entity instance is NOT associated with a persistence context. d. A managed entity instance is the instance associated with a persistence context.

a

Which statement about entity manager is true? a. A container-managed entity manager must be a JTA entity manager. b. An entity manager injected into session beans can use either JTA or resource-local transaction control. c. An entity manager created by calling the EntityManagerFactory.createEntityManager method always uses JTA transaction control.

c

Which statement describe about JMS is NOT true? a. JMS supports Publish/Subcribe b. JMS enhances access to email services c. JMS use JNDI to locate the destination

a

Which statement describe about Message-Driven Beans is correct? (Choose one) a. Message-Driven Beans are stateful b. An EJB 3.0 message-driven beans can itself be the client of another message-driven beans c. The bean mediates between the client and the other components of the application, presenting a simplified view to the client.

a

Which statement is true about EJB 3.0 containers? a. javax.naming.initialContext is guaranteed to provide a JNDI name space b. Java Telephony API is guaranteed to be available for session and message beans c. The Java 2D API is guaranteed to be available for session beans

a

Which statement is true about EJB 3.0 stateful session beans and stateless session beans? a. Both can have multiple remote and local business interfaces b. Only the stateful session bean class is required to implement java.io.Serializable interface c. Both can be passivated by the EJB container to preserve resource d. Only the stateless session bean class is required to implement java.io.Serializable interface

c

Which statements are BEST describe <jsp:getProperty> Action? a. Specifies the relative URI path of the resource to include. The resource must be part of the same Web application. b. Dynamically includes another resource in a JSP. As the JSP executes, the referenced resource is included and processed. c. Sets a property in the specified JavaBean instance. A special feature of this action is automatic matching of request parameters to bean properties of the same name. d. Gets a property in the specified JavaBean instance and converts the result to a string for output in the response.

a

Which statements are BEST describe errorPage attribute of <%@ page errorPage=....%> directive? a. Any exceptions in the current page that are not caught are sent to the error page for processing. The error page implicit object exception references the original exception. b. Specifies if the current page is an error page that will be invoked in response to an error on another page. If the attribute value is true, the implicit object exception is created and references the original exception that occurred. c. Specifies the MIME type of the data in the response to the client. The default type is text/html. d. Specifies the class from which the translated JSP will be inherited. This attribute must be a fully qualified package and class name.

a

Which statements are BEST describe prefix attribute of <%@ taglib prefix=...%>directive of JSP file? a. Specifies the relative or absolute URI of the tag library descriptor. b. Specifies the required prefix that distinguishes custom tags from built-in tags. The prefix names jsp, jspx, java, javax, servlet, sun and sunw are reserved. c. Allows programmers to include their own new tags in the form of tag libraries. These libraries can be used to encapsulate functionality and simplify the coding of a JSP. d. The scripting language used in the JSP. Currently, the only valid value for this attribute is java.

a

Which statements are BEST describe property attribute of <jsp:setProperty property=.... /> Action? a. The ID of the JavaBean for which a property (or properties) will be set. b. The name of the property to set. Specifying "*" for this attribute causes the JSP to match the request parameters to the properties of the bean. c. If request parameter names do not match bean property names, this attribute can be used to specify which request parameter should be used to obtain the value for a specific bean property. d. The value to assign to a bean property. The value typically is the result of a JSP expression.

FileNotFoundException

Which type of exception occurs when creating a DataInputStream for a nonexistent file?

What is synchronization and why is it important?

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.

RandomAccessFile(),

With which I/O class can you append or update a file?

super

Without ______, a constructor invokes the default constructor in the base class instead of the proper constructor. (i.e. studentName = "No name yet" vs. studentName = initialName)

memeto

Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.

What are wrapped classes?

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

is the static keyword used for importing a static nested class?

Yes and No! both work: import packageName.TopLevelClass.StaticClass import static packageName.TopLevelClass.StaticClass

if outer and inner classes define variables with the same name, how would you reference the outer class variable within the inner class?

[outer class name].this.[variable name] public class Outer { private String memo; public class Inner{ private String memo; System.out.println(Outer.this.memo); } }

Multi-line Comment

\* */

the entire process is JVM independent

____ , meaning an object can be serialized on one platform and deserialized on an entirely different platform.

JSF

____ completely separates Web UI from Java code so the application developed using JSF is easy to debug and maintain.

Explicit, default

____ initialization is better than ____ initialization.

Socket programming

_____ _____ provides a low-level mechanism by which you can connect two computers for the exchange of data.

The ObjectOutputStream class

_____ contains many write methods for writing various data types, but one method in particular stands out public final void writeObject(Object x) throws IOException -serializes an Object and sends it to the output stream.

IP

_____ is a network protocol that moves packets of data from a source to a destination. As the name implies, this is the protocol normally used on the Internet.

legacy classes : Stack

_____ is a subclass of Vector that implements a standard last-in, first-out stack.

legacy classes : Dictionary

_____ is an abstract class that represents a key/value storage repository and operates much like Map.

URL Uniform Resource Locator

_____ is an acronym for _____ _____ _____. (It is also the name of a class in Java.) A _____ is a pointer to a particular resource at a particular location on the Internet.

URL socket

_____ programming occurs at a higher level than _____ programming.

Array, Class, Reference

_____ types and _______ types are _______ typesThey both hold the memory addresses as opposed to the actual item named by the variable.

fter a serialized object has been written into a file

_____, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

legacy classes : Vector

______ implements a dynamic array. It is similar to ArrayList, but with some differences. -is synchronized. -ontains many legacy methods that are not part of the collections framework.

legacy classes : Properties

______ is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String.

Private

______ methods should serve only as HELPING methods and should be limited to the class in which they are defined.

r1 Instance, non-static, instance

_______ calls the method about because about is ______, and must be called by an _______ of the class it resides

Overloading;overriding

_______ gets a method used before with different parameter amount/type while _______ replaces a method's definition with the same name, return type, and parameter type.

Private instance variables

________ in a base class are not inherited by a derived class and CANNOT be referenced directly by name in a derived class.

constant

a container whose value can be read, but not changed. A variable is converted into a constant by placing the keyword final before the type; e.g., final double PI = 3.14159.

Private methods

_________ in a base class are not inherited by a derived class; they cannot be called directly by name from a derived class

legacy classes : Hashtable

_________ was part of the original java.util and is a concrete implementation of a Dictionary.

Overriding

__________ a method redefines it in a descendant class when the bass class has the same name, number, and types of parameters, and return type.

comapreTo

___________ method should return: *negative number if calling object "comes before" the parameter other *zero if the calling object "equal" the parameter other *Positive number if the calling object "comes after" the parameter other

a *file* that contains *binary data* is known as _____

a *binary file* (713)

garbage collector

a Java component that reclaims de-referenced handles.

escape sequence

a backslash followed by one or more additional characters.

FACT

a catch clause that uses a parameter variable of the Exception type is capable of catching any exceptions that inherits from the Exception class (690)

PrintStream class

a class that includes methods for displaying a value on the screen.

What is an inner class?

a nested class that is NOT static

scientific notation

a number expressed in the form A.B x 10C where A, B, and C are integers. The equivalent representation in Java can be represented in Java as A.BeC.

base-2

a number system based on the two digits 0 and 1

real number

a number that includes values to the left and right of a decimal point

fixed-point literals

a number with a fixed decimal point; e.g., -1.5 and 3.5.

literal

a particular value of any type; e.g., 'a', 1.2, and 5 are literals, respectively, of type char, double, and int.

remainder

a portion of the divisor that is left over after an integer division operation

expression

a series of operands, operators, objects, and/or messages that combine to produce a value.

Math class

a set of mathematical functions used to build complex expressions.

Unicode character

a standard code that Java uses to represent characters. Each letter, digit, or symbol is represented by a different number using 16 bits. The Unicode standard represents 216 = 65,536 different characters.

truth table

a table showing the value produced by a logical operator for each possible combination of operands.

overloaded

a term applied to a method name that has multiple meanings within a class.

FACT

a try statement can have several catch clauses in order to handle different types of exceptions (692) ~the program does not use the exception handlers to recover from any of the errors ~regardless of whether the file is not found or a nonnumeric item is encountered in the file, this program still halts

byte

a type that is made up of 8 bits

boolean

a type that stores a logical value of true (1) or false (0)

short

a type that uses 16 bits to store integer values. A short type has less capacity than an int type or long type

float

a type that uses 32 bits to represent a real number. A float type has less capacity than a double type.

long

a type that uses 64 bits to store integer values. A long type has greater capacity than an int type or short type.

char

a type used to store character values

collections framework

a unified architecture for representing and manipulating collections

null

a value that indicates no particular object is being referenced.

quotient

a whole number representing the number of times a dividend can be segmented into units equal to the divisor.

OutputStream class

abstract base class for writing to binary output stream

Use the ____ layout manager when you add components to a maximum of five sections. a. BorderLayout b. GridLayout c. GridBagLayout d. CardLayout

a. BorderLayout

Which of the following is true about design patterns?

a. Design patterns are obtained by trial and error by numerous software developers over quite a substantial period of time. b. Design patterns are solutions to general problems that software developers faced during software development. c. Design patterns represent the best practices used by experienced object-oriented software developers.

The parent class for all event objects is named ____, which descends from the Object class. a. EventObject b. Event c. ParentEvent d. AWTEvent

a. EventObject

The focusGained(FocusEvent) handler is defined in the ____ interface. a. FocusListener b. ComponentListener c. AdjustmentListener d. ActionListener

a. FocusListener

Clicking an item in a list box results in a(n) ____. a. ItemEvent b. WindowEvent c. ActionEvent d. MouseEvent

a. ItemEvent

a. If you were creating an app in many different languages, would you have to write the entire program from scratch for each language? b. What part of the program would stay the same? c. What part of the program would be different?

a. No b. Java code c. XML layout file

A BorderLayout is arranged in north, south, east, west, and bottom positions. a. True b. False

a. True

An additional layered pane exists above the root pane, but it is not often used explicitly by Java programmers. a. True b. False

a. True

Layout managers are interface classes that align components to prevent crowding or overlapping. a. True b. False

a. True

When you create a simple scroll pane using the constructor that takes no arguments, horizontal and vertical scroll bars appear only if they are needed. a. True b. False

a. True

Java automatically converts the add(), remove(), and setLayoutManager() statements to more complete versions that include _____. a. getContentPane() b. glassPane() c. getJFrame() d. addAll()

a. getContentPane()

Which of the following statements will set the background color of a button named stop to a color of red? a. stop.setBackground(Color.RED); b. stop.Backcolor = RED; c. red.setBackground(Color.RED); d. setBack.stop.Color.RED;

a. stop.setBackground(Color.RED);

A method that has no implementation is called a/an ___ method.

abstract

FACT

an *exception* is an object (682)

What happens if we try to create an enum from a String value that doesn't match exactly?

an IllegalArgumentException is thrown

How can an enum be like an abstract class with mini subclasses?

an enum type can define an abstract/default method implementation that is overridden by applicable enums: public enum Season { WINTER{ public String printTemp() { return "cold" }, SUMMER{ public String printTemp() { return "hot" }, FALL, SPRING; // always need // semi-colon if more than just values declared public String printTemperature() { return "ok"; } }

logical expression

an expression that evaluates to boolean true or false.

double expression

an expression that produces a double value.

What needs to be created in order to instantiate a member inner class?

an instance of the enclosing class

read-only item

an item, such as a constant, whose value can be read but not changed at run-time.

object serialization

an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

Iterator

an object that implements either the Iterator or the ListIterator interface. - enables you to cycle through a collection, obtaining or removing elements. -ListIterator extends Iterator to allow bidirectional traversal of a list and the modification of elements. https://www.tutorialspoint.com/java/java_using_iterator.htm

concatentation-assignment shorcut

an operation represented by +=. This shortcut combines assignment and concatenation operations on String values

for every try block

at least 1 catch block (can have multiple catch blocks to catch different types of exceptions in try block)

downcasting objects

avoid, casting animal to dog object; ((Dog) anAnimal).bark();

The FlowLayout class contains three constants you can use to align Components with a ____. a. Border b. Container c. Button d. Window

b. Container

If you do not specify alignment, Components are right-aligned in a FlowLayout Container by default. a. True b. False

b. False

The CardLayout manager generates a stack of containers, one on top of another. a. True b. False

b. False

The following statement produces a dark purple color that has green and blue components, but no red: Color darkPurple = new Color(100, 0, 100); a. True b. False

b. False

The wildcard in the import java.awt.* statement imports all types in the java.awt package, including java.awt.Color and java.awt.Font. a. True b. False

b. False

When you place a component on the screen, the vertical position is the x-axis and the horizontal position is the y-axis. a. True b. False

b. False

When you use BorderLayout, you are required to add components into each of the five regions. a. True b. False

b. False

As you add new Components to a ____, they are positioned in sequence from left to right across each row. a. CardLayout b. GridLayout c. FlowLayout d. BorderLayout

b. GridLayout

The JMenus are added to the JMenuBar using the ____ method. a. addMenu() b. add() c. addNewMenu() d. setMenu()

b. add()

With ____, a redrawn JPanel is displayed only when it is complete; this provides the viewer with updated screens that do not flicker while being redrawn. a. single buffering b. double buffering c. auto filtering d. double framing

b. double buffering

If you wanted to see the x-coordinate of a user click, you would use the ____ method of the MouseEvent class. a. getClick() b. getX() c. getY() d. getHoriz()

b. getX()

A ____ is placed at the top of a container and contains user options. a. glass pane b. menu bar c. content pane d. containment hierarchy

b. menu bar

Which of the following statements will correctly add a JMenuBar named myBar to a JFrame? a. myBar = setJMenuBar b. setJMenuBar(myBar) c. JMenuBar.setJMenuBar(myBar) d. JMenuBar = new JMenuBar(myBar)

b. setJMenuBar(myBar)

When you type "A", two ____ key codes are generated: Shift and "a". a. action b. virtual c. event d. default

b. virtual

Which property of TextView displays a solid color behind the text?

background

Which property of TextView displays an image as a backdrop behind the text?

background

Objects are saved in ___ format in object streams.

binary

When storing numbers in a file with fixed record sizes, it is easier to store them in ___ format.

binary

a file that is *opened or created* with the *RandomAccessFile class* is treated as a _____file

binary (719) ~the *RandomAccessFile class* has the same methods as the *DataOutputStream class* for writing data, and the same methods as the *DataInputStream class* for reading data

Given the HashSet class implementation discussed in section 16.4 (partially shown below), select the statement needed to complete the clear method, which is designed to remove all elements from the set. public class HashSet { private Node[] buckets; private int currentSize; public HashSet(int bucketsLength) { buckets = new Node[bucketsLength]; currentSize = 0; } public void clear() { for (int j = 0; j < buckets.length; ++j) { ___________________________ } currentSize = 0; } ... }

buckets[j] = null;

inheritance

building on existing classes to create more specialized classes (reusing work)

The part of the web application that is independent of the graphical user interface is called:

business logic.

The Color class can be used with the setBackground() and setForeground() methods of the ____ class. a. Container b. JPanel c. Component d. JFrame

c. Component

The parent class of MouseEvent is ____. a. AWTEvent b. EventObject c. InputEvent d. UserEvent

c. InputEvent

What is the parent class of JPanel? a. Object b. Component c. JComponent d. Container

c. JComponent

You use the getModifiers() method with an InputEvent object, and you can assign the return value to a(n) ____ variable. a. String b. boolean c. int d. double

c. int

Which of the following is NOT a method of the KeyListener interface? a. keyTyped() b. keyPressed() c. keyClicked() d. keyReleased()

c. keyClicked()

What should be done to get the attention of a thread?

call the thread's interrupt method

binary files

can contain non-character data, compiled java programs are binary files

interface restriction

can only contain abstract methods/constants

ArrayList downside

can only store objects

inheritance structures

diagram of inheritance hierarchies before the code is written

In an outer class that contains an inner class, what are two ways to reference the inner class in the outer class methods?

directly - Inner indirectly - Outer.Inner public class Outer { public class Inner{ } public test reference{ Inner inner = new Inner(); Outer.Inner inner2 = new Inner(); } }

if base class is private

cannot inherit or be accessed by subclasses

upcasting objects

casting a dog to an animal object

in versions prior to Java 7, each _____ clause can handle only 1 type of exception

catch class (700) ~however, a catch clause can handle more than 1 type of exception ~this can reduce a lot of duplicated code in a try statement that needs to catch multiple exceptions, but performs the same operation for each one

What is the name of the property used to center an EditText control hint property horizontally?

center_horizontal gravity property

text files use

character streams, which map each digit to a single byte of storage as a character

When a RadioGroup control is placed on the emulator, the first RadioButton control is selected by default. Which property is set as true by default?

checked

those that do not inherit from *Error* or *RuntimeException* are _____

checked exceptions (703) ~you should handle these exceptions in your program

subclass aka

child class/derived class

implement multiple interfaces

class Name implements Interface1, Interface2

wraper class

class for each primitive. Ex: Interger is wrapper class for the int primitive. Allow us to use primitive data types in situations that require objects.

concrete class

class you can instantiate using the new keyword, as appoesed to abstract class or interface.

*exception objects* are created from _____ in the Java API

classes (682)

close()

closes stream and flushes stream buffer

void close() [DataOutputStream method]

closes the file (714)

RuntimeException examples

dividing by 0, arithmetic exception generated, when program is run, program will stop and the output shows Exception in thread "main" and etc...

integer division

division operation that produces a quotient and a remainder.

if a local variable is defined before a local inner class definition, and reassigned afterwards, is the local variable effectively final?

doesn't matter when it's reassigned, it's not effectively final

array object method definition (within for loop, using dogCollection and bark)

dogCollection[i].bark();

With GlassFish, the default deployment directory is called:

domains/domain1/autodeploy

What does dpi stand for?

dots per inch

The readDouble and writeDouble methods of the RandomAccessFile class, process double precision floating-point numbers a ___ quantities.

eight-byte

Map interface

elements in collections consist of object with key value pairs

Given the ArrayStack class implementation discussed in section 16.3 (partially shown below), select the statements needed to complete the push method. public class ArrayStack { private Object[] elements; private int currentSize; public ArrayStack() { final int INITIAL_SIZE = 10; elements = new Object[INITIAL_SIZE]; currentSize = 0; } public void push(Object element) { growIfNecessary(); ________________ ________________ } }

elements[currentSize] = element; currentSize++;

ArrayList<Type>(int n)

empty ArrayList to hold n objects of specified type

A(n) _____ is software that duplicates how an app looks and feels on a particular device.

emulator

Java Generic methods and generic classes

enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively.

try block

encloses code that may give rise to 1+ exceptions

catch block

encloses code to handle specific type of exception

You assign the ___________ property to the string array that you create for a Spinner.

entries

a(n) _____ is an object that is generated in memory as the result of an error or an unexpected event

exception (681,682)

a(n) _____ is a section of code that responds to *exceptions* when they are *thrown*

exception handler (682)

What is wrong with the following statement? ResultSet result = statement.execute("SELECT * from emp WHERE empNum = '5'");

execute should be executeQuery

You can use the generic ____ method to execute arbitrary SQL statements.

execute()

must do this to define own exception

extend Exception class

the _____ holds the byte number of a location in the file

file pointer (721)

Which method yields a stream of all elements fulfilling a condition?

filter

the _____ is 1 or more statements that are always executed after the try block has executed and after any catch blocks have executed if an exception was thrown

finally block (698) ~the statements in the finally block execute whether an exception occurs or not

the try statement may have an optional _____ clause, which must appear after all of the catch clauses

finally clause (697) ~this is optional

Write a GetText( ) statement that converts a variable named deficit to a double data type and assigns the value to the variable named financeDeficit.

financeDeficit =Double.parseDouble(deficit.getText().toString());

Write a line of code that closes the resources of the existing Activity.

finish( ); OR onDestroy( );

Insert the missing code in the following code fragment. This fragment is intended to remove a node from the head of a linked list: public class LinkedList { . . . public Object removeFirst() { if (first == null) { throw new NoSuchElementException(); } Object element = first.data; ________________ ________________ } . . . }

first = first.next; return element;

Name two numeric data types that can contain a decimal point

float and double

File class methods (java.io)

getAbsolutePath, list, mkdir, createNewFile

To fetch a column in a result set that stores the number of children, use the ______ method.

getInt()

each exception object has a method named _____ that can be used to retrieve the *default error message* for the exception

getMessage (688) ~also used when the exception is not handled & the app halts

Which method of an exception object will retrieve a description of the exception that occurred?

getMessage()

input stream

gets data from external device

to ____ an exception, you use a try statement

handle (684)

Both Swing and JSF handle the tedious details of capturing user input, but JSF ________.

handles form-posting events.

Which method is NOT part of the ListIterator generic class?

hasMore

When you override the equals(Object o) method, what method are you also expected to override?

hashCode()

Deserializing an Object

https://www.tutorialspoint.com/java/java_serialization.htm

Given the partial ArrayList class declaration below, select an expression to complete the contains method, which is designed to return true if the element is contained within the list. public class ArrayList { private Object[] elements; private int currentSize; public ArrayList() { final int INITIAL_SIZE = 10; elements = new Object[INITIAL_SIZE]; currentSize = 0; } public boolean contains(Object item) { for (int i = 0; ________________ ; i++) { if (elements[i].equals(item)) { return true; } } return false; } ... }

i < currentSize

What is the preferred prefix for a filename of the launcher icon?

ic_launcher

Write an If statement that tests if the value in the variable age is between 18 and 21 years of age, inclusive, with empty braces.

if ( age >= 18 && age <=21) { }

Write an If statement that tests if the radio button named gender is selected with empty braces.

if (gender.isChecked()) { }

Fix this statement: if (hours < 2 || > 8){ }

if (hours < 2 || hours > 8) { }

FACT

if a class contains objects of other classes as fields, those classes must implement the *Serializable* interface, in order to be *serialized* (724)

Name two decision structures.

if and switch

Scanner source argument

if reading file with BufferedReader in, then new Scanner(in) otherwise if reading keyboard, new Scanner( System.in)

WARNING

if the file that you are opening with the *FileOutputStream* object already exists, it will be erased & an empty file by the same name will be created (713)

FACT

if you do not pass a message to the constructor, the exception will have a *null* message (704)

FACT

if you pass the name of an existing file to the FileOutputStream constructor, it will be erased and a new empty file with the same name will be created (718)

buffers are used to

improve program performance by reducing low-level i/o operatons (hodls 4k bytes of info)

FACT

in many cases, the code in the try block will be capable of throwing more than 1 type of exception (690)

Serializable interface

in order for an obcect to be serialized, its class must implement this interface, which is in the *java.io* package & has no methods or fields (724)

the problem with sequential file access:

in order to read a specific byte from the file, all the bytes that precede it must be read first (718)

import java.io.Serializible interface and implement it

in order to serialize a class

FACT

in the try block and the catch block, the braces are required (684)

exception object stores

info of nature of problem, lets the info be available to your code

type

information that specifies the kind of value that can be stored in a variable. Java uses primitive types to store the values of atomic variables and reference types to store references to objects.

In Java, generic programming can be achieved with ____.

inheritance

if base class is protected

inherited and accessed only by subclasses

how to write an object to a class

initialize the object (maybe using parameterized constructor), create ObjectOutputStream, and then use writeObject()

using Scanner nextInt to define int variable

int integer = aScanner.nextInt()

can't use Reader method to parse through

int values (use Scanner class)

primitive type

int, float, char, etc...

Initialize an array named temps with the integers 22, 56, 38, 30, and 57.

int[] temps = { 22, 56, 38, 30, 57 };

*Error* class

intended to be a *superclass* for exceptions that are thrown when a critical error occurs, such as an internal error in the JVM or running out of memory (683) ~your apps should not try to handle these errors because they are the result of a serious condition

when java performs i/o

interacts with streams

exception handling

intercepting & responding to *exceptions* (682)

super keyword

invokes base class method/constructor in a subclass

what is the purpose of an enum constructor?

it allows an enum value to have instance variables: public enum Season { WINTER("cold"), SUMMER("hot"); // always need // semi-colon if more than just values declared private String temperature; private Season(String temperature) { this.temperature = temperature; } public getTemperature() { return temperature; } }

When you close a connection:

it closes the connection and closes all statements and result sets.

What is a nested class?

it is a class defined within another class public class Animal { protected class Kingdom {} }

What is a local inner class?

it is a nested class defined within a method

What is a hash code?

it is a number that puts instances into a finite number of categories (think putting all same numbers together in a pile of cards)

what does effectively final local variable mean for a local inner class?

it means that if a local variable defined in the same method could compile with the keyword final in front of it, then it is effectively final and can be referenced inside the local inner class

What must an anonymous inner class define?

it must extend an existing class or implement an existing interface

What does this evaluate to and why? Season summer = Season.SUMMER; System.out.println(summer == Season.SUMMER);

it prints true because enums are like static final constants. They will point to the same instance.

What is an enum?

it represents an enumeration that holds a finite set of constant values

How is a static nested class namespaced?

it's own namespace is created package alphabet; public class A { public static class B {}} B would be imported using one of the following import alphabet.A.B; import static alphabet.A.B;

A(n) _____ is a single string of information in a string array.

item

Which Java package contains the LinkedList class?

java.collections

Collection Interfaces : are divided into two groups

java.util.Collection java.util.Map -not true collections

Collection Interfaces : java.util.Collection

java.util.Set java.util.SortedSet java.util.NavigableSet java.util.Queue java.util.concurrent.BlockingQueue java.util.concurrent.TransferQueue java.util.Deque java.util.concurrent.BlockingDeque

java.util.Map

java.util.SortedMap java.util.NavigableMap java.util.concurrent.ConcurrentMap java.util.concurrent.ConcurrentNavigableMap

All database URLs have the format:

jdbc:subprotocol:driver-specific data

when is an enum constructor called?

just once, the first time the code calls for any enum value, Java will construct all enum values and from then on return only already constructed values

when referencing an outer class member from a member inner class, what syntax is used?

just use the name of the member. ex: private String name; innerClassMethod(name); so no preface to the name variable is needed. treated like it's available within the member inner class

super

keyword that calls the constructor of the base class. *Must be the FIRST action taken in a constructor definition

Consider the following code snippet: public static void main(String[] args) { final Order myOrder = new Order(); JButton button = new JButton("Calculate"); final JLabel label = new JLabel("Total amount due"); . . . class MyListener implements ActionListener { public void actionPerformed(ActionEvent event) { . . . } } }

label and myOrder can be accessed.

What is the name of the icon on the Android home screen of your device that opens an app?

launcher icon

A(n) ______ is a container that can hold widgets and other graphical elements to help you design an interface for an application.

layout

What is the scope of a local inner class?

like a local variable goes in scope when method is invoked goes out of scope when method returns

A collection that allows speedy insertion and removal of already-located elements in the middle of is is called a ___.

linked list

The outcome of a SQL query is a ____________________.

list

To declare a bounded type parameter

list the type parameter's name, followed by the extends keyword, followed by its upper bound. example : public static <T extends Comparable<T>> T maximum(T x, T y, T z)

collection subinterface

list, map, set. Each define additonal methods that are appropriate for those types of collections.

If a thread sleeps after acquiring a ____, it blocks all other threads that want to acquire it.

lock

A file pointer is a position in a random access file. Because files can be very large, the file pointer is of type ____.

long

invoked, array of strings, operating system

main is _____________ automatically and given a default __________ but can be added with additional ones to provide elements using the _________.

A _____ is an object that is controlled by the JSF container.

managed bean

Which method applies a function to all elements of a stream, yielding another stream?

map

class method

message sent to a class, not a particular instance of the class

seek method

method used to move the *file pointer* (721)

What package will you use to import Element?

org.w3c.dom.Element

Consider the following code snippet: public class Coin { private String name; . . . public boolean equals(Object otherCoin) { return name.equals(otherCoin.name); } . . . } What is wrong with this code?

otherCoin must be cast as a Coin object before using the equals method.

example of printf()

out.printf("%d%-30s%15s\n", (i + 1))

How can the deepest class in a 3-level nested class be referenced from the outer class?

outer class only knows about inner classes defined at the member level - must use Inner to define the nested class within it, namely MostInner public class Outer { public class Inner{ public class MostInner{} } public getMostInner() { Outer.Inner.MostInner m = new Inner.new MostInner(); } }

in order for a catch clause to be able to deal with an exception, its _____ must be of a type that is compatible with the exception type

parameter (684)

px stands for _____

pixel

Answer the question below about the following initialized array: String[]pizzaToppings = new String[10]; What is the statement to assign mushrooms to the first array location?

pizzaToppings[0] = "mushrooms";

Answer the question below about the following initialized array: String[]pizzaToppings = new String[10]; What is the statement to assign green peppers to the fourth location in the array?

pizzaToppings[3] = "green peppers";

What is the web address of Google Play?

play.google.com

Name three types of drawable objects that can be set as a Background drawable.

png file, 9-patch, or solid color

when handling exceptions, you can use a(n) _____ reference as a parameter in the catch clause

polymorphic (690)

Consider the following code snippet: public class Demo { public static void main(String[] args) { Point[] p = new Point[4]; p[0] = new Colored3DPoint(4, 4, 4, Color.BLACK); p[1] = new ThreeDimensionalPoint(2, 2, 2); p[2] = new ColoredPoint(3, 3, Color.RED); p[3] = new Point(4, 4); for (int i = 0; i < p.length; i++) { String s = p[i].toString(); System.out.println("p[" + i + "] : " + s); } return; } } This code is an example of ____.

polymorphism

When an emulator launches, which orientation type is displayed?

portrait

final keyword regarding classes

prevents method overriding or inheritance

PrintWriter class methods

print() println() printf(formatString, args) flush() close()

precedence levels

priority assigned to an operator

A collection that allows items to be added only at one end and removed only at the other end is called a ___.

queue

in _____, a program can immediately jump to any location in the file without first reading the preceding bytes

random file access (718)

operator precedence

rank of an operator according to its precedence level.

What is the name of the folder that typically holds media files in the Android project?

raw

Which of the following algorithms would be efficiently executed on an ArrayList?

read n / 2 elements in random order from a list of n elementsread n / 2 elements in random order from a list of n elements

DataInputStream methods

read() skipBytes( int n) available()

BufferedReader methods

readLine() read() skip(long n)

If you want to process text data from a file, which keyword do you look for in classes that specialize in doing that?

reader

Boolean readBoolean() [DataInputStream method]

reads a boolean value from the file into returns it (716)

byte readByte() [DataInputStream method]

reads a byte value from the file and returns it (716)

double readDouble() [DataInputStream method]

reads a double value from the file and returns it (716)

float readFloat() [DataInputStream method]

reads a float value from the file and returns it (716)

long readLong() [DataInputStream method]

reads a long value from the file and returns it (716)

short readShort() [DataInputStream method]

reads a short value from the file and returns it (716)

int readInt() [DataInputStream method]

reads an int value from the file and returns it (716)

readLine()

reads line of text and returns as String variable

readObject()

reads object and returns as type Object, will probably cast to specific type

read()

reads single character and returns ASC!! value of character as int

BufferedReader class

reads text from input stream and provides buffering

A queue is a collection that ___.

remembers the order of elements and allows elements to be inserted only at one end and removed only at the other end.

binary number system

representing numbers with the digits 0 and 1

checked exceptions

requires code to be designed to handle these exceptions

What is the convention used for naming enums?

since they are like constants, all uppercase is used to name enum values

skipBytes(int n)

skips over data in input stream

skip( long n )

skips over n character in input stream, returns actual number of characters skipped as int value

What folder are music and image files saved within the Android project view?

res folder

In which subfolder in the Android project view are the XML files stored?

res/layout (answer 'res/values' also accepted)

What does the "R" in R.id.travel stand for?

resource

Which statement will add a dollar sign and the value of the double variable balance to a JTextArea component called results?

results.append("$" + balance);

Given the LinkedListStack class implementation discussed in section 16.3 (partially shown below), select the statement(s) to complete the peek method. public class LinkedListStack { private Node first; public LinkedListStack() { first = null; } public Object peek() { if (empty()) { throw new NoSuchElementException(); } _____________________________ } ... }

return first.data;

interface method definition

return name();

Select an appropriate expression to complete the following method, which is designed to return the sum of the two smallest values in the parameter array numbers. public static int sumTwoLowestElements(int[] numbers) { PriorityQueue<Integer> values = new PriorityQueue<>(); for (int num: numbers) { values.add(num); } ______________________ }

return values.remove() + values.remove();

available()

returns # of bytes remaining in file

toString()

returns String representation of object, can be overriden

list()

returns array of files in the directory definition (dir.list())

next()

returns next token in input source as String, skips to next element in input source

size() for ArrayList

returns number of objects in ArrayList

get(idx)

returns obj at specified index

isEmpty()

returns true if ArrayList is empty

hasNext()

returns true if another token is in input source, used to read to end of input source

getClass().getName()

returns type Class and returns name of class as String

What Java fundamentals do inner classes go against?

reuse of classes high cohesion

% %-

right justify, left justify

left associativity

rule that orders from the left operations that include multiple operators from the same precedence level.

right-associative

rule that orders from the right operations that include multiple operators from the same precedence level.

operator associativity

rules determining the order in which operations of the same precedence are performed.

In which method are the tasks that are performed by a thread coded?

run

The Runnable interface has a single method called ____.

run

When a thread is interrupted, the most common response is to terminate the ___ method.

run

Which tween effect shrinks an image?

scale

What does sp stand for?

scaled-independent pixels

Scanner class

scans input from sources and returns representation of Java primitive type

when the code in a method throws an exception, the normal execution of that method stops & the JVM _____ for a compatible exception handler inside the method

searches (702) ~if there is no code inside the method to handle the exception, then control of the program is passed to the previous method in the call stack [the method that called the offending method] ~if that method cannot handle the exception, then control is passed again, up the *call stack*, to the previous method. ~this continues until control reaches the *main method* ~if the main method does not handle the exception, then the program is halted and the default exception handler handles the exception (702)

when an exception is thrown by code in the try block, the JVM begins _____ the try statement for a catch clause that can handle it

searching (692) ~it searches the catch clauses from top to bottom and passes control of the program to the first catch clause with a parameter that is compatible with the exception

Which method in the RandomAccessFile class provides for random access?

seek

Which method moves the file pointer in a RandomAccessFile?

seek

flush()

sends data in buffer before buffer is full

output stream

sends data to external device

stream

sequence of bytes that flow into/out of a program

In ___ file access, the file is processed starting from the beginning.

sequential

What type of access does a LinkedList provide for its elements?

sequential

with _____ access, when a file is opened for input, its read position is at the very beginning of the file

sequential access (718) ~this means that the first time data is read from the file, the data will be read from its beginning. ~as the reading continues, the file's read position advances sequentially through the file's contents

Java allows you to _____ objects, which is a simpler way of saving objects to a file

serialize (724)

*IOException*

serves as a superclass for exceptions that are related to input and output operations (683)

*RuntimeException*

serves as a superclass for exceptions that result from programming errors, such as an out-of-bounds array subscript (683)

A collection without an intrinsic order is called a ___.

set

buffered text writing definition

set PrintWriter to null, PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter("mydata.txt")))

Which method of the Component class is used to set the position and size of a component?

setBounds() method is used to set the position and size of a component.

Write one line of code that opens the XML layout named lemon.

setContentView(R.layout.lemon);

set(idx, obj)

sets element at specified idx to specified obj

The ___ method is useful only if you know that a waiting thread can actually proceed.

signal

A waiting thread is blocked until another thread calls ___ on the condition object for which the thread is waiting.

signalAll

exception

signals abnormal situation/the occurrence of errors

In Java the byte type is a(n) ___ type.

signed

In Java, the byte type is a(n) ___ type.

signed

The ___ method stops the current thread for a given number of milliseconds.

sleep

Which method launches a Frame animation?

start( )

Write a statement that opens the Android Help Site: http://developer.android.com

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://developer.android.com")));

Write a startActivity statement that launches a class named Studio.

startActivity(new Intent(MainActivity.this, Studio.class));

Write one line of code that would launch a second class named Wireless from the present MainActivity class.

startActivity(new Intent(MainActivity.this, Wireless.class));

assignment statement

statement that assigns a value to a variable

What is a static nested class?

static class defined at the member level

The Collection Algorithms

static methods within the Collections class. https://www.tutorialspoint.com/java/java_collection_algorithms.htm

Which method ends a Frame animation?

stop();

What are the four states of an Activity?

stopped, dead, active, paused

FACT

storing data in its *binary format* is more efficient than storing it as text because there are fewer conversions to take place (713)

A ________ parser reports the building blocks of an XML document.

streaming

The ____ file (full name) holds commonly used phrases (arrays) of text in an application.

strings.xml

A _______ is a piece of code that serves as a placeholder to declare itself, containing just enough code to link to the rest of the program.

stub

ObjectOutputStream

subclass of OutputStream, implements DataOutput interface for writing objects

decrement operator

subtracts 1 from the value of a variable

java.io package

supports stream i/o, must be imported into any program that uses it

Change the following If decision structure to a Switch decision structure: if (count == 3){ result = "Password incorrect"; } else { }

switch(count){ case 3: result = "Password incorrect"; break; default: result = "Request password"; break; }

An HTML page contains ____ that describe the structure of the page.

tags

can hashCode() override contain variables not accounted for in the equals() override?

technically valid, but very bad practice. Remember, two objects that are considered equal from the equals() method should return the same hashcode. If a changing number or unaccounted for variable is used in hashcode, it's possible two equal objects will have different hashcodes.

Given the partial LinkedList class declaration below, select a statement to complete the size method, which is designed to return the number of list elements. public class LinkedList { class Node { public Object data; public Node next; } private Node first; . . . public int size() { int count = 0; Node temp = first; while (temp != null) { count++; _____________________ } return count; } }

temp = temp.next;

is-a test

tests inheritance and polymorphism

instanceof operator

tests whether object is instance (subclass/class/interface) of another type (will return true or false)

Which Plain TextView property is changed to identify the color of the control?

textColor

FACT

the *FileInputStream constructor* will throw a *FileNotFoundException* if the file named by the string argument cannot be found (715)

FACT

the *FileNotFoundException* is a *checked exception* (703)

NOTE

the *FileOutputStream* constructor throws an *IOException* if an error occurs when it attempts to open the file (713)

which class can you use to sequentially process a binary file?

the *RandomAccessFile class* (719)

FACT

the *RandomAccessFile class* treats a file as a stream of bytes (721) ~tey are numbered, with the first byte being 0 & the last being 1 less than the number of bytes in the file

NOTE

the *exception classes* are in packages in the Java API (683)

NOTE

the Java API documentation lists all of the exceptions that can be thrown from each method (685)

The #PCDATA rule means ____________.

the children can consist of any character data.

throwing an exception

the code signals that something went wrong

CONCEPT

the content of a binary file is not formatted as text & not meant to be opened in a text editor (712)

FACT

the default exception handler *prints* an error message & crashes the program (682)

assignment operator:

the equals sign (=)

What is new in Java 8 for effectively final local variables regarding access from local inner classes?

the final keyword is no longer required in front of local variables that will be used in local inner classes if the variable WOULD compile with final in front of it, then it is effectively final and will be accessible

Exception handling improves performance.

the following is not an advantage of Java exception handling

A. add(o: E) B. addAll(c: Collection<? extends E>) C. contains(o: Object): boolean D. containsAll(c: Collection<?>): boolean

the following methods are in the Collection interface

A. clear() B. isEmpty() C. size()

the following methods are in the Collection interface

A. Generics can help detect type errors at compile time, thus make programs more robust. B. Generics can make programs easy to read. C. Generics can avoid cumbersome castings.

the following statements are correct

A. Every recursive method must have a base case or a stopping condition. B. Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. C. Infinite recursion can occur if recursion does not reduce the problem in a manner that allows it to eventually converge into the base case.

the following statements are true

A. Generic type information is present at compile time. B. Generic type information is not present at runtime. C. You cannot create an instance using a generic class type parameter. D. You cannot create an array using a generic class type parameter. E. You cannot create an array using a generic class.

the following statements are true

A. The Collection interface is the root interface for manipulating a collection of objects. B. The Collection interface provides the basic operations for adding and removing elements in a collection. C. The AbstractCollection class is a convenience class that provides partial implementation for the Collection interface. D. Some of the methods in the Collection interface cannot be implemented in the concrete subclass. In this case, the method would throw java.lang.UnsupportedOperationException, a subclass of RuntimeException. E. All interfaces and classes in the Collections framework are declared using generic type since JDK 1.5.

the following statements are true

A. You use the keyword throws to declare exceptions in the method heading. B. A method may declare to throw multiple exceptions. C. To throw an exception, use the key word throw. D. If a checked exception occurs in a method, it must be either caught or declared to be thrown from the method.

the following statements are true

B. Recursive methods usually take more memory space than non-recursive methods. C. A recursive method can always be replaced by a non-recursive method. D. In some cases, however, using recursion enables you to give a natural, straightforward, simple solution to a program that would otherwise be difficult to solve.

the following statements are true

The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the preceding two numbers in the series.

the following statements are true

A. Comparable<String> c = new String("abc"); B. Comparable<String> c = "abc";

the following statements is correct

if x.equals(y) = true, what does this tell you about the hashcode for each?

the hashcode must be the same

interfaces can be used when

the is-a test doesn't work (can't use inheritance)

FACT

the key word *throws* is written at the end of the method header, followed by a list of the types of exceptions that the method can *throw* (703)

What happens to the image if you animate an object past the edges of the View object?

the object is clipped

The HTTP response code 404 means _______________.

the page was not found.

index

the position of a character in a String object.

deserialization

the process of reading a serialized object's bytes and constructing an object from them (725)

The following command: java pgmName hostname / lets you retrieve any item from a web server. The slash means:

the root page of the web server.

integers

the set of whole numbers = {...-3, -2, -1, 0, 1, 2, 3...}.

FACT

use *OutputInputStream* object along with a *FileInputStream* object (725)

throwing an unchecked exception

use throw keyword; throw new ThisTypeOfException()

List interface

use to store other collections. Ex: List<Asteroid> _asteroids = new ArrayList<Asteroid>();. To change to a linked list you'd just have to change one line of code

Scanner class

used to create objects that can read primitive type values from the keyboard.

finally block

used to enclose code that will always execute regardless of exceptions

modulus operator

used to get the remainder of an integer division

BufferedWriter

used to write text to output, provides buffering

When can an abstract class or interface be instantiated?

when instantiated with an anonymous inner class that implements the appropriate methods in the declaration

extend keyword

uses for subclasses to extend parent class

buffered streams

uses large block of memory to store batches of data that flow i/o of program

What is a better than using instanceof operators in a if/else statement?

using an interface - where each type implements own method - same method can be called, by implementation will be specific to subtype

Which Container method is used to cause a container to be laid out and redisplayed?

validate() method is used to cause a container to be laid out and redisplayed.

What do the following enum methods do? values() name() ordinal()

values() - produces iterable list through the values name() - produces a String representation of the value ordinal - produces the int value of the order in which the enum value was declared

Caesar cipher uses a shift of each character by a key with a value between 1 and 255. An a with a shift equal to 3 becomes a d. A z would become a c, wrapping around the alphabet. Which is the encryption of shadow for a key = 3?

vkdgrz

Bounded Type Parameters

want to restrict the kinds of types that are allowed to be passed to a type parameter.

FACT

when a file is first opened, the *file pointer* is set to 0 (721) ~when an item is read from the file, it is read from the byte that the *file pointer* points to ~Reading also causes the pointer to advance to the byte beyond the item that was read

when does a instanceof b evaluate to true?

when a is a - instance of b - subclass of b - implementation of b

FACT

when an exception is thrown by a method executing under several layers of method calls, it is sometimes helpful to know which methods were responsible for the method being called (699)

FACT

when an exception is thrown, it cannot be ignored, but must be handled by the program or default exception handler (702)

FACT

when an object is serialized, it is converted into a series of bytes that contains the object's data (724) ~if the object is set up properly, even the other objects that it might contain as fields are automatically *serialized*

FACT

when data is stored in a *binary file*, you cannot open the file in a text editor (713)

FACT

when in the same try statement you are handling multiple exceptions & some of the exceptions are related to each other through inheritance, then you should handle the more specialized exception classes before the more general exception classes (697)

Why must a local variable be effectively final or final before a local inner class can access it?

when the local inner class is compiled, it can only know about the value at runtime of the local variable if is final - it can be passed in the constructor of the local inner class or stored as a constant in the .class file

example of using readLine()

while(( String line = in.readLine()) != null) (reads line of input, stores it in string line)

ArrayList class

works like an array, but its size is easily expanded to accomodate new elements

serializing

write object to a file

the _____ method throws an *IOException* if an error occurs

writeObject method (725)

to write a string to a binary file you should use the *DataOutputStream* class's _____ method

writeUTF method (717) ~this method writes its *String* argument in a format known as *UTF-8 encoding*

PrintWriter

writes formatted representation of objects to text output stream

writeObject(Object obj)

writes object to output stream

DataOutputStream

writes primitive Java types

FileWriter

writes text to files, connect output stream to a file (subclass of OutputStreamWriter)

void writeUTF(String str) [DataOutputStream method]

writes the String object passed to str to the file using the Unicode Text Format (714)

void writeBoolean(boolean b) [DataOutputStream method]

writes the boolean value passed to b to the file (714)

void writeByte(byte b) [DataOutputStream method]

writes the byte value passed to b to the file (714)

void writeDouble(double d) [DataOutputStream method]

writes the double value to d to the file (714)

void writeFloat(float f) [DataOutputStream method]

writes the float value passed to f to the file (714)

void writeInt(int i) [DataOutputStream method]

writes the int value passed to i to the file (714)

void writeLong(long num) [DataOutputStream method]

writes the long value passed to num to the file (714)

void writeShort(short s) [DataOutputStream method]

writes the short value passed to s to the file (714)

What are the two instances where a reference x instanceof Object returns false?

x is literally null (null instanceof Object) x points to a null reference

Can enum values be used in switch statements?

yes

If an interface is defined within a class, do all the methods have to be public?

yes

If an interface is defined within a class, does the class implementing the methods have to make the overridden methods public?

yes

can a member inner class be abstract or final?

yes

Can an enclosing class refer to members of a static nested class?

yes - can refer to all of them, even private variables

Can a member inner class extend other classes or implement interfaces?

yes to both

Can an anonymous inner class be defined inline as a parameter for a method?

yes! public void testIt() { abstract SaleTodayOnly { abstract void someMethod(); } public void add(int one, SaleTodayOnly s) { } public static void main (String[] args) { add( 4, new SaleTodayOnly() { void someMethod() {// some code } ); } }

Can a local inner class have access to members of the enclosing class?

yes, access to all

Can a enum type have a constructor?

yes, but must be private or else will not compile

Is it legal to override hashcode and not equals and vice versa?

yes, but not good practice

Can you create an enum from a String?

yes, but the String must match exactly the with the enum spelling Season s = Season.valueOf("SUMMER") // creates the enum Season.SUMMER // SUMMER must be all caps

can enum instance variables be updated within instance methods?

yes, can be updated

Does this compile? Runnable r = new Thread(); if (r instanceOf Exception) { }

yes, comparing an interface using an instanceof operator always compiles because the compiler doesn't know if a subclass of the right hand side implements the interface of the left hand side. Ex: Compiler doesn't know if subclass of Exception implements Runnable.

Can a member inner class access members of the outer class in which is defined?

yes, including private members, because the inner class is still defined in the same class

If an enum has an abstract method, does each enum have to implement it?

yes, just like a concrete class extending an abstract class

is a semi-colon required after an anonymous inner class definition?

yes, since it is assigned to a variable definition, needs to have semi colon like any other statement

if a local variable is initialized in all branches of an if-else statement, can it be final?

yes, since it is only set once (regardless of which branch) it is effectively final

Can interfaces defined within a class be private?

yes, they can and only be accessed by class itself

Can interfaces be defined within a class?

yes, they can be defined within a class

can a local inner class instance be the return type for a method?

yes, they work like local variables, can be returned

FACT

you can think of the code in the try block as being *protected* since the app will not halt if the try block throws an exception (684)

FACT

you can use the *throw* statement to manually throw an exception (704) ~causes the object to be created and thrown

CONCEPT

you can write code that throws 1 of the standard Java exceptions, or an instance of a custom exception class that you have designed (704)

If your program needs to look at several result sets at the same time, _____.

you need to create multiple Statement objects.

Or

||

Constructors

*Must always have the same name of the class they're in *Always public *Never have a return type (not even void) *If you have a non-default one you must have a default *Should give a value to every instance variables *Should be the 1st methods of the class *STRONGLY recommended but not required

toString

*Public *Non-static *Expects no arguments *Should be overriden

Non-static

A _______ method may only be called instanceOfTheClassInWhichTheMethodResides.methodName(required arguments);

private, modified

A ________ instance variable that has an array type can be _______ outside of its class, if a public method in the class returns the array.

super();

A class that is an sub part of another should have this at the first line; A call to the constructor of the parent class.

cannot, change, state

A method _______ change the value of an indexed variable when it is a primitive type but can ________ the ________ when it is a class type.

Static variable

A variable that is shared by all the instances of the class in which that variable is declared

Methods

Actions class can complete

Sequential Search Algorithm

Algorithm that looks at the array elements from first to last to see whether the sought-after item is equal to any of the array elements

Selection Sort

Algorithm that rearranges the values of the array so that a[0] is the smallest, a[1] is the next smallest, and etc.

Object

All classes descend from the class ________ (1st generation)

Allocates memory for array to hold length

Array_Name = new Base_Type[Length];

Multidimensional arrays

Arrays having more than one index

0, 1

Arrays start _____ not ____ or other numbers

Two-dimensional array, row, column

Arrays that have two indices, [first index] denotes the ___, [second index] denotes the ______ (begin at 0) (Displayed on paper as a ____ table)

n-dimensional arrays

Arrays with n indices are said to be ___

Instance Variables

Attributes of a class

access, invocation, return type, alias of parameters

Cannot overload on:

square brackets, argument, method

Characteristics of Array Arguments *No _______ are written when you pass an entire array as an argument to a method *An array of any length can be used as a(n) _________ corresponding to an array parameter *A ____________ can change the values in an array parameter

Displaying values entered into array

Function of code: System.out.println("The 7 temperatures are:"); for (int index = 0; index < 7; index++) System.out.print(temperature[index] + " "); System.out.println( );

Overloading methods

Having 2 or more methods in the class with the same name ; _______ on the parameter list (number and type of arguments expected)

Convert the type

If the arguments do not have an exact match with any of the overloaded methods, Java will try to _________________. Otherwise it will fail.

Method Header

Make up the _______ *modifiers (public/private) *invocation(non-static/static) *return_type(void, primitive, class, single) *name(verb, first lowercase letter) *parameter_list(number and type of arguments to be passed

Overriding

Making your own versions of the toString and equals methods

Static variable

Memory space is put in place not for one instance but for all instances. One change from an instance affects all instances

Setters

Sets the value of the instance variable, always public, Controls access to CHANGE of variable

Class

Specifies the members of the objects -Instance Variables -Methods

Multidimensional array parameter

Syntax for a method with a _____ *public *static Base_Type[]...[] Method_Name(Parameter_List)

Declaring a Multidimensional array

Syntax for__________ Base_type[]...[]Array_Name = new Base_Type[Length_1]...[Length_n];

Two-dimensional array

Syntax represents: _____________ Array_Name[Row_Index][Column_Index]

arrays of arrays

The Java compiler represents a multidimensional as __________.

equality (==)

The _______ operator tests whether the arrays are stored in the same place in the computer's memory.

length

The only public instance variable for an array *contains number of elements in an array *value cannot be changed

array, String, String

The parameter String[] args declares that args is an _______ whose base is ______ that takes an array of _______ values as an argument

public static Return_Type Method_Name(Base_Type[] Param_Name)

The syntax for an argument to a method being an entire array:

base

The type for the array is called the ___________

last valid index

arrayName.length - 1 represents the ______ of an array


Related study sets

Fundamentals of Networking Chapter 14

View Set

Ch 14: Annuities & Individual Retirement Accounts

View Set

AWS Developer Associate Exam Questions

View Set

AP CHEMISTRY UNIT 1 - Atomic structure and periodic trends

View Set