JAVA FINAL 1
Refactor - extract method
You have a code fragment that can be grouped together: turn the fragment into a method with a self-explanatory name.
compiler
a program that translates code in a high-level language to machine instructions (such as bytecode for java)
parameter
a reference or value that is passed to a method or subrouting
constructor
a sequence of statements for initializing a newly instantiated object; the job of the constructor is to initialize the instance variables of an object
Java standard class library (Java API)
a set of predefined classes and methods that other programmers have already written for us System, out, println and String are not Java reseved words, they are part of the API
single responsibility
class dose well define job
What is a local class?
classes that are defined in a block, which is a group of zero or more statements between balanced braces. You typically find local classes defined in the body of a method.
switch statement
implements selection control flow
ASCII
maps characters to a number; human and machine readable
terabyte
maximum memory size is 2^40 memory bytes
event handler
processes the events and determines what to do
Mutator methods typically begin with the word "____".
set
instruction set
set of all operations that can be executed by a processor
What is a base class?
the parent of a child class
The toString() method is automatically inherited from the __________________ class. 1. GObject 2. Object 3. java.lang 4. Root 5. Component
2. Object
Take remainder operator
%
The Java Software Development Kit (JDK)
A set of command line tools (e.g., compilers, de-compilers, debuggers) used to develop Java programs. The JDK also contains the JRE, which contains the JVM.
array element
individual value in an array
short
16 bit, useful if memory an issue
Less than or equal to
<=
abstract window toolkit
ABT
Define the keyword "public"
Able to be modified by the class, package, subclass, and world.
JTextField
Hold any text. Can be editable. Use for small amounts of input.
Event Handlers
Methods that host the response code (tells what to do if event occurs).
Can you initialize an array like this - int arr2[] = {1,2,3,4}
No - You need the new keyword
In a UML diagram for a class
classes are represented as rectangles there may be a section containing the name of the class there may be a section containing the attributes (data) of the class there may be a section containing the methods of the class
List
list is an interface that arrayList and other list inherit from
What is JDBC?
- JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.
You cannot declare the same ____ name more than once within a block, even if a block contains other blocks.
variable
The advantage(s) of the Random class' pseudo-random number generators, compared to the Math.random method, is that
you may create several random number generators you can generate random ints, floats, and ints within a range you can initialize and reinitialize Random generators
Boolean not equal to
!=
Which of the following is a valid identifier? (Choose all that apply.) 1) $343 2) class 3) 9X 4) 8+9 5) radius
$343 radius
Bitwise And operator
&
What is the difference between & and &&?
& evaluates both sides. If the first one is false the second statement will be evaluated. && works differently. When the first expression is false it will not execute the second one. This is also known a short cut.
An int variable can hold ________. (Choose all that apply.) 1) 'x' 2) 120 3) 120.0 4) "x" 5) "120"
'x' 120
Can we execute a program without main() method?
Yes, one of the way is static block
add operator
+
Preincrement
++counter
What is UNICODE?
- Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.
How can I set a cookie in JSP?
- response. setHeader("Set-Cookie", "cookie string"); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) - to the bean, and in jsp-file:<% bean. setResponse (response); %>
.java
1. A source code file has the ____ extension.
separates package names / adds folders
.
The extension name of a Java source code file is
.java
Division operator
/
comment
//
numChars = name1.length();
// returns the number of characters name1 contains
What does element indexing start at?
0.
Which of the following are correct ways to declare variables? (Choose all that apply.) 1) int length; int width; 2) int length, width; 3) int length; width; 4) int length, int width;
1) int length; int width; 2) int length, width;
Black box Steps
1. Considered input and output values 2. Partition inputs and outputs into ranges 3. For each equivalence class produce a) set of typical test that cover normal cases b) set of boundary value tests at or around the extreme limits of the equivalence class
What is output with the statement System.out.println(x+y); if x and y are int values where x=10 and y=5?
15
The Swing package
is complementary to the AWT
AND operator (&&)
A logical operator used to ensure that two conditions are both true before choosing a path of execution. Performs short-circuit evaluation.
breakpoint
A marker that can be set in the debugger at any executable line of source code, causing the application to pause when it reaches the specified line of code.
Append
A method that adds text to a JTextArea component.
Suppose x is 1. What is x after x += 2?
3
byte
8 bits
Stop
8. The debugger command ________ sets a breakpoint at an executable line of source code in an application.
The UML represents both the merge symbol and the decision symbol as _____.
Diamonds
What is platform?
A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.
APPLET
A small application that is loaded with an HTML page from a Web server that runs on the client computer.
Merge Symbol
A symbol in the UML that joins two flows of activity into one flow of activity.
CLOB
Character Large OBject
Local variables (field)
Defined inside methods, constructors or blocks. Initialized within method and destroyed when method complete.
Java is a strongly typed language. What is meant by "strongly typed"?
Every variable has a single type associated with it throughout its existence in the program, and the variable can only store values of that type
Staging area
File indicating the modified files in the working directory to be included in the next commit. (Local). Use 'git add'.
What happens when a class final?
It cannot be extended?
What is the JVM?
Java Virtual Machine.
Can you set a float to 1.0?
No, that would automatically make it a double.
Can we override static method?
No, you can't override the static method because they are the part of class not object.
Is delete,next,main,exit or null keyword in java?
No.
font property
Property specifying font name (Times New Roman), style (Bold) and size (12) of any text.
background property
Property that specifies the background color of a content pane component.
Volatility is a property of
RAM
Integer.parseInt
Returns the integer equivalent of a String.
Which of the following lines of code implicitly calls the toString() method, assuming that pete is an initialized Student object variable?
String s = "President: " + pete;
Java was developed by ________.
Sun Microsystems
2
If the variable x contains the value 5, what value will x contain after the expression x -= 3 is executed?
Demo
The filename of the source file must be the same as the class name (###case sensitive###) java MyFirstApp (###not MyFirstApp.class###)
What is object cloning?
The object cloning is used to create the exact copy of an object.
Incrementing
The process of adding 1 to an integer.
destructive
The process of assigning data (or writing) to a memory location, in which the previous value is overwritten or lost.
Suppose x is a char variable with a value 'b'. What is the printout of the statement System.out.println(++x)?
c
MAC
medium access control: data link protocol sub-layer that determine how to arbitrate ownership of a shared communication line when multiple nodes want to send messages at the same time
The speed of the CPU is measured in ________.
megahertz gigahertz
debugging
The process of locating and removing errors in an application.
compiling
The process that converts a source code file (.java) into a .class file.
Having multiple class methods of the same name where each method has a different number of or type of parameters is known as
method overloading
Things an object can do are called?
methods
overload
methods having the same name but different parameter types
behaviors
methods; action for the object to do
Problem Solving
The purpose of writing a program is to solve a problem The key to designing a solution is breaking it down into manageable pieces An object-oriented approach lends itself to this kind of solution decomposition We will dissect our solutions into pieces called classes (.java files) We design separate parts (classes) and then integrate them
What does the word before the instanceof operator have to be and what does the word after?
The word before has to be an object. The word after has to be a superclass.
throws keyword
the throws keyword is used to declare and throw exceptions as opposed to the throw keyword which is followed by a specific instance of an exception (throw new Exception();)
-g compiler option
This flag or option causes the compiler to generate debugging information that is used by the debugger to help you debug your applications.
if statement
This single-selection statement performs action(s) based on a condition.
Halting Problem
To determine if a collection of Turing machine instructions together with any initial tape contents will ever halt if started on that tape
Method signature
name and parameters
||
or operator, control statement is executed when at least one condition is true
java.lang.Thread
provides infrastructure for multithreaded programs. can extend thread but issue with multiple class inheritance so extend runnable instead.
The main method for a Java program is defined by
public static main(String[ ] args)
Main Method
public static void main(String args[])
In Java, "instantiation" means
creating a new object of the class
orphaned data
data that isn't referenced anywhere
variable
data value that can change
operation
deployment and maintenance
To prevent subclasses from overriding an inherited method, the superclass can mark the method as:
final
What is the syntax of a looping control flow example?
for (int i=1; i<10; i++) { ... } while (x < y) { ... } do { ... } while (x<y)
For loop
for( insert argument here) { insert code here }
What is the syntax of a decision control flow example?
if (x == y) { ... } else { ... } switch (index) { case 0: {...} case 1: {...} default: {...} }
If an instance variable creates an object when will it be ran?
When the class is needed in main for the first time
If a program compiles fine, but it produces incorrect result, then the program suffers ________.
a logic error
64 bit integer
long
Map
an interface that maps keys to values - a map object can store the key value pairs
transistor
an electrical switch with no moving parts
main class
application class; contains the main method, start of the program
pseudocode
An informal language that helps programmers develop algorithms.
What is a field?
An instance variable
Benefits of Continuous Integration
- allow team detect problems early - reduce integration problems - increase visibility
Target (ANT)
- can depend on other targets - 'depends' specifies order targets should be executed.
Test Driven Development (TDD)
1. Tests developed before code is written. 2. Once code passes, new tests added 3. Code extended to pass new tests and refactored if necessary. Create tests you know will fail because you know implementation not in place.
Comment
9. A breakpoint cannot be set at a(n) ____.
The Unicode of 'a' is 97. What is the Unicode for 'c'?
99
What is a pipeline?
A Pipeline is built up from stages which can pass data on to subsequent stages
Infinite Loop
A logical error in which a repetition statement never terminates.
getText
A method that accesses (or gets) the text property of a component such as a JLabel, JTextField or a JButton.
Double.parseDouble
A method that converts a String containing a floating-point number into a double value.
block
A set of statements that is enclosed in curly braces ({ and }).
SERVLET
A small program that runs on the server. Is mainly used to generate HTML pages.
sentence-style capitalization
A style that capitalizes the first letter of the first word In the text (for example, Cartons per shipment): other letters in the text are lowercase, unless they are the first letters of proper nouns.
reserved word
A word that is reserved for use by Java and cannot be used to create your own identifiers. Also called *keyword*.
What does the NEW keyword do?
Allocates new space in memory.
To print the number of elements in the array named ar, you can write : A.System.out.println(length); B.System.out.println(ar.length()); C.System.out.println(ar.length); D.System.out.println(ar.length-1);
C. System.out.println(ar.length);
What does the method .equals do from the String class?
Compares the equality of two strings.
What does the method .equals do from the class object?
Compares two object area memories.
What does Javac do?
Compiles the program.
DNS
Domain Name System; converts from a symbolic host name such as Columbia.edu to its 32-bit IP address
The ________ method parses a string s to a double value.
Double.parseDouble(s);
The ________ method parses a string s to an int value.
Integer.parseInt(s);
Java Runtime Environment (JRE)
Interpreter for compiled Java byte code programs. = Java Virtual Machine (JVM)
variable declaration
It associates a type and an identifier (or name) with the variable
is true regarding the mod operator, %
It can be performed on any numeric values, and the result always is numeric
If a parent class has a constructor that takes parameters what must the child constructor do, if anything at all?
It must call that parents constructor with super().
short s = (short)9; int i = 8; s+=i; Will this compile,if so what is the output?
It will compile because += and other operators like that do a cast. So s+=i; is s = (short)(s+i);
uneditable JTextField
JTextField in which the user cannot type values or edit existing text. Such JTextFields are often used to display the results of calculations.
Can you make a constructor final?
No, constructor can't be final.
heap sort
O(nlog2n) comparisons; consists of two phases, the construction and extraction phase
Reference Assignment
Once a String object has been created, neither its value nor its length can be changed (it's immutable) However, its reference variables can change
Which of the following about Java arrays is true? (i) Array components must be of the type double. (ii) The array index must evaluate to an integer.
Only (ii)
When can super() be called.
Only the FIRST line of the constructor.
________ is a program that runs on a computer to manage and control a computer's activities.
Operating system
logical operators
Operators (&&, ||, &, |, ^ and !) that can be used to form complex conditions by combining simple ones.
Task (ANT)
Piece of code that can be executed - can have multiple attributes (arguments) name: name of task <name attribute1="value1" attribute2="value2"...>
System.out.println("Hello")
Prints Hello to console on a new line.
Inheritance*
Process where one object acquires the properties of another.
Suite of tests
Run multiple test classes as a single test @RunWith(Suite.class) @Suite.SuiteClasses({class_name, ...})
What happens when their is no main?
Runtime Error
semicolon ( ; )
The character used to indicate the end of a Java statement.
What is classloader?
The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.
What will be the initial value of an object reference which is defined as an instance variable?
The object references are all initialized to null in Java.
If you print an object what will be printed?
The objects toString method.
icon property
The property that specifies the file name of the image displayed in a JLabel.
arithmetic operators
These operators are used for performing calculations.
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java in case of class.
How can you cast a polymorphic object?
To the object type or any of its subclasses.
argument
Values inside of the parentheses that follow the method name in a method call are called ____(s).
What happens if you declare a class constructor to have a void return type?
You'll likely receive a syntax error
Program control
____ refer(s) to the task of executing an application's statements in the correct order.
Mutator method
a method that modifies the object on which the method is invoked
Interface
a reference type that provides a template for a contract bw one class and another. composed of method signatures which define the public interface of the implementing class
Every statement in Java ends with ________.
a semicolon (;)
what is a try/catch?
a try/catch block is used to catch exceptions - if the code in the try block throws an exception the rest of the try block is skipped and the catch block is run
In Java a variable may contain
a value or a reference
object
an instance of a class
white space
any sequence of only space, tab, and newline characters
ethernet
broadband technology, originally designed to operate at 10 Mbps using coaxial cable; uses the bus topology for LAN
8 bit integer
byte
class derived from another class?
class inherits from class
check exception
exception that compiler sees and need to be caught
Close Window (GUI)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
exception
indication that abnormal situation occurred
You are ____ required to write a constructor method for a class.
never
event listener
object that includes a method that gets executed in response to generated events
parameter passing
specifying expressions to be arguments for a method when it is called
Autoboxing is
the automatic conversion of a wrapper object to/from its corresponding primitive type
Define the keyword "extends"
used to create a subclass for an existing class.
Is the instance block executed before the constructor?
Yes
An action
In an activity diagram, a rectangle with curved sides represents _____.
What is a cloneable interface and how many methods does it contain?
- It is not having any method because it is a TAGGED or MARKER interface.
What value will z have if we execute the following assignment statement? float z = 5 / 10;
z will equal 0.0
What is a Java Bean?
- A Java Bean is a software component that has been designed to be reusable in a variety of different environments.
What is meant by Inheritance and what are its advantages?
- Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.
ANT
- specifies how to build something. - require configuration file build.xml - A depends on B means that B needs to occur before A. - if B compiled then A will compile immediately.
loosly coupled
- system is one in which each of its components has, or makes use of, little or no knowledge of the definitions of other separate components
Levels of synchronization
1. None 2. Class methods only (ensure class variables thread safe) 3. Class and Instance methods - protect integrity of all fields - allow different threads share objects - all fields protected from simultaneous access and modification
char[][] array1 = new char[15][10]; What is the value of array1[3].length? 1. 15 2. 10 3. 2 4. 0
2. 10
/
2. The ________ operator performs division.
Compiler
2. The __________ converts a .java file to a .class file.
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] > a[x]) x = i; System.out.println(x); 1. Finds the position of the smallest value in a. 2. Sums the elements in a. 3. Counts the elements in a. 4. Finds the position of the largest value in a.
4. Finds the position of the largest value in a.
Compiler
4. Syntax errors are found by the ____.
long
64 bit
input JTextField
A JTextField used to get user input.
newline
A character that is inserted in code when you press Enter.
use of constructors in new instances
A constructor is a special method whose purpose is to construct and initialize objects
block
A group of code statements that are enclosed in curly braces ({ and }).
String
A sequence of characters that represents text information.
integer
A whole number, such as 919, -11 or 0 (not a decimal or fraction)
keyword
A word that is reserved by Java. These words cannot be used as identifiers. Also called *reserved word*.
Note that the Unicode for character A is 65. The expression "A" + 1 evaluates to ________.
A1
git commit
Commits staged files to Repo.
break mode
Debugger mode the application is in when execution stops at a breakpoint.
How can objects be ready for garbage collection(name three ways)?
By setting an object to null, setting an object to another object or setting it to a NEW object.
GUI
Graphical User Interface
bytecode
Instructions for the Java virtual machine
If a byte is multiplied by a short and set to a value what must that value be?
Int
iterator()
Iterator<String> iter = names.iterator(); while(iter.hasNext()){ System.out.println(iter.next()); }
format
Method ____ of DecimalFormat can display double values in a special format, such as with two digits to the right of the decimal point.
Consider the following declaration. double[] sales = new double[50]; int j; Which of the following correctly initializes all the components of the array sales to 10. (i) for (j = 0; j < 49; j++) sales[j] = 10; (ii) for (j = 1; j <= 50; j++) sales[j] = 10;
None of these
Expressions
Order of operations is applied: Multiplication, division, and remainder are evaluated before addition, subtraction, and string concatenation Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order Assignment operator is last
Executable
Pseudocode usually only describes ____ lines of code.
Batch processing (JDBC)
Reduce overhead by executing a large number at once.
Does constructor return any value?
Technically it returns the constructed object
More About System.out
The System.out object represents a destination (the monitor screen) to which we can send an output The System.out object provides another service in addition to println The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line
DecimalFormat
The class used to format floating-point numbers (that is, numbers with decimal points).
What is wrong with the following method call? displayValue (double x);
The data type of the argument x should not be included in the method call
The header of a value-returning method must specify this.
The data type of the return value
What is the purpose of the Java garbage collection?
The garbage collection is used to discard any not used data.
message dialog
The general name for a dialog that displays messages to users.
straight-line form
The manner in which arithmetic expressions must be written so they can be typed in Java code.
The _ statement executes until its loop-continuation condition becomes false.
While
________ is an operating system.
Windows XP
this.field
accesses an instance variable in the current class
unchecked exception
exceptions that are not caught by the compiler subclass of runtime
A classification hierarchy represents an organization based on _____________ and _____________.
generalization and specialization
Collection
represents a group of objects
sort-in-place
use same same amount of memory space when sorted
What is an accessor?
ways to get variables from class
char[][] array1 = new char[15][10]; How many dimensions are in the array above? 1. 3 2. 2 3. 1 4. 0
2. 2
int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the value of num.length in the array above? 1. 0 2. 100 3. 99 4. 101
100
try-catch control statement
exception control statement; statements are executed in the try block, when an exception is thrown, catch block is executed and rest of try block ignored
Which of the following Applet methods is called automatically when the applet is first loaded? 1) Applet (the Applet's constructor) 2) init 3) start 4) getCodeBase 5) getImage
init
Suppose a Scanner object is created as follows: Scanner input = new Scanner(System.in); What method do you use to read an int value?
input.nextInt();
instance data value
instances of the same class will possess the same set of data values
int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the data type of the array above? 1. num 2. int 3. char 4. list
int
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } What is the return type of the method above?
int
Consider a sequence of method invocations as follows: main calls m1, m1 calls m2, m2 calls m3 and then m2 calls m4, m3 calls m5. If m4 has just terminated, what method will resume execution?
m2
control statement
manipulate the sequence/order of execution of program statements; selection and repetition
What does pass by value mean?
means the called functions' parameter will be a copy of the callers' passed argument.
The word println is a(n)
method
class method
method defined for a class
instance method
method defined for an object
The behavior of an object is defined by the object's
methods
Add and assign operator
+=
What are wrapper classes?
- Wrapper classes are classes that allow primitive types to be accessed as objects.
subclass
- inherits from parent class
subtract and assign operator
-=
Binary numbers are composed entirely of
0s and 1s
Which array initializations are illegal? 1// int[] arr = new int[]; 2//int []arr = new int[5]; 3// int[][] arr = [1][4]; 4// int arr[][] =new int [][2]; 5// int arr[][] = new int[2][]; 6//int arr = new int[2]; 7//int[][] arr = new[5]{1,2,3};
1,3,4,6,7
double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} How many rows are in the array above? 1. 4 2. 0 3. 2 4. 3
1. 4
Refactoring Techniques
1. Extract Method 2. Extract Class 3. Rename 4. Move class 5. Replace conditional with Polymorphism 6. Decompose conditional 7. Encapsulate collection 8. Replace error code with exception 9. Split Loop
Version control principles
1. The Lock 2. The Merge
Valid Identifier
1. The name of a variable must be a ____.
The inside block, which is contained entirely within an outside block, is referred to as ____. 1. nested 2. out of scope 3. ambiguous 4. a reference
1. nested
Picture elements
10. Pixels are ____.
Assuming a=3, the values of a and b after the assignment b=a-- are _____.
2, 3
What is the value of (double)(5/2)?
2.0
Which of the following assignment statements is incorrect? (Choose all that apply.) 1) i = j = k = 1; 2) i = 1; j = 1; k = 1; 3) i = 1 = j = 1 = k = 1; 4) i == j == k == 1;
3) i = 1 = j = 1 = k = 1; 4) i == j == k == 1;
setTitle
3. Use ____ to set the text that appears on a JFrame's title bar.
A(n) ____ variable is known only within the boundaries of the method. 1. instance 2. double 3. local 4. method
3. local
24 % 5 is ________.
4
If a, b, and c are int variables with a = 5, b = 7, c = 12, then the statement int z = (a * b - c) / a; will result in z equal to
4
Size and location of component
6. The bounds property controls the ____.
Not changed
6. When a value is read from memory, that value is ____.
6 bits can be used to represent ________ distinct items or
64
Note that the Unicode for character A is 65. The expression 'A' + 1 evaluates to ________.
66
setText
7. A Jlabel component displays the text specified by ____.
Greater than
>
Greater than or equal to
>=
comment
A ____ begins with two forward slashes (//).
Transfer of control
A ______ occurs when an executed statement does not directly follow the previously executed statement in the written application.
When a method tests an argument and returns a true or false value, it should return
A boolean value
state button
A button that can be in the on/off (true/false) state, such as a CheckBox.
JOptionPane
A class that provides a method for displaying message dialogs and constants for displaying icons in those dialogs.
end-of-line comment
A comment that appears at the *end of a code line*.
full-line comment
A comment that appears on a line by itself in source code.
Loop-Continuation Condition
A condition used in a repetition statement (such as while) that repeats only while the statement is true.
Enumeration
A data type that is described by using a list of ordered values.
A debugger command that is used to examine the values of variables and expressions.
By default what is this considered - 12.21?
A double.
source code file
A file with a .java extension. These files are editable by the programmer, but are not executable.
What is blank final variable?
A final variable, not initalized at the time of declaration, is known as blank final variable.
Header
A line of text at the top of a JTextArea that clarifies the information being displayed.
String.valueOf
A method that converts a numeric value (such as an integer) into text.
String.equals
A method that evaluates whether a String contains specific text specified.
Instance Variable
A non static field - a variable that applies only to the instance of the class in which it is instantiated.
floating-point number
A number with a decimal point, such as 2.3456, 0.0 and -845.4680
String literal
A sequence of characters within double quotes.
What is a stream (in the context of the new Java 8 Collection API)?
A sequence of elements supporting sequential and parallel aggregate operations.
book-title capitalization
A style that capitalizes the first letter of each significant word in the text (for example, Calculate the Total).
white space
A tab, space or newline is called a(n) _____.
Variables
A variable is a name for a location (a chunk) in memory that holds a value (a fixed type of data) Variables come in two flavors: primitive and reference primitive: integer (such as 1, 2,...), floating point number (such as 1.2, 3.5, etc.), boolean (true or false) and char (such as 'A', 'B',...) reference: "address" of an object that resides in memory A variable declaration specifies the variable's name and the type of information that it will hold
Constant
A variable whose value cannot be changed after its initial declaration is called a _____.
constant
A variable whose value cannot be changed after its initial declaration.
Turing machine
A very simple model of a computing agent proposed by Alan Turing that is used in theoretical computer science to explore computability of problems
Algorithm
A(n) ___ is a procedure for solving a problem in terms of the actions to be executed and the order in which these actions are to be executed.
The value of the last element in the array created by the statement int[] ar = new int[3]; is : A. 0 B. 1 C. 2 D. 3
A. 0
Define the keyword "protected"
Able to be modified by the class, package, and subclass. But not the world.
++ (unary increment operator)
Adds one to an integer variable.
ASCII
American Standard Code for Information Interchange, which encodes 128 characters from 8-bits (binary)
JPS
An HTML page in which Java is invoked.
Class
An abstract description of a thing.
What is an accessor?
An accessor is a method that returns the value of a property of a dto - referred to as a 'getter'
method
An application segment containing statements that perform a task.
Declaration with Initialization
An assignment statement changes the value of a variable The assignment operator is the = sign If you wrote keys = 80; The 88 would be overwritten You should assign a value to a variable that is consistent with the variable's declared type
logic error
An error that does not prevent the application from compiling successfully, but does cause the application to produce erroneous results when it runs.
operand
An expression that is combined with an operator (and possibly other expressions) to perform a task (such as multiplication).
By default what is this considered - 12?
An int.
binary operator
An operator that requires two operands.
Loop
Another general name for a repetition statement.
argument
Any values the method needs to carry out its task, and are supplied in the method call.
JTextArea method _ adds text to a JTextArea.
Append
The last element in the array created by the statement int[] ar = { 1, 2, 3 }; is : A. ar[3] B. ar[2] C. ar(3) D. ar(2)
B. ar[2]
How can a method send a primitive value back to the caller?
By using the return statement
Java is similar in syntax to what other high level language?
C++
How do you make an object call a method and then cast?
Call the method and put parenthesis with the class type next to it. Ex: (B)aa.m1();
Methods rule (subtypes)
Calls to the subtype methods must behave like calls to the corresponding supertype method.
Decimal, Text
Class DecimalFormat is used to control how ____ numbers are formatted as ____.
JComboBox
Combine text field and drop down list. Text field can be editable.
Refactor - decompose conditional
Complicated if-then-else: extract methods from the condition, then part, then else parts. if (date.before(SUMMER_START)) charge = quantity * winterRate + winterService Charge; else charge quantity * summerRate BECOMES if(notSummer(date)) charge = winterCharge(quantity) else charge = summerCharge(quantity)
JLabel
Component that displays a text or an image that the user cannot modify
Final
Constants are declared with keyword ____.
right brace (})
Denotes the end of a *block of code*.
Glass box steps
Ensure 1. Statement coverage (every statement is executed at least once. 2. Branch coverage (each condition is evaluated at least once). 3. Path coverage (all control flow paths are executed at least once).
comment (//)
Explanatory text that is inserted to improve an application's readability.
Java Program Structure
In the Java programming language: -A program is made up of one or more classes defined in source files (with the .java extension) -A class contains one or more methods -A method contains program statements
What happens when you divide a double or a float by 0?
Infinity
If I don't provide any arguments on the command line, then the String array of Main method will be empty or null?
It is empty. But not null.
What is the reference type of a polymorphic object instance?
It is the declaration of the instance. The stuff before the equals sign.
What is the function of a frame's pack method?
It sets the size appropriately for display
The expression "Java " + 1 + 2 + 3 evaluates to ________.
Java 123
________ contains predefined classes and interfaces for developing Java programs.
Java API
What is the JDK?
Java Development Kit.
________ consists of a set of separate programs for developing and testing Java programs, each of which is invoked from a command line.
Java JDK
JSE API
Java Standard Edition Application Programming Interface Libraries
Java compiler translates Java source code into ________.
Java bytecode
Class=Blueprint
Just like how one blueprint (class) is used to create several similar, but different houses (objects)
final
Keyword that precedes the data type in a declaration of a constant.
Which are valid array declarations? 1// arr[] int; 2// arr[] arr1; 3//arr[][5] arr2; 4//arr[][] arr4 = new arr[][];
Line 2, array declarations are not initialized yet.
The ________ method returns a raised to the power of b.
Math.pow(a, b)
Expressions that use logical operators can form complex conditions
Max +5, then less than sign, then the logical not and logical & operators Think of it like true always wins
In a UML activity diagram, a(n) _ symbol joins 2 flows of activity into 1 flow of activity.
Merge
Define the keyword "void"
Method that does not return.
Are arrays used only for primitives?
No
Can an abstract method be final?
No
Will System.out.println((char)4) display 4?
No
Is it legal to use .super in static methods?
No - .this and .super cannot be used or a compilation error will happen.
What is covariant return type?
Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type.
Danger of using GIT
Only one repository.
What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
git push
Publishes committed local files to remote repo.
Commit
Publishes file to GIT directory (Repository). Making it accessible by team. Use 'git commit -m "Message"'.
How do you make an object cast first and then call a method?
Put the class in parenthesis next to the method and surround that in parenthesis. Ex: class B extends A{} A aa = new B(); ((B)aa.m1())
Random Access Memory
RAM; 3 characteristics: 1 - memory divided into cells and each cell has an address. 2 - All accesses to memory are at a specific address; must get complete cell. 3 - Time it takes to fetch/store a cell is the same for all cells.
Final
Retains the same value throughout the program
executeUpdate (SQL command)
Returns number of rows affected. Use for INSERT, UPDATE or DELETE. rows = st.executeUpdate("UPDATE names SET age = 21 WHERE name = 'John Howard'");
Logical AND and Logical OR
Since && and || each have two operands, there are four possible combinations of conditions a and b
debugger
Software that allows you to monitor the execution of your applications to locate and remove logic errors.
@Test(timeout = T)
Test fails if runs longer than T milliseconds.
Variable
The name (an identifier) given to a container that holds values in a Java program
String Concatenation Operator
The name for a plus (+) operator that combines its two operands (Strings) into a single String.
editable property
The property that specifies the appearance and behavior of a JTextField (whether the user can enter text.)
location property
The property that specifies where a component's upper-left corner appears on the JFrame.
inheritance (in Java)
The relationship between a more general superclass and a more specialized subclass
JDBC
The set of classes which allows easy access to databases.
String Concatenation
The string concatenation operator (the plus symbol) is used to append one string to the end of another. In the case of a long string, you must use concatenation to break it across multiple lines.
setText
The text on a JLabel is specified with _____.
JCheckBox text
The text that appears alongside a JCheckBox.
Type casting
The type of a variable into another type.
How is an instance block wrote?
With two brackets outside of the main method.
What are Wrapper classes?
Wrapper classes are objects of primitives. Every primitive has a wrapper class.
Are StringBuffer/StringBuilder final classes?
Yes
Can we override the overloaded method?
Yes.
set
You can modify the value of a variable by using the debugger's ____ command.
Java Reserved Words
You cannot use use reserved words for your own names (Java identifiers)
Consider having three String variables a, b, and c. The statement c = a + b; also can be achieved by saying
c = a.concat(b);
Layout managers are associated with
containers
Using getCurrencyInstance( ) formats a variable, automatically inserting
decimal point for cents dollar sign percent sign
public
declares the function can be called outside of the class
Depend (ANT)
determines which classfiles are out of date with respect to their source.
Enum
enumerated type of class. - list of constants. - use when need predefined list of values that do not represent values of textual data
checked exception
exception that is check at compile time
runtime exception
exception the happen during the running of the program
exception propagator
exception thrower that does NOT include a matching catch block; passes on the exception to another method
Which phase of the fetch-decode-execute cycle might use a circuit in the arithmetic-logic unit?
execute
zero-indexing
first element begins at zero as opposed to one
memory
functional unit of a computer that stores and retrieves the instructions and data being executed
overloading a method
giving more than one meaning to a method name
A ____________ relationship exists between two classes when one class contains fields that are instances of the other class.
has-A
Memory Address Register (MAR)
holds the address of the cell to be fetched or stored
this()
invokes the constructor.
Which JDK command is correct to run a Java application in ByteCode.class?
java ByteCode
Which library package would you import to use NumberFormat and DecimalFormat?
java.text
sentinel-controlled loop
loop body is executed until a certain condition is met
Computer can execute the code in ________.
machine language
When executing a program, the processor reads each program instruction from
main memory
run()
main method for an individual thread
encapsulate
makes class variable private and give access with public methods
static
means only one copy exists of the field or method and it belongs to the class not an instance. Its shared between all instances of the class.
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is a valid call to the method above?
minimum(5, 4);
The relationship between a class and an object is best described as
objects are instances of classes
off-by-one error
one fewer iteration or one too many
Which of the following is a legal Java identifier? 1) 1ForAll 2) oneForAll 3) one/4/all 4) 1_4_all 5) 1forall
oneForAll
Private
only accessible if in same class.
The advantages of the DecimalFormat class compared with the NumberFormat class include
only precise control over the number of digits to be displayed and control over the presence of a leading zero
abstract method
only the method header but no body
What does the term overloading mean?
overloading a method is to declare two or more methods of the same name with different parameters
If you want to draw a red circle inside of a green square in an applet where the paint method is passed a Graphics object called page, which of the following sets of commands might you use?
page.setColor(Color.green); page.fillRect(50, 50, 100, 100); page.setColor(Color.red); page.fillOval(60, 60, 80, 80);
Which modifier is used to specify that a method cannot be used outside a class?
private
private
private members can only be accessed by other members of their own class
Methods in interfaces are automatically what?
public and abstract.
Which of the following is NOT a modifier?
return
Program
set of classes, one with a 'main' method (.java)
JTextArea method _, when called with an empty string, can be used to delete all the text in a JTextArea.
setText
A Java program is best classified as
software
arithmetic/Logic Unit (ALU)
subsystem that performs such mathematical and logical operations as addition, subtraction, and comparison for equality; registers, interconnections between components, and ALU circuitry
Map
the interface for Hashmap and other map types
What are aggregate operations?
where the values are grouped together as input on certain criteria to form a single value of more significant meaning
While loop
while(insert argument here) { insert code here }
Multiplication operator
*
Subtraction operator
-
Checkout
- Make a local copy of code/file. - Checkout from Version Database.
Starvation
- Some threads allowed to be greedy and others starved of resources, making no progress So some of the philosophers eat everything others get nothing.
Generics
- accept another type as a parameter - collections <E> <X>
Which of the following are correct names for variables according to Java naming conventions? (Choose all that apply.) 1) radius 2) Radius 3) RADIUS 4) findArea 5) FindArea
1) radius 4) findArea
int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the index number of the last component in the array above? 1. 99 2. 100 3. 0 4. 101
1. 99
Name and type
3. Every variable has a ________.
int
32 bit
What will be displayed by this command: System.out.println(Math.pow(3, 3-1));
9
variable
A location in the computer's memory where a value can be stored for use by an application.
Package
A logical collection of associated classes, which in its own directory, subdirectory be saved.
Public
Accessible by all.
All @param tags in a method's documentation comment must
Appear after the general description of the method
The condition exp1 || exp2 evaluates to false when ___.
Both are false.
Which of the following is not a benefit derived from using methods in programming? A. Code reuse B. Problems are more easily solved C. Simplifies programs D. All of the above are benefits
D. All of the above are benefits
If null is on the left of the instanceof operator what will the answer always be?
False
What will be printed if null was on the left side of the instance of operator?
False
Types of Maps
HashMap: unordered, use for max speed TreeMap: ordered by key LinkedHashMap: inseretion ordered.
Types of sets
HashSet<E>: unordered TreeSet<E>: ordered based on value LinkedHashSet<E> : insertion ordered
The line of text that is added to a JTextArea to clarify the information that will be displayed in tabular format is called a _____.
Header
How do you make a constant.
Make a variable with final and static modifiers.
Is this valid code? while(false){ System.out.println("Hey"); }
No, it will cause a compilation error because of unreachable code. If their is a boolean that is false and it is put inside the parenthesis it fine.
What if I write static public void instead of public static void?
Program compiles and runs properly.
-- (unary decrement operator)
Subtracts one from an integer variable.
Suppose you define a Java class as follows: public class Test{ } In order to compile this program, the source code should be stored in a file named
Test.java
Glass box
Testing code (can see code)
Black box
Testing to specifications (code unseen)
If you print THIS in system.out.println, what will print?
That classes toString.
What does it mean if a string is immutable?
That it cannot be changed once it is created.
Escape Sequence
The combination of a backslash and a character that can represent a special character, such as a newline or a tab.
javac command
The command that compiles a source code file (.java) into a . class file.
extends keyword
The keyword the specifies that a class inherits data and functionality from an existing class.
class keyword
The keyword used to begin a class declaration.
actionPerformed
The kind of event that occurs when a JButton is clicked.
content pane
The portion of a JFrame that contains the GUI components.
Classes contain methods that determine the behaviors of objects
Two common usages of methods: -change the values of the instance variables, e.g., making deposits to a bank account object should change its current balance -methods can behave differently based on the values of the instance variables, e.g., playing a "Darkstar" song object and a "My Way" song object should be somehow different...
Input Tokens
Unless specified otherwise, white space is used to separate the tokens (elements) of the input White space includes space characters, tabs, new line characters The next method of the Scanner class reads the next input token and returns it as a string Methods such as nextInt and nextDouble read data of particular types (int and double)
JInternalFrame
Use for Multiple Document Interface (MDI)
Escape Sequence
What if we wanted to print the quote character? The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\) System.out.println ("I said \"Hello\" to you.");
What is overloading?
When a method has the same name but different signature. EX: void m1() int m1(int a) void m1(int a, int b)
instance of a class
When you construct an object from a class ex Dog jasmine=new Dog();
declaring
When you specify the type and name of a variable to be used in an application, you are ____ a variable.
What output is produced by the following?
X: 25 Y: 65 Z: 30050
Declares arrays
[]
What is an arrayList
a inherently ordered dynamic data structure that implements the List interface and extends AbstractList
Formal parameters of primitive data types provide ____ between actual parameters and formal parameters.
a one-way link
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements replaces the last object in the collection with element?
a.set(3, element);
binary
base-two numeral system; usually using 1s and 0s
Comments should
be insightful and explain what the instruction's intention is
true or false
boolean
What is this()?
calls a constructor in the same class?
analysis
feasibility study; result is a requirements specification
Consider a method defined with the header: public void foo(int a, int b). Which of the following method calls is legal? 1) foo(0, 0.1); 2) foo(0 / 1, 2 * 3); 3) foo(0); 4) foo( ); 5) foo(1 + 2, 3 * 0.1);
foo(0 / 1, 2 * 3);
array
holds a fixed number of values of a given type
count-controlled loop
loop body is executed a fixed number of times
posttest loop
loop body is executed at least once, then condition is tested
To define a class that will represent a car, which of the following definitions is most appropriate? 1) private class car 2) public class car 3) public class Car 4) public class CAR 5) private class Car
public class Car
Basic Enum class
public enum Level { HIGH, MEDIUM, LOW } //Assign it Level level = Level.HIGH;
Heap
stores java object
Given the method heading public void strange(int a, int b) and the declaration int[] alpha = new int[10]; int[] beta = new int[10];
strange(alpha[0], alpha[1]);
instantiation
when instantiating a class, constructing an object of that class
What is the printout of the following code: double x = 5.5; int y = (int)x; System.out.println("x is " + x + " and y is " + y);
x is 5.5 and y is 5
Which of the following would return the last character of the String x? 1) x.charAt(0); 2) x.charAt(last); 3) x.charAt(length(x)); 4) x.charAt(x.length( )-1); 5) x.charAt(x.length( ));
x.charAt(x.length( )-1);
The String class' compareTo method
yields 0 if the two strings are identical
Which of the following is not syntactically legal in Java? 1) public class Foo 2) System.out.println("Hi"); 3) { } 4) s t a t i c main(String[ ] args) 5) only System.out.println("Hi"); is legally valid, all of the rest are illegal
4) s t a t i c main(String[ ] args)
________ is a device to connect a computer to a local area network (LAN).
NIC
Can their be any duplicate cases in a switch statement?
No
Can you use continue in a switch?
No
Can you use long in a switch statement?
No
If you want to output the text "hi there", including the quote marks, which of the following could do that?
System.out.println("\"hi there\"");
How is the ternary operator structured?
logical-expression? expr1:expr2; expr1 gets executed if logical-expression is true, if not expr2 gets executed. If it is being set to a variable the value of what expression gets executed gets put into that variable.
In order for a computer to be accessible over a computer network, the computer needs its own
network address
Do you have to initialize a local variable?
Yes
Can you declare the main method as final?
Yes, such as, public static final void main(String[] args){}.
What is a mutator?
a mutator is a method that changes the value of a field in a class - often called a 'setter'
An API is
an Application Programming Interface
What is garbage collection?
attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program.
If you pass the first element of the array ar to the method x() like this, x(ar[0]); the element ar[0] :
cannot be changed by the method x()
To use JOptionPane in your program, you may import it using:
import javax.swing.JOptionPane; import javax.swing.*;
cohesive
single responsibility class dose well define job
For a computer to communicate over the Internet, it must use
the combined TCP/IP protocol
encapsulation
the hiding of implementation details and providing methods for data access
What does the static keyword mean?
the static keyword is used to define a field or method that will not change across all instances of that class - it defines a class level element that can be accessed without instantiating an object of that class
Can you use this() and super() both in a constructor?
No. Because super() or this() must be the first statement.
The condition Exp1 ^ exp2 evaluates to true when ____.
Either exp1 is false and exp2 is true or exp1 is true and exp2 is false.
What can't a method not do when it is final?
It cannot be overloaded.
Is the Java language pass by value or pass by reference?
java is passed by value.
size property
Property that specifies the width and height, in pixels, of a component.
setText
Sets the text property of the JTextArea component.
The UML decision/merge symbols can be distinguished by _.
The number of flowlines entering or exiting the symbol and whether or not they have guard conditions. (Both of the above)
Write an if then statement where i=10
if(i=10){ //do stuff }
int value
The variable type that stores integer values.
% (remainder operator)
This operator yields the remainder after division.
How is the import keyword used?
the import keyword is used to let the compiler know that the class is going to use an external package
SuperClass
the parent or supertype of a class
scope
the part of a program in which a variable can be accessed
What does the public keyword mean?
the public access modifier means that all classes have access to that element
To determine the number of valid elements in an ArrayList, use:
the size() method
local variable
variable defined within a method that cannot be accessed outside of that method
Accessor method
method that accesses an object and returns some information about it, without changing the object
unchecked exceptions
runtime exceptions; unchecked at compile time and detected only at runtime
3 different groups of patterns
1. Creational: managing the creation of objects 2. Structural: provide a more workable interface for client code. 3. Behavioural: managing common interactions
Type parameter
<X> ...of type X. <String> is of type String. <Tree> is a Tree object
________ is the Java assignment operator.
=
UML Diagrams - list the behavior diagrams
Behavior Diagrams - STIACUS Sequence Timing Interactive Activity Communication Use Case State
this
Denotes current object. Resolves ambiguity problems. this.tree = tree;
left brace ({)
Denotes the beginning of a *block of code*.
JOptionPane.ERROR_MESSAGE
Icon containing a stop sign, alerts the user of errors or critical situations.
The lifetime of a method's local variable is
Only while the method is executing
What does a for loop with two semicolons do(for(;;))?
Runs infinitly
The Dot Operator
The dot operator (.) gives you access to an object's instance variables (states) and methods (behaviors) It says: use the Dog object referenced by the variable myDog to invoke the bark() method Think of a Dog reference variable as a Dog remote control When you use the dot operator on an object reference variable, it is like pressing a button on the remote control for that object
Escape Character
This character (\) allows you to form escape sequences.
A JCheckBox is selected when the isSelected method returns __.
True
Define the keyword "catch"
Used to catch exceptions and tell the application to do something else.
computer network
a set of independent computer systems connected by telecommunication links for the purpose of sharing information and resources
instance variable
a variable defined in a class for which every object of the class has its own value
bit
binary digit; smallest unit of information, either 0 or 1; n bits has 2^n possible values
What are the only things you can use in switch statements?
byte, short, int, char, string and enum
Postdecrement
counter--
JOptionPane is a class that provides GUI
dialog boxes
exception
error condition that can occur during the normal course of program execution; exception is thrown
32 bit real number
float
event-driven programming
flow of execution is determined by events;
A variable whose scope is restricted to the method where it was declared is known as a(n)
local variable
syntax
rules that define how to form instructions in a particular programming language; grammer
16 bit integer
short
override
used by a subclass for methods from the parent class
override
when a child class has the same method name as the parent class, the child's method body will be implemented
What does it take to create and use and object?
- 2 classes. 1 class for the type of object (Dog, ClarmClock,Television) and another class to test your new class -the tester class is where you put the pain method and in that main() method you create access object of your new class type. -the test has 1 job: try out the methods and vairables of your new object class type
What is an event and what are the models available for event handling?
- An event is an event object that describes a state of change in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two types of models for handling events and they are: a) event-inheritance model and b) event-delegation model
Deadlock
- Blocked waiting for a resource held by another blocked thread - all philosophers pick up the left fork at the same time before any can pick up the right fork - No progress possible.
Pass by reference
- Objects and arrays - Changes affect original as it is given access to the address not just a copy.
why is it a good idea to split into layers ?
- read it easer and debug easier
What is the value of alpha[4] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 2; for (j = 1; j < 5; j++) alpha[j] = alpha[j - 1] + 3; 1. 11 2. 14 3. 5 4. 8
2. 14
What is the last index of the string TEXT?
3. The first letter starts with index 0.
Define the keyword "abstract"
Abstract is assigned when you want to prevent an instance of a class from being created.
How many constructors can a class have? 1. Any number 2. 0 3. 1 4. 2
Any number
What is the instanceof operator?
Checks if one objects is a instance of another.
Assume that you have an ArrayList variable named a containing many elements. You can rearrange the elements in random order by writing:
Collections.shuffle(a);
cont
Debugger command that resumes program execution after a breakpoint is reached while debugging.
Bit Permutations
Each additional bit doubles the number of possible permutations Each permutation can represent a particular item N bits can represent up to 2^N unique items, so to represent 50 states, you would need 6 bits: 1 bit: 2^1 = 2 items 2 bits: 2^2 = 4 items 3 bits: 2^3 = 8 items 4 bits: 2^4 = 16 items 5 bits: 2^5 = 32 items Five bits wouldn't be enough, because 2^5 is 32. Six bits would give us 64 permutations, and some wouldn't be used.
What does the substring method written like this return - stringName.subString(1)?
Everything from index 1 and up(Inclusive)
What is composition?
Holding the reference of the other class within some other class is known as composition.
case sensitive
Identifiers with identical spelling are treated differently if the capitalization of the identifiers differs. This kind of capitalization is called _____.
What is method overloading?
If a class have multiple methods by same name but different parameters, it is known as Method Overloading. It increases the readability of the program.
Dangers of threads
Introduce ASYNCHRONOUS BEHAVIOUR - multiple threads access same variable/storage location can become unpredictable. - only one should alter data at a time.
________provides an integrated development environment (IDE) for rapidly developing Java programs. Editing, compiling, building, debugging, and online help are integrated in one graphical user interface.
Java IDE
This part of a method is a collection of statements that are performed when the method is executed.
Method body
Which of the following could be used to instantiate a new Student s1? 1) Student s1 = new Student( ); 2) s1 = new Student( ); 3) Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33); 4) new Student s1 = ("Jane Doe", "Computer Science", 3.333, 33); 5) new Student(s1);
Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33);
Method overriding
Subclass method can override methods from abstract or concrete classes. Within a subclass an override method in the super can still be called with super.method().
Hashcode (GIT)
Uniquely identify each commit.
setText
Use _____ to set the text on the face of a JButton.
interface
a collection of abstract methods
HashMap
dynamic data structure where a set of keys holds references to objects
op code
operation code; unique unsigned integer code assigned to each machine language operation recognized by hardware
What is x after the following statements? int x = 1; x *= x + 1;
x is 2
Take remainder and assign operator
%=
Software Patterns
- Reusable solution to common problem. - Description/Template
Local Repository
- Stored on local computer. - Individual checks out version from Version database.
setBackground
1. Use ___ to specify the content pane's background color.
Methods that require you to use an object to call them are called ____ methods. 1. accessor 2. instance 3. internal 4. static
2. Instance
word is spelled incorrectly; parentheses is omitted.
6. Syntax errors occur for many reasons, such as when a(n) ____.
What is the difference between a class and an object
A class is a blueprint for an object. tells the virtual machine how to make an object. you might use a button class to make dozens of different buttons, each button might have its own color, size, shape, label,
JButton component
A component that, when clicked, commands the application to perform an action.
What is this automatically? 45e7
A double
When dividing what must the variable be put into?
A double because division automatically sets it to a double.
What is a package?
A folder where your classes are stored
Refactor - replace error code with exception
A method returns a special code to indicate an error - throw an exception instead.
While Statement
A specific control statement that executes a set of body statements while a loop continuation condition is true.
nested statement
A statement that is placed inside another control statement.
multiline statement
A statement that is spread over multiple lines of code for readability.
single-selection statement
A statement, such as the if statement, that selects or ignores a single action or sequence of actions.
What level of access to the properties and methods of the enclosing class does a static nested class have?
A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Charachter Strings
A string literal is represented by putting double quotes around the text examples: "I Rule!" "The World" "123 Main Street" "X" "" literal is an explicit data (constant) value used in a program Every character string is an object in Java, defined by the String class Every string literal represents a String object A string literal can contain any valid characters, including numeric digits, punctuation, and other special characters.
empty string ("")
A string that does not contain any characters.
event
An action that can trigger an event handler.
Which of the following would be a valid method call for the following method? public static void showProduct (int num1, double num2) { int product; product = num1 * (int)num2; System.out.println("The product is " + product); } A. showProduct(10.0, 4); B. showProduct(33.0, 55.0); C. showProduct(5.5, 4.0); D. showProduct(10, 4.5);
D. showProduct(10, 4.5);
Here is a loop that is supposed to sum each of the values in the array named ar : double sum = 0.0; for (int i=0; i < ar.length; i++) // ??? System.out.println(sum); What goes on the line containing ???? : A. i = sum + ar[i]; B. sum + ar[i]; C. sum = sum + i; D. sum += ar[i];
D. sum += ar[i];
how to store an object that you construct by storing it in a variable
Date birthday=new Date
clear
Debugger command that displays a list of all the breakpoints in an application.
Debugger command that displays the value of a variable when an application is stopped at a breakpoint during execution in the debugger.
Class variables
Declared with 'static' keyword. In class but not in methods. One per class - if it is set to 5 and an object changes it to 6 it will then be changed to 6 for all instances of the class.
Statement (JDBC)
Defines methods that enable send SQL commands and receive data from DB. Statement st = connection.createStatement(); connection.execute(); etc.
Definition of class
Describes the properties and behavior of a prototypical object. During runtime, the application creates individual instances of classes where the instances are called objects. For example: class - Book properties - title, author behaviors - checkOut(), checkIn() Then at runtime, the application creates a separate object for each book as they are requested by users.
String mutation example to put into Java
Even though we can't change String value or length, several methods of the String class return new String objects that are modified versions of the original
Events
Every action creates an event on Event Dispatch Thread. Actions = button click, mouse over etc.
Which of the following statements is correct? 1) Every line in a program must end with a semicolon. 2) Every statement in a program must end with a semicolon. 3) Every comment line must end with a semicolon. 4) Every method must end with a semicolon. 5) Every class must end with a semicolon.
Every statement in a program must end with a semicolon.
DASD
Every unit of information has a unique address but the time needed to access the information depends on its physical location and the current state of the device. Stands for direct access storage device.
How can exceptions be handled in Java?
Exceptions can either be thrown or handled using a try catch block.
The JOptionPane dialog icon typically used to caution the user against potential problems is the ____.
Exclamation point
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] > a[x]) x = i; System.out.println(x); 1. Finds the position of the largest value in a. 2. Sums the elements in a. 3. Finds the position of the smallest value in a. 4. Counts the elements in a.
Finds the position of the largest value in a.
Packages
For purposes of accessing them, classes in the Java API are grouped into packages
________is Architecture-Neutral.
Java
join (Threads)
Makes other thread/next thread wait until the first thread terminated. one.start(); two.start(); one.join(); three.start(); // Three has to wait on one
Is it legal to use .this in static methods?
No - .this and .super cannot be used or a compilation error will happen.
What happens if their is no default in a switch statement?
Nothing happens.
Define the keyword "private"
Only able to be modified inside the class.
What is an actual parameter?
The value passed into a method by a method call
If class B has variable v and class A does to, what happens? A a = new B(); a.v();
The variable of the reference type will be called even if it overriden.
Primitive Types
There are eight Primitive data types in Java Four of them represent integers • byte, short, int, long Two of them represent floating point numbers • float, double One of them represents a single character • char And one of them represents boolean values • boolean
assembly language
a low level programming language that implements symbolic representation of the numeric machine codes.
actual parameter
actual value or reference that is passed to a method or subroutine -> gary.transfer(200); 200 is the actual parameter
The first element in the array created by the statement int[] ar = { 1, 2, 3 }; is :
ar[0]
The last element in the array created by the statement int[] ar = { 1, 2, 3 }; is :
ar[2]
Arrays
are NOT collections. Do NOT: 1. support iterators 2. grow in size at runtime 3. are not threadsafe Primitive types of a fixed size.
What is arr1,arr2 and arr3? int[] arr,arr2[][],arr3;
arr is an array. arr2 is a triple array. arr3 is a triple array.
binary search
array must already be sorted; O(log2n) comparisons; search starts in the middle of the array and searches the array by halves
two-dimensional array
array with an array at each element in the array
What is specialization?
as opposed to generalization - specialization refers to the hierarchy of a superclass and subclass in which the superclass is always more inclusive than the subclass - the farther down the hierarchical chain, the more
What is the syntax of a sequence control flow example?
base = rate * hours; taxes = base * taxRate; net = base - taxes; count++; count--;
Why do computers use zeros and ones?
because digital devices have two stable states and it is natural to use one state for 0 and the other for 1.
machine language
binary instructions that are decoded and executed by the control unit
A method that has the signature void m(int[] ar) : A. can change the values in the array ar B. cannot change the values in the array ar C. can only change copies of each of the elements in the array ar D. None of these
can change the values in the array ar
Which of the following assignment statements is correct? (Choose all that apply.) 1) char c = 'd'; 2) char c = 100; 3) char c = "d"; 4) char c = "100";
char c = 'd'; char c = 100;
Class
class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions, methods).
To improve readability and maintainability, you should declare ________ instead of using literal values such as 3.14159.
constants
When you write an explicit ____ for a class, you no longer receive the automatically written version.
constructor
Example of three references and two object
d and c are aliases, because they both reference the same book
Given the following method header, which of the method calls would cause an error? public void displayValues(int x, int y)
displayValue(a,b); // where a is a short and b is a long
Transaction processing (JDBC)
e.g. Funds transfer commit() rollback() savepoint..
final
entity can not be changed
control unit
fetches from memory the next instruction to be executed, decodes it, and executes it by issuing appropriate command to ALU, memory, or I/O
According to Java naming convention, which of the following names can be variables? (Choose all that apply.) 1) FindArea 2) findArea 3) totalLength 4) TOTAL_LENGTH 5) class
findArea totalLength
Which of the following are storage devices? (Choose all that apply.) 1) floppy disk 2) hard disk 3) flash stick 4) CD-ROM
floppy disk hard disk flash stick
Write an endless for loop where i=10
for(i=10; i > 5; i++){ System.out.println(i); }
Things an object knows about itself are called ?
instance variables
mass storage
nonvolatile storage, information can be saved between shutdowns. The storage of large amounts of data in a persisting and machine-readable fashion.
an instance is another way of saying ____?
object
time complexity
quantifies the amount of time taken by an algorithm to run; commonly expressed using big O notation
The ability to directly obtain a stored item by referencing its address is known as
random access
Variable Declaration
stating the name of the variable coupled with its data type
switch statement
take a variable selects appropriate case for value
break statement
terminates switch statement; causes execution to continue from the statement following the switch statement
boolean expression
test condition
pretest loop
test is done before the execution of the loop body
Try catch exception block
try {... normal code} catch(exception-class object) {... exception-handling code}
StringTokenizer is a class in the java.util library that can divide a String based on some delimiter String (a delimiter is a separator). If the instruction StringTokener st = new StringTokenizer(str, "&&"); is executed, where str is some String, then st divides up str into separate Strings whenever
two ampersands are found
A Java character is stored in ________.
two bytes
An "alias" is when
two different reference variables refer to the same physical object
bubble sort
type of exchange sort; compare the first pair of elements(exchange if needed), compare the second pair, third, fourth, and so on until the end of the list; highest number guaranteed to be in the last place after first sort
boolean
type with possible values of true of false
Exceptions
undesireable events outside the 'normal' behaviour of a program. - recoverable (not always) - handled in method where occur or propagated to calling program
What is shadowing?
when a local variable has the same name as another variable in the same scope thus hiding the non local variable
25 % 1 is ________.
0
byte
8 bit, useful if memory an issue
Before
8. The expression to the right of the assignment operator (=) is always evaluated ____ the assignment occurs.
Components of a color
9. RGB values specify the ____.
Which of the following characters does not need to have an associated "closing" character in a Java program? 1) { 2) ( 3) [ 4) < 5) all of these require closing characters
<
Sets
- No Duplicates - Usually unordered
What does a contain after the following loop? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; for (int i = size; i > pos; i--) a[i - 1] = a[i]; size--; 1. {3, 7, 0, 0, 0, 0} 2. {0, 0, 0, 0, 0, 0} 3. {3, 7, 7, 0, 0, 0} 4. {1, 1, 1, 0, 0, 0}
{0, 0, 0, 0, 0, 0}
What does a contain after the following loop? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; for (int i = pos; i < size - 1; i++) a[i + 1] = a[i]; size--;
{1, 1, 1, 0, 0, 0}
Bitwise Or operator
|
Integer
unsigned int, 0 -> 2^31 -1
explicit parameter
a parameter of a method other than the object on which the method is invoked. The parameter explicitly fed to a method through the parenthesis.
Mistyping "println" as "printn" will result in
a syntax error
A variable comes into existence, or ____, when you declare it. 1. is referenced 2. comes into scope 3. overrides scope 4. goes out of scope
2. comes into scope
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] > a[x]) x = i; System.out.println(x); 1. Sums the elements in a. 2. Finds the position of the smallest value in a. 3. Finds the position of the largest value in a. 4. Counts the elements in a.
3. Finds the position of the largest value in a.
Methods that retrieve values are called ____ methods. 1. static 2. mutator 3. accessor 4. class
3. accessor
Assume you have a Student object and a Student variable named bill that refers to your Student object. Which of these statements would be legal? bill.name = "Bill Gates"; // I bill.setName("Bill Gates"); // II println(bill.getName()); // III bill.studentID = 123L; // IV println(bill.getID()); // V 1. II, III, IV, VI 2. IV, V 3. All of them 4. II, III, V 1 5. None of them
4. II, III, V
Parentheses
4. In Java, use ________ to force the order of evaluation of operators.
Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following sets of statements are valid (both syntactically and semantically) in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); 1. Both (i) and (ii) 2. Only (ii) 3. None of these 4. Only (i)
4. Only (i)
If a method in the superclass is declared protected, you may replace it in the subclass as long as the subclass method that you define: 1. has a different number, type, or order of parameters 2. has a different return type 3. is defined as protected or private 4. is defined as public or protected 5. is defined only as public
4. is defined as public or protected
Mutator methods typically begin with the word "____". 1. read 2. get 3. call 4. set
4. set.
.java
5. Java source code files have the extension ____.
What file is created after a program is created?
A .class file.
The Java Runtime Environment (JRE)
A set of libraries that define the application programming interface (API) of the Java language. The JRE also contains the JVM application.
Explicit cast
Action of a programmer in order to convert a variable to a more limited type.
Refactoring
Cleans code whilst preserving behaviour.
What is the output of the following Java code? int[] list = {0, 5, 10, 15, 20}; int j; for (j = 1; j <= 5; j++) System.out.print(list[j] + " "); System.out.println(); 1. 5 10 15 20 0 2. 5 10 15 20 20 3. 0 5 10 15 20 4. Code contains index out-of-bound
Code contains index out-of-bound
Church-Turing Thesis
If there exists an algorithm to do a symbol manipulation task, then there exists a Turing machine to do that task
Can You use float in a switch statement?
No
Can a byte be set to an int variable?
No
If a superclass implements an interface and a subclass implements the same interface is their a compilation error?
No
Operator && __.
Performs short-circuit evaluation
Which of the following statements is NOT true?
The operator new must always be used to allocate space of a specific type, regardless of the type.
HashMap
a dynamic data structure filled with key value mappings - datatypes of the entries are specified in the declaration - keys are a Set - no duplicates
what does a finally block do?
a finally block is run after a try catch even if the try block caught an exception - used to execute code even if an exception is thrown
An error in a program that results in the program outputting $100 instead of the correct answer, $250 is
a logical error
A JPanel can be added to a JFrame to form a GUI. In order to place other GUI components such as JLabels and Buttons into the JFrame, which of the following messages is passed to the JPanel? 1) insert 2) include 3) get 4) getContentPane 5) add
add
The software failure at the Denver International Airport's baggage handling system is a good example of 1) how a large system can be obsolete by the time it is developed 2) how designers sometimes have too much faith in the technology they are using 3) how failures are often a result of multiple variables caused by a system as a whole in actual operation 4) how the use of a centralized computer is really unrealistic in today's distributed processing 5) all of these
all of these
What is the heap?
an area of memory allocated for objects by the JVM
Objects...
are instances (instantiations) of classes, as objects are created, the properties that are defined in the class template are copied to each object instance and assigned values. Thus, each object has its own copy of the class properties
array
collection of data values of the same type; reference data type
32 bit integer
int
Clock -hr: int -min: int -sec: int +Clock() +Clock(int, int, int) +setTime(int, int, int): void +getHours(): int +getMinutes(): int +getSeconds(): int +printTime(): void +incrementSeconds(): int +incrementMinutes(): int +incrementHours(): boolean +equals(Clock): boolean +makeCopy(Clock): void +getCopy(): Clock Which of the following would be a default constructor for the class Clock shown in the figure above? 1. public Clock(0, 0, 0) { setTime(); } 2. private Clock(10){ setTime(); } 3. public Clock(0) { setTime(0); } 4. public Clock(){ setTime(0, 0, 0); }
public Clock(){ setTime(0, 0, 0); }
The main method header is written as:
public static void main(String[ ] args)
Variables in interfaces are declared what automatically?
public, static and final.
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is visible in method one? 1. x (block three's local variable) 2. local variables of method two 3. rate (before main) 4. one (method two's formal parameter)
rate (before main)
What does the throws keyword mean?
used to create a exception object
"Or" operator
||
Bitwise Not operator
~
What is BDK?
- BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set of Beans and it can be used to test Beans without writing a code.
What is the use of bin and lib in JDK?
- Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.
What is casting?
- Casting is used to convert the value of one type to another.
What is the difference between an argument and a parameter?
- While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.
What is an I/O filter?
- An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
What is adapter class?
- An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested. For example, the MouseMotionAdapter class has two methods, mouseDragged()and mouseMoved(). The signatures of these empty are exactly as defined in the MouseMotionListener interface. If you are interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged() .
How many ways can an argument be passed to a subroutine and explain them?
- An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.
What is an applet?
- Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.
What is the difference between Assignment and Initialization?
- Assignment can be done as many times as desired whereas initialization can be done only once.
What are Class, Constructor and Primitive data types?
- Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.
What is meant by controls and what are different types of controls in AWT?
- Controls are components that allow a user to interact with your application and the AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.
What are cookies and how will you use them?
- Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user. a) Create a cookie with the Cookie constructor: public Cookie(String name, String value) b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse. addCookie(Cookie cookie) c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest: public Cookie[ ] HttpServletRequest. getCookie().
What is daemon thread and which method is used to create the daemon thread?
- Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon() method is used to create a daemon thread.
What is the life cycle of a servlet?
- Each Servlet has the same life cycle: a) A server loads and initializes the servlet by init () method. b) The servlet handles zero or more client's requests through service() method. c) The server removes the servlet through destroy() method.
What is Internet address?
- Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number.
What are inner class and anonymous class?
- Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.
What is interface and its use?
- Interface is similar to a class which may contain method's signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a)Declaring methods that one or more classes are expected to implement b)Capturing similarities between unrelated classes without forcing a class relationship. c)Determining an object's programming interface without revealing the actual body of the class.
What is Domain Naming Service(DNS)?
- It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters.
What type of driver did you use in project?
- JDBC-ODBC Bridge driver (is a driver that uses native(C language) libraries and makes calls to an existing ODBC driver to access a database engine).
What are JSP ACTIONS?
- JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include: jsp:include - Include a file at the time the page is requested. jsp:useBean - Find or instantiate a JavaBean. jsp:setProperty - Set the property of a JavaBean. jsp:getProperty - Insert the property of a JavaBean into the output. jsp:forward - Forward the requester to a newpage. Jsp: plugin - Generate browser-specific code that makes an OBJECT or EMBED
What is JSP?
- JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The advantages are: a) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process. b) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it.
What are JSP scripting elements?
- JSP scripting elements lets to insert Java code into the servlet that will be generated from the current JSP page. There are three forms: a) Expressions of the form <%= expression %> that are evaluated and inserted into the output, b) Scriptlets of the form<% code %>that are inserted into the servlet's service method, and c) Declarations of the form <%! Code %>that are inserted into the body of the servlet class, outside of any existing methods.
What is a Jar file?
- Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. The package java. util. zip contains classes that read and write jar files.
What is method overloading and method overriding?
- Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.
What are methods and how are they defined?
- Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method's signature is a combination of the first three parts mentioned above.
What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?
- Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.
Are there any global variables in Java, which can be accessed by other part of your program?
- No, it is not the main method in which you define variables. Global variables is not possible because concept of encapsulation is eliminated here.
What is an Object and how do you allocate memory to it?
- Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.
What is OOPs?
- Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.
What is RMI and steps involved in developing an RMI object?
- Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the interfaces and their implementations with the java compiler d) Compile the server implementation with RMI compiler e) Run the RMI registry f) Run the application
What is serialization and deserialization?
- Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
What is Server-Side Includes (SSI)?
- Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an . shtml extension.
What is Servlet chaining?
- Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet's output is piped to the next servlet's input. This process continues until the last servlet is reached. Its output is then sent back to the client.
What is servlet?
- Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.
Why should we go for inter-servlet communication?
- Servlets running together in the same server communicate with each other in several ways. The three major reasons to use interservlet communication are: a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object) b) Servlet reuse - allows the servlet to reuse the public methods of another servlet. c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)
What is session tracking and how do you track a user session in servlets?
- Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are: a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password. b) Hidden form fields - fields are added to an HTML form that are not displayed in the client's browser. When the form containing the fields is submitted, the fields are sent back to the server. c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change. d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser. e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session. maxresidents property.
What is the difference between set and list?
- Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.
What are the types of statements in JDBC?
- Statement: to be used createStatement() method for executing single SQL statement PreparedStatement — To be used preparedStatement() method for executing same SQL statement over and over. CallableStatement — To be used prepareCall() method for multiple SQL statements over and over.
What is the difference between TCP/IP and UDP?
- TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. It is like a phone call. UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination. It is like a postal mail.
What are the advantages of the model over the event-inheritance model?
- The event-delegation model has two advantages over the event-inheritance model. They are: a)It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component's design and its use. b)It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to be repeatedly process unhandled events as is the case of the event-inheritance.
What is the difference between exception and error?
- The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.
What are the types of JDBC Driver Models and explain them?
- There are two types of JDBC Driver Models and they are: a) Two tier model and b) Three tier model. Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is required to communicate with the particular database management system that is being accessed. SQL statements are sent to the database and the results are given to user. This model is referred to as client/server configuration where user is the client and the machine that has the database is called as the server. Three tier model: A middle tier is introduced in this model. The functions of this model are: a) Collection of SQL statements from the client and handing it over to the database, b) Receiving results from database to the client and c) Maintaining control over accessing and updating of the above.
How to create and call stored procedures?
- To create stored procedures: Create procedure procedurename (specify in, out and in out parameters) BEGIN Any multiple SQL statement; END; To call stored procedures: CallableStatement csmt = con. prepareCall("{call procedure name(?,?)}"); csmt. registerOutParameter(column no. , data type); csmt. setInt(column no. , column name) csmt. execute();
What are Transient and Volatile Modifiers?
- Transient: The transient modifier applies to variables only and it is not stored as part of its object's Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
What is URL?
- URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http - protocol name, address - IP address or host name, 80 - port number and index.html - file path.
What are Vector, Hashtable, LinkedList and Enumeration?
- Vector : The Vector class provides the capability to implement a growable array of objects. Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the object's keys. Hash codes are integer values that identify objects. LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations. Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements() and nextElement(). HasMoreElemnts() tests if this enumeration has more elements and nextElement method returns successive elements of the series.
What is Garbage Collection and how to call it explicitly?
- When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.
When will you synchronize a piece of your code?
- When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
What is connection pooling?
- With servlets, opening a database connection is a major bottleneck because we are creating and tearing down a new connection for every page request and the time taken to create connection will be more. Creating a connection pool is an ideal approach for a complicated servlet. With a connection pool, we can duplicate only the resources we need to duplicate rather than the entire servlet. A connection pool can also intelligently manage the size of the pool and make sure each connection remains valid. A number of connection pool packages are currently available. Some like DbConnectionBroker are freely available from Java Exchange Works by creating an object that dispenses connections and connection Ids on request. The ConnectionPool class maintains a Hastable, using Connection objects as keys and Boolean values as stored values. The Boolean value indicates whether a connection is in use or not. A program calls getConnection() method of the ConnectionPool for getting Connection object it can use; it calls returnConnection() to give the connection back to the pool.
Is it possible to communicate from an applet to servlet and how many ways and how?
- Yes, there are three ways to communicate from an applet to servlet and they are: a) HTTP Communication(Text-based and object-based) b) Socket Communication c) RMI Communication
Can you have an inner class inside a method and what variables can you access?
- Yes, we can have an inner class inside a method and final variables(local) can be accessed.
Is it possible to call servlet with parameters in the URL?
- Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).
What is the difference between Integer and int?
- a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.
What is the difference between JDBC and ODBC?
- a) OBDC is for Microsoft and JDBC is for Java applications. b) ODBC can't be directly used with Java because it uses a C interface. c) ODBC makes use of pointers which have been removed totally from Java. d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required. e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms. f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC.
What is the difference between String and String Buffer?
- a) String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings.
What is the difference between doPost and doGet methods?
- a) doGet() method is used to get information, while doPost() method is used for posting information. b) doGet() requests can't send large amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length. c) A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.
What is the difference between applications and applets?
- a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface.
What is final, finalize() and finally?
- final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can't be overridden. A final variable can't change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.
What is finalize() method?
- finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.
What is the lifecycle of an applet?
- init() method - Can be called when an applet is first loaded start() method - Can be called each time an applet is started. paint() method - Can be called when the applet is minimized or maximized. stop() method - Can be used when the browser moves off the applet's page. destroy() method - Can be called when the browser is finished with the applet.
What modifiers may be used with top-level class?
- public, abstract and final can be used for top-level class.
What are different types of access modifiers?
- public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can't be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package.
Explain the methods, rebind() and lookup() in Naming class?
- rebind() of the Naming class(found in java. rmi) is used to update the RMI registry on the server machine. Naming. rebind("AddSever", AddServerImpl); lookup() of the Naming class accepts one argument, the rmi URL and returns a reference to an object of type AddServerImpl.
What are Predefined variables or implicit objects?
- simplified code in JSP expressions . They are request, response, out, session, application, config, pageContext, and page.
What is source and listener?
- source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way. listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.
What is the difference between this() and super()?
- this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.
What are the steps involved for making a connection with a database or how do you connect to a database?
a) Loading the driver : To load the driver, Class. forName() method is used. Class. forName("sun. jdbc. odbc. JdbcOdbcDriver"); When the driver is loaded, it registers itself with the java. sql. DriverManager class as an available database driver. b) Making a connection with database: To open a connection to a given database, DriverManager. getConnection() method is used. Connection con = DriverManager. getConnection ("jdbc:odbc:somedb", "user", "password"); c) Executing SQL statements : To execute a SQL query, java. sql. statements class is used. createStatement() method of Connection to obtain a new Statement object. Statement stmt = con. createStatement(); A query that returns data can be executed using the executeQuery() method of Statement. This method executes the statement and returns a java. sql. ResultSet that encapsulates the retrieved data: ResultSet rs = stmt. executeQuery("SELECT * FROM some table"); d) Process the results : ResultSet returns one row at a time. Next() method of ResultSet object can be called to move to the next row. The getString() and getObject() methods are used for retrieving column values: while(rs. next()) { String event = rs. getString("event"); Object count = (Integer) rs. getObject("count");
Boolean not
!
If you want to output a double so that at least 1 digit appears to the left side of the decimal point and exactly 1 digit appears to the right side of the decimal point, which pattern would you give a DecimalFormat variable when you instantiate it?
"0.0"
Suppose that String name = "Frank Zappa". What will the instruction name.toUpperCase( ).replace('A', 'I'); return?
"FRINK ZIPPI"
"And" operator
&&
Which of the following is the correct expression of character 4?
'4'
If the String major = "Computer Science", what is returned by major.charAt(1)?
'o'
Software Layers and responsibilities
* Presentation Layer - rendering the user interface, responding to user event, creating and populating domain objects, and invoking the business layer. * The Business Layer - managing workflow by coordinating the execution of services located in the service layer. * The Service Layer - service interfaces and implementations, the movement of objects in and out of the application, and the hiding of technology choices. * The Domain Layer - abstracting domain objects (i.e., the nouns) as they appear in the problem space. Data types for: user interface ->> Presentation Layer; manage use case workflow ->>Business Layer; move objects in and out of application ->>Service Layer; abstract the "nouns" of problem space ->> Domain Layer
Multiply and assign operator
*=
Increment by one
++
Given the following assignment statement, which of the following answers is true regarding the order that the operators will be applied based on operator precedence? a = (b + c) * d / e - f;
+, *, /, -
Interfaces (implement)
- Abstract methods. All methods are public. - Cannot be instantiated. - Class that 'implements' an interface inherits its abstract methods.
Event Adapters
- Adapter = Design Pattern - Each Listener has a corresponding Adapter abstract class
What is the difference between Array and vector?
- Array is a set of related data type and static whereas vector is a growable array of objects and dynamic.
Atomic Swing Components
- Basic Controls JButton, JComboBox, JList, JMenu, JSlider, JSpinner, JTextField - Uneditable Displays JLabel, JProgressBar - Interactive Displays JColorChooser, JFileChooser, JTable, JTextArea, JTree
Top Swing Level
- Can appear anywhere on desktop. - Serve as root of containment hierarchy, all others must be contained in top lvl container - have content pane - can have menu bar added JFrame, JDialog, JApplet
Disadvantages of Centralised Servers
- Central point of failure - Latency if remote - Inaccessibility if off-line
Collections
- Compound data type that groups multiple elements of the same type together. - Encapsulates the data structure needed to store the elements and the algorithms needed to manipulate them. - Group of elements of the same type
Race Conditions
- Concurrent access problem - outcome depends on which thread gets to a value first - Results in asynchronous changes = can't predict variables affected by threads - Shared variables need 'volatile' keyword
JPanel
- Contain parts of UI - Can contain other JPanels - Contain multiple different types of components.
The Merge (version control)
- Copy-modify-merge - Harry and Sally access at same time, both edit, Sally publishes first and Harry receives 'out-of-date' error. - Version control system performs diff operation and identifies conflicts. - Manual intervention required if conflicts. - Harry has to compare latest version with his own, creates merge and publishes merge.
GIT
- Distributed version control. - Snapshot based = takes snapshot of each version. - Uses checksums to identify changes to files.
The Lock (version control)
- Lock-modify-unlock - When Harry accesses file he LOCKS it, reads/edits then releases lock. Sally then LOCKS it and does the same. - Only 1 person can access file at time!
Applying Encapsulation*
- Make fields private - make accessors (getters) and mutators (setters) public - make helper (utility) methods private
Threads
- Multiple processes within a single program. - Executed in slices or parallel. - Based on a priority system : this thread before that thread - Separate units of a parent process that share the resources of the parent process
Synchronization
- Only allows one thread access at a time. - Sets a lock on the method or object - When synchronized method terminated, lock released - Places an overhead on execution time (Don't over use it)
Pass by value
- Primitive types - makes a copy so does not affect original
Benefits of Refactoring
- Reduces maintenance problems - Reduces probability of errors - Reduces duplicated code.
How can I delete a cookie with JSP?
- Say that I have a cookie called "foo, " that I set a while ago & I want it to go away. I simply: <% Cookie killCookie = new Cookie("foo", null); KillCookie. setPath("/"); killCookie. setMaxAge(0); response. addCookie(killCookie); %>
Abstraction (extend)
- Segregation of implementation from interface. - cannot be instantiated - Partial implementation - Class can only extend one abstract class
What is stored procedure?
- Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.
Observer Pattern
- Synchronises state and/or responses across a collection of objects in response to an event. - Have Observer and Subject - Observer queries Subject to determine what was the change of state and responds appropriately based on Subjects new state. - Subject adds observers, sets state and gets state.
What is synchronization?
- Synchronization is the mechanism that ensures that only one thread is accessing the resources at a time.
Livelock
- Thread acts in response to another thread, makes no progress but is not blocked - Thread states can and do change but no progress can be made - think of corridor dance example Philosophers pass fork back and forth but no one gets to eat.
Disadvantages of the the Lock (version control)
- Unnecessary serialisation of development steps - Programmers forget to release the lock - Doesn't consider dependencies between classes that may be out to different people at the same time.
Central Repository
- Version database stored on server. - Team checks out version from database. - Checkout = make local copy.
What is deadlock?
- When two threads are waiting each other and can't precede the program is said to be deadlock.
base class
- class that other classes inherit from
Safely stop thread
- control loop with stopFlag - make sure stopFlag independent of other threads - check value frequently - use end() private volatile boolean stopflag; stopflag = false; //in run() try block: while (!stopflag) { d = Math.log(i++); sleep(1);} public void end() { stopflag = true;}
Specialization
- creating new subclass from existing class for more specialized version of parent
Encapsulation*
- data hiding - make fields in class private, accessible via public methods - protective barrier against outside code - access is controlled by interface - Alter code without affecting those that use it
Disadvantages of TDD
- difficult for programs with complex interactions with their environment e.g. GUI - Bad tests = bad code - if programmer write own code = blind spots - scalability debated.
Advantages of exceptions
- error handling is separated from normal code - allows different kind of errors to be distinguished
Unchecked exception
- errors and run time exceptions - result of programming errors AssertionError, VirtualMachineError, ArithmeticException, NullPointerException, IndexOutOfBoundsException
Thread safety
- for GUIs use EventDispatch thread and SwingUtilities.invokeLater(new threadClass()) public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); SwingUtilities.invokeLater(new HelloWorldSwing());
data hiding
- hides internal object details
Checked exception
- if can throw 'checked' exception must: 1. include exception handling code to catch exception or 2. Declare to its caller that it potentially throws exception
java.lang.Runnable
- implemented by classes that run on threads - implement instead of extending Thread Need a Thread wrapper - Thread one = new Thread(new HelloRunnable());
Timer
- implements Runnable - runs a TimerTask object on JVM background thread - so use to Schedule Tasks (threads) // set Timer as a daemon thread Timer timer = new Timer(true); timer.schedule(hello1, 1000); // will run after 1000 milisec timer.schedule(hello2, 2000);
a class that extends a class
- inherits methods another class
Maps
- maps keys to values - can have duplicate keys - each key maps to one value
Object lock (synchronization)
- must be final, otherwise could change and dif threads synchronize on dif objects private final static Object sharedLock = new Object(); public static void displayMessage(JumbledMessage jm) throws InterruptedException { synchronized(sharedLock) { for (int i = 0; i < jm.message.length(); i++) { System.out.print(jm.message.charAt(i)); Thread.currentThread().sleep(50); } System.out.println();}}
Java
- object oriented - architecture neutral - portable - fast -secure -network aware - syntax based on C and C++
Queues
- ordered sequence of elements - access via endpoints - structures for LIFO and FIFO
Lists
- ordered sequence of elements - indexable by individual elements or range - elements can be insereted at or removed from any position - can have duplicates
super classs
- parrent class
final
- prevents class from being extended or overridden - prevents variables from being altered = constant
volatile
- thread goes straight to source and doesn't locally ache - ensuring working with up to date data "Go back and check" - reduce concurrent thread access issues. private volatile boolean pleaseStop; while (!pleaseStop) { // do some stuff... }
Instance variables
- variables inside class but not in methods - instantiated when class loaded - accessed by any method in class
Decrement by one
--
Which of the following lines is not a Java comment? (Choose all that apply.) 1) /** comments */ 2) // comments 3) -- comments 4) /* comments */ 5) ** comments **
-- comments ** comments **
Predecrement
--counter
What will be the result of the following assignment statement? Assume b = 5 and c = 10. int a = b * (-c + 2) / 2;
-20
-24 % -5 is ________.
-4
-24 % 5 is ________.
-4
What is the difference between an interface and an abstract class?
-All methods in an interface are implicitly abstract. Abstract classes don't have to have abstract methods but interfaces do. -Interface variables are also final and abstract class variables don't have to be final. -An abstract class implements an interface and does not have to provide implementation for the interface methods.
Object-oriented programming
-Identify and define objects and solve problems by manipulating objects -look at everything as objects that already have a set of directions
data access class
...
The extension name of a Java bytecode file is
.class
What are 5 method of the class object.
.equals, .toString, .clone, .finalize, .getClass
The instruction: System.out.println("Hello World"); might best be commented as
// used to demonstrate an output message
divide and assign operator
/=
-25 % 5 is ________.
0
Assume that x, y, and z are all integers (int) equal to 50, 20, and 6 respectively. What is the result of x / y / z?
0
Suppose x is 1. What is x after x -= 1?
0
The Random class has a method nextFloat( ) which returns a random float value between
0 and 1
Consider the double value likelihood = 0.013885. What would be output if DecimalFormat dformatter = DecimalFormat("0.00##"); and you execute System.out.println(df.format(likelihood)); ?
0.0139
What does the following loop print? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = a[0]; for (int i = 1; i < len; i++) if (a[i] < x) x = a[i]; System.out.println(x); 1. 36 2. 12 3. 1 4. 6
1
double[] as = new double[7]; double[] bs; bs = as; How many objects are present after the code fragment above is executed? 1. 2 2. 14 3. 1 4. 7
1
int[] hit = new hit[5]; hit[0] = 3; hit[1] = 5; hit[2] = 2; hit[3] = 6; hit[4] = 1; System.out.println(hit[1 + 3]); What is the output of the code fragment above? 1. 1 2. 5 3. 6 4. 3
1
If you want to store into the String name the value "George Bush", you would do which statement?
1) String name = "George Bush"; 2) String name = new String("George Bush"); 3) String name = "George" + " " + "Bush"; 4) String name = new String("George" + " " + "Bush");
Once we have implemented the solution, we are not done with the problem because
1) the solution may not be the best (most efficient) 2) the solution may have errors and need testing and fixing before we are done 3)the solution may, at a later date, need revising to handle new specifications 4) the solution may, at a later date, need revising because of new programming language features
What is difference between static (class) method and instance method?
1)Object is not required to call static method. Object is required to call instance methods. 2)Non-static (instance) members cannot be accessed in static context (static method, static block and static nested class) directly. static and non-static variables both can be accessed in instance methods.
What does the following loop print? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = a[0]; for (int i = 1; i < len; i++) if (a[i] < x) x = a[i]; System.out.println(x); 1. 1 2. 12 3. 6 4. 36
1. 1
int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; How many components are in the array above? 1. 100 2. 0 3. 50 4. 99
1. 100
What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 5; for (j = 1; j < 5; j++) { if (j % 2 == 0) alpha[j] = alpha[j - 1] + 2; else alpha[j] = alpha[j - 1] + 3; } 1. 13 2. 15 3. None of these 4. 10
1. 13
Event loop
1. Action (button click, mouse movement...) registered generating event that can be tracked 2. Event passed to affected component, 3. Listen for Event 4. Respond to Event.
How many constructors can a class have? 1. Any number 2. 2 3. 1 4. 0
1. Any number
Suppose you have the following declaration. char[] nameList = new char[100]; Which of the following range is valid for the index of the array nameList. (i) 1 through 100 (ii) 0 through 100 1. Both are invalid 2. Only (i) 3. None of these 4. Only (ii)
1. Both are invalid
TDD Mantra
1. Create new tests that fail (RED) 2. Write code to pass the test (GREEN) 3. Refactor
Interface rules
1. Exceptions should be declared by interface method. 2. Signature and return type should be the same for interface and implemented class. 3. A class can implement multiple interfaces. 4. An interface can extend another interface.
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] < a[x]) x = i; System.out.println(x); 1. Finds the position of the smallest value in a. 2. Sums the elements in a. 3. Finds the position of the largest value in a. 4. Counts the elements in a.
1. Finds the position of the smallest value in a.
An object is a(n) ____ of a class. 1. instance 2. method 3. field 4. constant
1. Instance
4 heavyweight Swing components
1. JFrame 2. JWindow 3. JDialog 4. JApplet
Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (value > 0) { a[size] = value; size++; value = cin.nextInt(); } 1. May crashe at runtime because it can input more elements than the array can hold 2. Reads up to 3 values and inserts them in the array in the correct position. 3. Reads one value and places it in the remaining first unused space endlessly. 4. Reads up to 3 values and places them in the array in the unused space.
1. May crashe at runtime because it can input more elements than the array can hold
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 1; if (j > 2) alpha[j - 1] = alpha[j] + 2; } 1. None of these 2. alpha = {1, 2, 3, 4, 5} 3. alpha = {1, 5, 6, 7, 5} 4. alpha = {4, 5, 6, 7, 9}
1. None of these
If a class's only constructor requires an argument, you must provide an argument for every ____ of the class that you create. 1. object 2. type 3. parameter 4. method
1. Object
Suppose you have the following declaration. double[] salesData = new double[1000]; Which of the following range is valid for the index of the array salesData. (i) 0 through 999 (ii) 1 through 1000 1. Only (i) 2. None of these 3. Both are invalid 4. Only (ii)
1. Only (i)
Consider the following statements. public class Circle { private double radius; public Circle() { radius = 0.0; } public Circle(double r) { radius = r; } public void set(double r) { radius = r; } public void print() { System.out.println(radius + " " + area + " " + circumference()); } public double area() { return 3.14 * radius * radius; } public double circumference() { return 2 * 3.14 * radius; } } Assume, also that you have the following two statements appearing inside a method in another class: Circle myCircle = new Circle(); double r; Which of the following statements are valid (both syntactically and semantically) in Java? (Assume that cin is Scanner object initialized to the standard input device.) (i) r = cin.nextDouble(); myCircle.area = 3.14 * r * r; System.out.println(myCircle.area); (ii) r = cin.nextDouble(); myCircle.set(r); System.out.println(myCircle.area()); 1. Only (ii) 2. Both (i) and (ii) 3. Only (i) 4. None of these
1. Only (ii)
Redundant
1. Parentheses that are added to an expression simply to make it easier to read are known as ________ parentheses.
Mismanaged threads result in
1. Race Conditions 2. Deadlock 3. Starvation 4. Livelock
Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (size < capacity && value > 0) { a[size] = value; size++; 1. Reads one value and places it in the remaining three unused spaces in a. 2. Reads up to 3 values and places them in the array in the unused space. 3. Reads up to 3 values and inserts them in the array in the correct position. 4. Crashes at runtime because it tries to write beyond the array.
1. Reads one value and places it in the remaining three unused spaces in a.
Client/server programming (Daemon thread)
1. Server listens using daemon thread for each port 2. Request comes, daemon thread responds 3. Creates/calls another thread to do work 4. Worker thread terminates naturally 5. Daemon thread continues monitoring port
Subtype rules
1. Signature rule 2. Methods rule 3. Properties rule
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x += a[i]; System.out.println(x); 1. Sums the even elements in a. 2. Finds the largest value in a. 3. Finds the smallest value in a. 4. Counts the even elements in a.
1. Sums the even elements in a.
The reference to an object that is passed to any object's nonstatic class method is called the ____. 1. this reference 2. magic number 3. literal constant 4. reference
1. This
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements replaces the first object in the collection with element? 1. a.set(0, element); 2. a.set(element, 0); 3. a.add(0, element); 4. a[0] = element;
1. a.set(0, element);
Methods that retrieve values are called ____ methods. 1. accessor 2. class 3. mutator 4. static
1. accessor
___________________ is one of the primary mechanisms that we use to understand the natural world around us. Starting as infants we begin to recognize the difference between categories like food, toys, pets, and people. As we mature, we learn to divide these general categories or classes into subcategories like siblings and parents, vegetables and dessert. 1. classification 2. encapsulation 3. specialization 4. generalization
1. classification
A(n) ____ method is a method that creates and initializes objects. 1. constructor 2. non-static 3. instance 4. accessor
1. constructor
You can use ____ arguments to initialize field values, but you can also use arguments for any other purpose. 1. constructor 2. field 3. data 4. object
1. constructor
Which of the following lines of code explicitly calls the toString() method, assuming that pete is an initialized Student object variable? 1. println(pete.toString()); 2. println("" + pete); 3. println(super.toString()); 4. println(pete)
1. println(pete.toString());
To call a superclass method from a subclass method, when both methods have the same name and signature, prefix the call to the superclass method with: 1. super 2. the name of the superclass (that is, Person, if that is the name of the superclass) 3. no prefix is necessary. You cannot call an overridden superclass method from the subclass method you've overridden. 4. this 5. base
1. super
Which of the following expressions will yield 0.5? (Choose all that apply.) 1) 1 / 2 2) 1.0 / 2 3) (double) (1 / 2) 4) (double) 1 / 2 5) 1 / 2.0
1.0 / 2 (double) 1 / 2 1 / 2.0
int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the value at index 10 of the array above?
10
What is the output of the following Java code? int[] alpha = {2, 4, 6, 8, 10}; int j; for (j = 4; j >= 0; j--) System.out.print(alpha[j] + " "); System.out.println();
10 8 6 4 2
10. The debugger command ________ allows you to "peek into the computer" and look at the value of a variable.
What is the result of 45 / 4?
11
Which memory capacity is the largest?
12,000,000 megabytes
What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 5; for (j = 1; j < 5; j++) { if (j % 2 == 0) alpha[j] = alpha[j - 1] + 2; else alpha[j] = alpha[j - 1] + 3; } 1. None of these 2. 13 3. 15 4. 10
13
What is output with the statement System.out.println(""+x+y); if x and y are int values where x=10 and y=5?
15
char[][] array1 = new char[15][10]; What is the value of array1.length? 1. 15 2. 0 3. 2 4. 10
15
char
16 bit unicode character
What will be returned from the following method? public static double methodA() { double a = 8.5 + 9.5; return a; }
18.0
Consider the following statement: System.out.println("1 big bad wolf\t8 the 3 little pigs\n4 dinner\r2night"); This statement will output ________ lines of text
2
What does the following loop print? int[] a = {6, 1, 9, 5, 12, 7}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x++; System.out.println(x); 1. 4 2. 22 3. 18 4. 2
2
The ________ method displays an input dialog for reading a string. (Choose all that apply.) 1) String string = JOptionPane.showMessageDialog(null, "Enter a string", "Input Demo", JOptionPane.QUESTION_MESSAGE); 2) String string = JOptionPane.showInputDialog(null, "Enter a string", "Input Demo", JOptionPane.QUESTION_MESSAGE); 3) String string = JOptionPane.showInputDialog("Enter a string", "Input Demo", JOptionPane.QUESTION_MESSAGE); 4) String string = JOptionPane.showInputDialog(null, "Enter a string"); 5) String string = JOptionPane.showInputDialog("Enter a string");
2) String string = JOptionPane.showInputDialog(null, "Enter a string", "Input Demo", JOptionPane.QUESTION_MESSAGE); 4) String string = JOptionPane.showInputDialog(null, "Enter a string"); 5) String string = JOptionPane.showInputDialog("Enter a string");
Suppose that sales is a two-dimensional array of 10 rows and 7 columns wherein each component is of the type int , and sum and j are int variables. Which of the following correctly finds the sum of the elements of the fifth row of sales? 1. sum = 0; for(j = 0; j < 10; j++) sum = sum + sales[5][j]; 2. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[4][j]; 3. sum = 0; for(j = 0; j < 10; j++) sum = sum + sales[4][j]; 4. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[5][j];
2. sum = 0; for(j = 0; j < 7; j++) sum = sum + sales[4][j];
What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; for (j = 4; j >= 0; j--) { alpha[j] = j + 5; if (j <= 2) alpha[j + 1] = alpha[j] + 3; } 1. 8 2. 10 3. 9 4. 5
2. 10
public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } How many constructors are present in the class definition above? 1. 3 2. 2 3. 1 4. 0
2. 2
Assume that two arrays are parallel. Assume the first array contains a person's id number and the second contains his or her age. In which index of the second array would you find the age of the person in the third index of the first array? 1. 2 2. 3 3. 1 4. It cannot be determined from the information given.
2. 3
int[] hits = {10, 15, 20, 25, 30}; copy(hits); What is being passed into copy in the method call above? 1. 10 2. A reference to the array object hits 3. The value of the elements of hits 4. A copy of the array hits
2. A reference to the array object hits
How many constructors can a class have? 1. 2 2. Any number 3. 1 4. 0
2. Any number
public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } Which of the following statements would you use to declare a new reference variable of the type Illustrate and instantiate the object with a value of 9 for the variable x? 1. Illustrate.illObject(9); 2. Illustrate illObject = new Illustrate(9); 3. Illustrate illObject(9); 4. illObject = Illustrate(9);
2. Illustrate illObject = new Illustrate(9);
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int z = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Where is identifier z (block three's local variable) visible? 1. In block three and main 2. In block three only 3. In two and block three 4. In one and block three
2. In block three only
Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following statements are valid in Java? (Assume that cin is Scanner object initialized to the standard input device.) (i) bigRect.length = cin.nextDouble(); bigRect.width = cin.nextDouble(); (ii) double l; double w; l = cin.nextDouble(); w = cin.nextDouble(); bigRect.set(l, w); 1. Only (i) 2. Only (ii) 3. Both (i) and (ii) 4. None of these
2. Only (ii)
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x += a[i]; System.out.println(x); 1. Counts the even elements in a. 2. Sums the even elements in a. 3. Finds the largest value in a. 4. Finds the smallest value in a.
2. Sums the even elements in a.
Which of the following is used to allocate memory for the instance variables of an object of a class? 1. the reserved word public 2. the operator new 3. the operator + 4. the reserved word static
2. The operator new
Which of the following statements is NOT true? 1. Reference variables contain the address of the memory space where the data is stored. 2. The operator new must always be used to allocate space of a specific type, regardless of the type. 3. Reference variables do not directly contain the data. 4. A String variable is actually a reference variable of the type String.
2. The operator new must always be used to allocate space of a specific type, regardless of the type.
int[] x = new int[10]; x[0] = 34; x[1] = 88; println(x[0] + " " + x[1] + " " + x[10]); What is the output of the code fragment above? 1. 34 88 88 2. This program throws an exception. 3. 34 88 0 4. 0 34 88
2. This program throws an exception.
Javac
2. To compile an application, type the command ____ followed by the name of the file.
Primitive
2. Types already defined in Java, such as int, are known as ____ types.
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int x = 0; for (int e : a) x += a; 1. Sums all the elements in a. 2. Will not compile (syntax error) 3. Finds the largest value in e. 4. Counts each element in a.
2. Will not compile (syntax error)
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements adds the object to the beginning of the collection? 1. a[4] = element; 2. a.add(0, element); 3. a.insert(element); 4. a.add(element, 0); 5. a[0] = element;
2. a.add(0, element);
A(n) ____ constructor is one that requires no arguments. Student Response Value Correct Answer Feedback 1. write 2. default 3. class 4. explicit
2. default
Programmers frequently use the same name for a(n) ____ and an argument to a method simply because it is the "best name" to use. 1. block 2. instance field 3. variable 4. constant
2. instance field
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is NOT part of the heading of the method above? 1. static 2. int smaller; 3. minimum(int x, int y) 4. public
2. int smaller;
Clock ---------------------------------------- -hr: int -min: int -sec: int --------------------------------------- +Clock() +Clock(int, int, int) +setTime(int, int, int) : void +getHours() : int +getMinutes() : int +getSeconds() : int +printTime() : void +incrementSeconds() : int +incrementMinutes() : int +incrementHours() : int +equals(Clock) : boolean +makeCopy(Clock) : void +getCopy() : Clock ---------------------------------------- According to the UML class diagram above, which of the following is a data member? 1. printTime() 2. min 3. Clock() 4. Clock
2. min
To access the name instance variable from inside a method defined in the Student class, name must use the _____________ modifier. (We'll ignore the default package-private access if no modifier is used.) 1. public 2. protected or public 3. private or protected 4. private 5. protected 6. Any of them
2. protected or public
Which of the following is NOT true about return statements? 1. A method can have more than one return statement. 2. return statements can be used in void methods to return values. 3. Whenever a return statement executes in a method, the remaining statements are skipped and the method exits. 4. A value-returning method returns its value via the return statement.
2. return statements can be used in void methods to return values.
What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] < value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 1, 3, 5, 0, 0, 0 } 2. { 5, 1, 3, 7, 0, 0 } 3. { 1, 3, 5, 7, 0, 0 } 4. { 1, 3, 7, 5, 0, 0 }
2. { 5, 1, 3, 7, 0, 0 }
What is the value of (double)5/2?
2.5
What is the printout of System.out.println('z' - 'a')?
25
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Based on the above code, what would be the output of the statement int s = minimum(5, minimum(3, 7)); 1. 5 2. There would be no output; this is not a valid statement. 3. 7 4. 3
3
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Based on the above code, what would be the output of the statement int s = minimum(5, minimum(3, 7));
3
A color image is broken down into individual pixels (points), each of which is represented by
3 values denoting the intensity of red, green, and blue in the image
Suppose i is an int type variable. Which of the following statements display the character whose Unicode is stored in variable i? 1) System.out.println(i); 2) System.out.println((char)i); 3) System.out.println((int)i); 4) System.out.println(i + " ");
3) System.out.println((char)i);
What does the following loop print? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = a[0]; for (int i = 1; i < len; i++) if (a[i] > x) x = a[i]; System.out.println(x); 1. 36 2. 6 3. 12 4. 1
3. 12
What does the following loop print? int[] a = {6, 9, 1, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 1; i < len; i++) if (a[i] < a[x]) x = i; System.out.println(x); 1. 6 2. 1 3. 2 4. 4
3. 2
What is the value of alpha[2] after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) alpha[j] = 2 * j + 1; 1. 1 2. 4 3. 5 4. 6
3. 5
The arguments in a method call are often referred to as ____. 1. concept parameters 2. constants 3. actual parameters 4. argument lists
3. Actual parameters
Consider the following declaration. int[] list = new int[10]; int j; int sum; Which of the following correctly finds the sum of the elements of list? (i) sum = 0; for (j = 0; j < 10; j++) sum = sum + list[j]; (ii) sum = list[0]; for (j = 1; j < 10; j++) sum = sum + list[j]; 1. Only (ii) 2. Only (i) 3. Both (i) and (ii) 4. None of these
3. Both (i) and (ii)
When you override a method defined in a superclass, you must do all of these except: 1. Use exactly the same number and type of parameters as the original method 2. Use an access specifier that is at least as permissive as the superclass method 3. Change either the number, type, or order of parameters in the subclass. 4. Return exactly the same type as the original method.
3. Change either the number, type, or order of parameters in the subclass.
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; for (int e : a) e = 0; 1. Changes each element in a to 0. 2. Compiles, but crashes when run. 3. Changes each element e to 0 but has no effect on the corresponding element in a. 4. Will not compile (syntax error)
3. Changes each element e to 0 but has no effect on the corresponding element in a.
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int x = 0; for (int e : a) x++; 1. Sums all the elements in a. 2. Will not compile (syntax error) 3. Counts each element in a. 4. Finds the largest value in e.
3. Counts each element in a.
What does the following loop do? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] > value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. Removes (deletes) value from a so that the array remains ordered. 2. Places value in the last element of a 3. Inserts value into a so that the array remains ordered. 4. Places value in the first unused space in a (where the first 0 appears)
3. Inserts value into a so that the array remains ordered.
Consider the following statements. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println("Length = " + length + "; Width = " + width + "\n" + + " Area = " + area() + "; Perimeter = " + perimeter()); } public double area() { return length * width; } public void perimeter() { return 2 * length + 2 * width; } } What is the output of the following statements?
3. Length = 14.0; Width = 10.0 Area = 140.0; Perimeter = 48.0
Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public void perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(); Which of the following sets of statements are valid in Java? (i) bigRect.set(10, 5); (ii) bigRect.length = 10; bigRect.width = 5; 1. Only (ii) 2. None of these 3. Only (i) 4. Both (i) and (ii)
3. Only (i)
Which of the following class definitions is correct in Java? (i) public class Student { private String name; private double gpa; private int id; public void Student() { name = ""; gpa = 0; id = 0; } public void Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } (ii) public class Student { private String name; private double gpa; private int id; public Student() { name = ""; gpa = 0; id = 0; } public Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } 1. Both (i) and (ii) 2. None of these 3. Only (ii) 4. Only (i)
3. Only ii
public class Illustrate { private int x; private int y; public Illustrate() { x = 1; y = 2; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y); } public void incrementY() { y++; } } What does the default constructor do in the class definition above? 1. Sets the value of x to 0 2. There is no default constructor. 3. Sets the value of x to 1 4. Sets the value of x to a
3. Sets the value of x to 1.
public static String exampleMethod(int n, char ch) Which of the following statements about the method heading above is NOT true? 1. The method has two parameters. 2. exampleMethod is an identifier giving a name to this specific method. 3. The method cannot be used outside the class. 4. It is a value-returning method of type String.
3. The method cannot be used outside the class.
Consider the following method definition. public int strange(int[] list, int item) { int count; for (int j = 0; j < list.length; j++) if (list[j] == item) count++; return count; } Which of the following statements best describe the behavior of this method? 1. This method returns the sum of all the values of list. 2. None of these 3. This method returns the number of times item is stored in list. 4. This method returns the number of values stored in list.
3. This method returns the number of times item is stored in list.
Which of the following is the array subscripting operator in Java? 1. . 2. {} 3. [] 4. new
3. []
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following is an example of a local identifier in the example above? 1. w (line 20) 2. t (line 5) 3. a (line 25) 4. rate (line 3)
3. a (line 25)
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements adds the object to the end of the collection? 1. a[3] = element; 2. a[4] = element; 3. a.add(element); 4. a.add(element, 4);
3. a.add(element);
Constructors have the same name as the ____. 1. data members 2. member methods 3. class 4. package
3. class
When you create your own new, user-defined types, there are really three different strategies you can use. Which of these is not one of those strategies? 1. defining a component from scratch, inheriting only the methods in the Object class 2. extending an existing component by adding new features 3. defining a component from scratch, inheriting no methods whatsoever 4. combining simpler components to create a new component
3. defining a component from scratch, inheriting no methods whatsoever
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements assigns the last object in the collection to the variable element? 1. element = a[3]; 2. element = a[4]; 3. element = a.get(3); 4. a.get(3, element); 5. a.get(element, e);
3. element = a.get(3);
The keyword ____ indicates that a field value is non-changable. 1. const 2. readonly 3. final 4. static
3. final
Assigning ____ to a field means that no other classes can access the field's values. 1. key access 2. user rights 3. private access 4. protected access
3. private access
Person -name: String +setName(String name): void +getName(): String ^ Student -studentID: long +Student(String sname, long sid) +setID(): long To access the name instance variable from inside a method defined in the Student class, name must use the _____________ modifier. (We'll ignore the default package-private access if no modifier is used.) 1. Any of them 2. public 3. protected or public 4. protected 5. private 6. private or protected
3. protected
Consider the following method which takes any number of parameters. Which statement would return the first of the numbers passed when calling the method? int first = firstNum(7, 9, 15); public int firstNum(int..nums) { // what goes here? } 1. return nums[0] 2. return nums; 3. return nums...0 4. return nums.first;
3. return nums..0
Which of the following words indicates an object's reference to itself? 1. public 2. that 3. this 4. protected
3. this
Mutator methods typically have a return type of ______________. 1. boolean 2. String 3. void 4. int
3. void
What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] > value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 5, 1, 3, 7, 0, 0 } 2. { 1, 3, 7, 5, 0, 0 } 3. { 1, 3, 5, 7, 0, 0 } 4. { 1, 3, 5, 0, 0, 0 }
3. { 1, 3, 5, 7, 0, 0 }
Assuming c=5, the value of variable d after the assignment d=c * ++c is _____.
30
Which of the following expression results in a value 1? 1) 2 % 1 2) 15 % 4 3) 25 % 5 4) 37 % 6
37 % 6
What does the following loop print? int[] a = {6, 1, 9, 5, 12, 7}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 1) x++; System.out.println(x); 1. 18 2. 2 3. 22 4. 4
4
double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is the value of vals.length in the array above? 1. 16 2. 4 3. 0 4. 3
4
What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; for (j = 4; j >= 0; j--) { alpha[j] = j + 5; if (j <= 2) alpha[j + 1] = alpha[j] + 3; } 1. 9 2. 5 3. 8 4. 10
4. 10
What is the value of alpha[4] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 2; for (j = 1; j < 5; j++) alpha[j] = alpha[j - 1] + 3; 1. 5 2. 11 3. 8 4. 14
4. 14
char[][] array1 = new char[15][10]; What is the value of array1.length? 1. 0 2. 10 3. 2 4. 15
4. 15
int[] array1 = {1, 3, 5, 7}; for (int i = 0; i < array1.length; i++) if (array1[i] > 5) System.out.println(i + " " + array1[i]); What is the output of the code fragment above? 1. 0 3 2. 7 3 3. 5 1 4. 3 7
4. 3 7
What is the value of alpha[2] after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) alpha[j] = 2 * j + 1; 1. 4 2. 6 3. 1 4. 5
4. 5
Consider the following statements. public class PersonalInfo { private String name; private int age; private double height; private double weight; public void set(String s, int a, double h, double w) { name = s; age = a; height = h; weight = w; } public String getName() { return name; } public int getAge() { return age; } public double getHeight() { return height; } public double getWeight() { return weight; } } Assume you have the following code fragment inside a method in a different class: PersonalInfo person1 = new PersonalInfo(); PersonalInfo person2 = new PersonalInfo(); String n; int a; double h, w; Which of the following statements are valid (both syntactically and semantically) in Java? (i) person2 = person1; (ii) n = person1.getName(); a = person1.getAge(); h = person1.getHeight(); w = person1.getWeight(); person2.set(n, a, h, w); 1. None of these 2. Only (ii) 3. Only (i) 4. Both (i) and (ii)
4. Both (i) and (ii)
Which of the following class definitions is correct in Java? (i) public class Student { private String name; private double gpa; private int id; public void Student() { name = ""; gpa = 0; id = 0; } public void Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } (ii) public class Student { private String name; private double gpa; private int id; public Student() { name = ""; gpa = 0; id = 0; } public Student(String s, double g, int i) { set(s, g, i); } public void set(String s, double g, int i) { name = s; gpa = g; id = i; } public void print() { System.out.println(name + " " + id + " " + gpa); } } 1. Only (i) 2. Both (i) and (ii) 3. None of these 4. Only (ii)
4. Only (ii)
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 7}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 1) x += a[i]; System.out.println(x); 1. Finds the largest value in a. 2. Finds the smallest value in a. 3. Counts the odd elements in a. 4. Sums the odd elements in a.
4. Sums the odd elements in a.
setText()
4. Use the ____ method to clear any text displayed in a JTextField.
Which of these are superclass members are not inherited by a subclass? 1. a protected method 2. a protected instance variable 3. a public instance variable 4. a public constructor 5. a public method
4. a public constructor
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements adds the object to the end of the collection 1. a[3] = element; 2. a.add(element, 4); 3. a[4] = element; 4. a.add(element);
4. a.add(element);
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = 2 * j; if (j % 2 == 1) alpha[j - 1] = alpha[j] + j; } 1. alpha = {0, 2, 4, 6, 8} 2. alpha = {0, 3, 4, 7, 8} 3. alpha = {0, 2, 9, 6, 8} 4. alpha = {3, 2, 9, 6, 8}
4. alpha = {3, 2, 9, 6, 8}
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 5; if (j % 2 == 1) alpha[j - 1] = alpha[j] + 2; } 1. alpha = {5, 6, 10, 8, 9} 2. alpha = {8, 6, 7, 8, 9} 3. alpha = {5, 6, 7, 8, 9} 4. alpha = {8, 6, 10, 8, 9}
4. alpha = {8, 6, 10, 8, 9}
Person -name: String +setName(String name): void +getName(): String ^ Student -studentID: long +Student(String sname, long sid) +setID(): long Which of these fields or methods are inherited (and accessible) by the Student class? 1. getName(), setName(), name 2. name, getName(), setName(), getID() 3. studentID, name, getName(), setName(), getID() 4. getName(), setName(), toString() 5. None of them 6. getName(), setName(), studentID, getID()
4. getName(), setName(), toString()
int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100; What is the data type of the array above? 1. list 2. num 3. char 4. int
4. int
A locally declared variable always ____ another variable with the same name elsewhere in the class. 1. uses 2. creates 3. deletes 4. masks
4. masks
Which of the following lines of code explicitly calls the toString() method, assuming that pete is an initialized Student object variable? 1. println(super.toString()); 2. println("" + pete); 3. println(pete); 4. println(pete.toString());
4. println(pete.toString());
What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] < value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 1, 3, 7, 5, 0, 0 } 2. { 1, 3, 5, 0, 0, 0 } 3. { 1, 3, 5, 7, 0, 0 } 4. { 5, 1, 3, 7, 0, 0 }
4. { 5, 1, 3, 7, 0, 0 }
What does a contain after the following loop? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; for (int i = size; i > pos; i--) a[i - 1] = a[i]; size--; 1. {3, 7, 7, 0, 0, 0} 2. {1, 1, 1, 0, 0, 0} 3. {3, 7, 0, 0, 0, 0} 4. {0, 0, 0, 0, 0, 0}
4. {0, 0, 0, 0, 0, 0}
cache memory
5 to 10 times faster than RAM, but smaller. When a computer uses something it'll use it again very soon -> move the data from regular RAM to cache
Left to right
5. If an expression contains several multiplication, division and remainder operations, they are performed from ________.
the line number of the error; a brief description of the error.
5. Upon finding a syntax error in an application, the compiler will notify the user of an error by giving the user ____.
Replaces
5. When a value is placed into a memory location, the value ____ the previous value in that location.
When you define a subclass, like Student, and don't supply a constructor, then its superclass must: 1. have an explicit working constructor defined 2. have no constructors defined 3. have an explicit default (no-arg) constructor defined 4. have an explicit copy constructor defined 5. have no constructors defined or have an explicit default (no-arg) constructor defined.
5. have no constructors defined or have an explicit default (no-arg) constructor defined.
When you define a subclass, like Student, and add a single constructor with this signature Student(String name, long id), an implicit first line is added to your constructor. That line is: 1. No implicit lines are added to your constructor 2. this(); 3. super(name, id); 4. base(); 5. super();
5. super();
When you create a new class using inheritance, you use the extends keyword to specify the __________________ when you define the ________________. 1. derived class, subclass 2. derived class, base class 3. superclass, base class 4. subclass, base class 5. superclass, subclass 6. subclass, superclass
5. superclass, subclass
double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is in vals[2][1]? 1. 1.3 2. 3.3 3. 3.5 4. 5.3
5.3
Nondestructive
6. Reading a value from a variable is a ________ process.
In straight-line form
7. Arithmetic expressions in Java must be written ____ to facilitate entering expressions into the computer.
KeyPressed
7. Pressing a key in JTextField raises the ________ event.
The expression (int)(76.0252175 * 100) / 100 evaluates to ________.
76
One byte has ________ bits.
8
setHorizontalAlignment
8. Use ____ to align the text displayed inside a Jlabel.
Math.pow(2, 3) returns ________.
8.0
int
9. Variables used to store integer values should be declared with keyword ________.
End of a statement
;
Less than
<
Assignment
=
Boolean equals
==
What is the difference between = and ==?
== is used for comparison and = is used for assignment.
Boolean Expressions
A boolean expression often uses one of Java's equality operators or relational operators, which all return boolean results: Note the difference between the equality operator (==) and the assignment operator (=)
Boolean
A boolean value represents a true or false condition (1 bit) The reserved words true and false are the only valid values for a boolean type boolean done = false; A boolean variable are usually used to indicate whether a particular condition is true, such as whether the size of a dog is greater than 60
Charachters
A char variable stores a single character (16 bits) Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' Example of declarations with initialization: char topGrade = 'A'; char terminator = ';', separator = ' '; Note the difference between a primitive character variable, which holds only one character (enclosed by single quotes), and a String object, which can hold multiple characters (enclosed by double quotes)
Java Class Libraries
A class library is a collection of classes to facilitate programmers when developing programs The Java standard class library is part of any Java development environment (available after installing JDK) The Java standard class library is sometimes referred to as the Java API (Application Programming Interface) Its classes are not part of the Java language per se, but we rely heavily on them Various classes we've already used (System, String) are part of the Java API
What does it mean for a method to take in an interface as a parameter.
A class that implements that interface must be passed.
If class B has method m1 and class A doesn't, what happens? A a = new B(); a.m1();
A compilation error. If class A has the method and class B doesn't the method will be called from class A, if class B overrides that method, class B's method will be called. Their will be a compilation error if A doesn't have that method.
________ translates high-level language program into machine language program.
A compiler
JTextField component
A component that can accept user input from the keyboard or display output to the user.
JLabel component
A component used to describe another component. This helps users understand a component's purpose.
Constant
A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence As the name implies, it is constant and cannot be changed The compiler will issue an error if you try to change the value of a constant In Java, we use the final modifier to declare a constant final int NUM_SEASONS = 4; whenever you use the reference variable, NUM_SEASONS, it will equal 4 Constants are useful for three important reasons First, they give meaning to otherwise unclear literal values Example: MAX_LOAD means more than the literal 250 Second, they facilitate program maintenance If a constant is used in multiple places, its value need only be set in one place Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers
Switch Statement
A control flow statement that takes an argument and compares it to the cases supplied to it - runs the code under a case if the arguments are equal - will run all the code underlying one case if a 'break' or 'return' is not encountered.
What does it mean when an object is passed by value?
A copy is made and that copy is passed. When something is passed by value any changes to that value doesn't affect the actual object.
double
A datatype that can *represent numbers with decimal points*.
What does the finally keyword do?
A finally code block can be placed after a try catch block. The code in the finally block will always run whether or not an exception is thrown.
bug
A flaw in an application that prevents the application from executing correctly.
Repetition Statement
A general name for a statement that allows the programmer to specify that an action or actions should be repeated, depending on a condition.
What does the term generic mean?
A generic type is a parameterized type - a type
NOT (!) operator
A logical operator that enables a programmer to reverse the meaning of a condition, true is false, false is true if evaluated.
XOR operator (^)
A logical operator that evaluates to true if and only if one operand is true.
OR operator (||)
A logical operator used to ensure that either or both of two conditions are true. Performs short-circuit evaluation.
Refactor - encapsulate collection
A method returns a collection - make it return a read-only view and provide add/remove methods. (get, set, add, remove..)
setText
A method that sets the text property of a component, such as a JLabel, JTextField or JButton.
Java bytecode
A platform independent instruction set that's produced when Java source code is compiled.
Java Virtual Machine (JVM)
A platform-targeted runtime environment that knows how to execute Java bytecode.
algorithm
A procedure for solving a problem, specifying the actions to be executed and the order in which these actions are to be executed.
control
A program statement (such as if, if...else, switch, while, do...while or for) that specifies the flow of ____.
algorithm
A sequence of steps that is unambiguous, executable, and terminating. a well ordered collection of unambiguous and effectively computable operations that when executed produces a result and halts in a finite amount of time
identifier
A series of characters consisting of letters, digits and underscores used to *name classes and GUI components*.
body
A set of statements that is enclosed in curly braces ({ and }). This is also called a *block*. Another name for this is a ____.
double-selection statement
A statement, such as if...else, that selects between two different actions or sequences of actions.
What is static method?
A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class. static method can access static data member and can change the value of it.
Counter-Controlled Repetition (Definite Repetition)
A technique that uses a counter to limit the number of times that a block of statements will execute.
statement
A unit of code that performs an action and ends with a semicolon.
static variable
A variable defined in a class that has only one value for the whole class, and which can be accessed and changed by any method of that class.
True and False
A variable of type boolean can be assigned the values _____.
Counter
A variable often used to determine the number of times a block of statements in a loop will execute.
A variable or an expression can be examined by the _____ debugger command.
primitive type
A variable type already defined in Java. (Examples: boolean, byte, char, short, int, long, float and double)
In the following code, System.out.println(num), is an example of ________. double num = 5.4; System.out.println(num); num = 0.0;
A void method
Difference between while loop and do/while loop?
A while loop runs as long as its given condition is true - do/while loops at least once and the until the condition is false
Categorize each of the following situations as a compile-time error, run-time error, or logical error.
A. Multiplying two numbers why you mean to add them. logical error B. Dividing by zero run-time error C. Forgetting a semicolon at the end of a programming statement compile-time error D. Spelling a word incorrectly in the output logical error E. Producing inaccurate results logical error F. Typing { when you should have typed a ( compile-time error
what can be put in main to access a and staticAccess? public class A{ static int a = 13; static void staticAccess(){} public static void main(String args[]){ //Line 1 // Line 2 } }
A.a and A.staticAccess You can use the class name to call a static member.
Polymorphism*
Able to perform operations without knowing the subclass of the object (just superclass). Apply the same operation on values of different types as long as they have common ancestor. * parent class reference is used to refer to a child class object - program decides which to run at run time
Protected
Accessible if in same package.
When an object, such as a String, is passed as an argument, it is A. Passed by value like any other parameter value B. Actually a reference to the object that is passed C. Encrypted D. Necessary to know exactly how long the string is when writing the program
Actually a reference to the object that is passed
What is difference between aggregation and composition?
Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator (aggregation) but bike has an engine (compostion).
Explain a class for an alarm clock
Alarm object have an instance variable to hold the alarmTime, and two methods for getting and setting the alarmTime
Three
All Java applications can be written in terms of ____ types of program control.
Can we treat all types of exceptions the same?
All exceptions can be caught by using the Exception or Throwable type.
8 primitive data types
All of Java's numeric primitive data types are signed. Boolean (1 bit): true, false char (2 bytes): Unicode characters, ranging from 0 TO 65,535 byte (1 byte): -128 to 127 short (2 bytes): -32,768 TO 32,767 int (4 bytes): -2,147,483,648 TO 2,147,483,647 long (8 bytes): -9,223,372,036,854,775,808 TO +9,223,372,036,854,775,807 float (4 bytes): 1.40129846432481707e-45 TO 3.40282346638528860e+38 (+ or -) double (8 bytes): 4.94065645841246544e-324d TO 1.79769313486231570e+308d (+ or -)
Local variables A. Lose the values stored in them between calls to the method in which the variable is declared B. May have the same name as local variables in other methods C. Are hidden from other methods D. All of the above
All of the above
dot separator
Allows programmers to call methods of a particular class or object.
What does API stand for?
An application-programming interface (API) is a set of programming instructions and standards for accessing a Web-based software application or Web tool
forward slash (/)
An arithmetic operator that indicates division.
logic error
An error that does not prevent your application from compiling successfully but does cause your application to produce erroneous results.
syntax error
An error that occurs when code violates the grammatical rules of a programming language.
left operand
An expression that appears on the left side of a *binary operator*.
right operand
An expression that appears on the right side of a binary operator.
unary operator
An operator with only one operand (such as + or -).
Constructors are special methods defined in a class that are used to initialize ___ ___.
Answer: object instances Constructors must have the same name as the class name; the class Book will have constructors named Book (must be identical). Constructs are not allowed to explicitly declare that they return a type; rather, the implicit type they return is the enclosing class type in which they're defined.
What happens if you attempt to use a variable before it has been initialized?
Answers A syntax error may be generated by the compiler and A runtime error may occur during execution are correct
How many JCheckBoxes in a GUI can be selected at once?
Any number
API
Application Programming Interface; a code library for building programs
What is the difference between an array and an array list?
Array lists can only store objects while arrays can store objects or primitives. Arrays have a fixed size while arraylists can change size.
Types of Queues
ArrayDeque: double ended ArrayBlockingQueue: fixed capacity, FIFO PriorityQueue: ordered based on value
Types of Lists
ArrayList: resizable array LinkedList: FIFO Stack: LIFO Vector: deprecated
What is a static nested class?
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
Assertions
Assert that particular state must be true for program to proceed. Used for defensive programming and can be basis of formal programming proofs.
Assignment Conversion
Assignment conversion occurs when a value of one type is assigned to a variable of another Only widening conversions can happen via assignment
Given: 1//int a = 7; 2//static int ab = 9; 3//final static int abc = 6; 4//static void m1(){ 5//ab = 9 + 3; 6//a = a + 9; 7//abc++; } Where is the compilation error?
At Line 6, this is because a non-static variable is being accessed in a static method.
If you pass the first element of the array ar to the method x() like this, x(ar[0]); the element ar[0] : A. will be changed by the method x() B. cannot be changed by the method x() C. may be changed by the method x(), but not necessarily D. None of these
B. cannot be changed by the method x()
Consider a Rational class designed to represent rational numbers as a pair of int's, along with methods reduce (to reduce the rational to simplest form), gcd (to find the greatest common divisor of two int's), as well as methods for addition, subtraction, multiplication, and division. Why should the reduce and gcd methods be declared to be private.
Because they will only be called from methods inside of Rational
Why method overloading is not possible by changing the return type in java?
Becauseof ambiguity.
BLOB
Binary Large OBject - converted to byte arrays before being stored - important in cloud services - data that doesn't fit in standard data types e.g. pictures, media files, archives - alternative to serialization
Consider the following declaration. Scanner cin = new Scanner(System.in); int[] beta = new int[3]; int j; Which of the following input statements correctly input values into beta? (i) beta[0] = cin.nextInt(); beta[1] = cin.nextInt(); beta[2] = cin.nextInt(); (ii) for (j = 0; j < 3; j++) beta[j] = cin.nextInt();
Both (i) and (ii)
The condition expression1 && expression2 evaluates to true when __.
Both expressions are true.
Casting Conversion
Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value being converted double money = 84.69; int dollars =(int) money; // dollars = 84
What is the function of the dot operator?
Both, It allows one to access the data within an object when given a reference to the object and It allows one to invoke a method within an object when given a reference to the object are correct
Methods are commonly used to
Break a problem down into small manageable pieces
methods are commonly used to
Break a problem down into small manageable pieces.
Continuous Integration (CI)
Build generated whenever: - change to a defined repository - fixed intervals e.g. CruiseControl, Jenkins (previously Hudson) - configured using config.xml file - effectiveness depends on quality of system integration tests. limited by GUI's etc. Use mocks etc to overcome issues. http://www.thoughtworks.com/continuous-integration
CruiseControl
Build scheduler - <listeners> listen to the status of the build - <bootstrappers> actions to do before build
static fields and methods
By default, data members and methods are "instance" members and are said to be "non static." Non static instance data members are copied to each object instance of the class, so each object has its own copy. Non static methods can reference these copied data members through an implicit object reference (but you can access it via "this" when necessary). The concept of non static instance members is illustrated below. public class Book { private String title = ""; public void setTitle(String title) { this.title = title; } } When there's a need to not copy data members to each object instance, such as constants. They can remain in the class definition. Data members and methods that are not associated with object instances are call "class" members; they are local to the class and are not affiliated with the objects. Annotated with the keyword "static": public static final int CHECKOUT_DURATION = 21; Because the above data member is a class variable, it can be accessed through the class name as follows: int duration = Book.CHECKOUT_DURATION; Methods can also be designated as static: private static int nextId = 1; public static int getNextId() { return nextId++; } Above, method getNextId() provides access to the static data member and manages its next value. IMPORTANT: "static only sees static" but "non-static sees everything" static members can only access other static members; in particular, static members cannot access non-static members. Non-static members have access to all members (both static and non-static).
Method m1 has a declaration of void m1() and m2 has a method declaration of public static void m2(). m2 wants to call m2, how does m2 do that?
By making an instance of the class m1 is in and using that, or by changing its method declaration so it is not static.
You can create an array of three doubles by writing : A. double ar[] = 3; B. double ar[3]; C. double ar[] = { 1.1, 2.2, 3.3 }; D. double[] ar = double(3);
C. double ar[] = { 1.1, 2.2, 3.3 };
Which of the following methods returns an array ? A. int acpy(int n) { ... } B. int acpy(int[] n) { ... } C. int[] acpy(int n) { ... } D. None of these
C. int[] acpy(int n) { ... }
To create the array variable named ar, you would use : A. int ar; B. int() ar; C. int[] ar; D. None of these
C. int[] ar;
If you pass the array ar to the method m() like this, m(ar); the element ar[0] : A. will be changed by the method m() B. cannot be changed by the method m() C. may be changed by the method m(), but not necessarily D. None of these
C. may be changed by the method m(), but not necessarily
Here is a loop that should average the contents of the array named ar : double sum = 0.0; int n = 0; for (int i=0; i < ar.length; i++, n++) sum = sum + ar[i]; if ( ?????? ) System.out.println("Average = " + ( sum / n ); What goes where the ???? appears : A. sum > 0 B. n == 0 C. n > 0 D. None of these
C. n > 0
Objects example illustrated
CLASS Book title: String author: String isCheckedOut: boolean checkOut(): void checkIn(): void If a user checks out 2 books, each of them are assigned the class properties: Book Book title: Call of the Wild title: Gone with the Wind author: J. London author: M. Mitchell isCheckedOut: true isCheckedOut: true class is a type, and objects are instances of those types
________ is the brain of a computer.
CPU
Public modifier
Can be applied to a class and/or individual data members and methods within a class; indicates that the given item is accessible across package boundaries, the following class and method are both accessible outside the package in which they're defined. package domain; public class Book { public void checkOut() { } }
Default (no modifier)
Can be applied to a class and/or individual data members and methods within a class; indicates that the given item is not accessible across package boundaries (i.e., it limits access to members of the same package) e.g., the following class and method are NOT accessible outside the package in which they're defined. package domain; class Book { void checkout() { } }
Protected modifier
Can be applied to individual data members and methods (but cannot be applied to a class); when applied, it restricts access to members of the same class and any derived class; e.g., the following method, setHashCode, is only accessible to members of the LibraryItem class and any derived classes (e.g., Book). package domain; public class LibraryItem { protected void setHashCode() { } } package domain; public class Book extends LibraryItem { public LibraryItem () { setHashCode(); } }
Private
Can be applied to individual data members and methods (but cannot be applied to a class); when applied, it restricts access to members of the same class; e.g., the following data member, isbn, is only accessible to members of the Book class, and nowhere else. package domain; public class Book { private String isbn; public void getIsbn() { return isbn } }
Attributes (ANT)
Can contain references to a property. References resolved before task executed
When you overload a method defined in a superclass, you must do which one of these? 1. Change either the number, type, or order of parameters in the subclass. 2. Use an access specifier that is at least as permissive as the superclass method 3. Return exactly the same type as the original method. 4. Use exactly the same number and type of parameters as the original method.
Change either the number, type, or order of parameters in the subclass.
When you override a method defined in a superclass, you must do all of these except:
Change either the number, type, or order of parameters in the subclass.
semicolon (;)
Character used to terminate each statement in an application.
What are the different types of exception in Java?
Checked and unchecked exceptions. Checked exceptions are caught by the compiler while run time exceptions are ignored by the compiler and don't show up until run time.
Working directory
Checkout of the latest version of a project. May contain modified files that are not staged or committed. (Local)
UML Class diagram w/ general syntax
ClassName Properties Here Behaviors Here Book title: String author: String isCheckedOut: boolean checkOut(): void checkIn(): void Each property name is followed by its data type (e.g., String, boolean). Each method name is followed by its return type (e.g., void).
Object-Oriented Programming
Classes are the building blocks of a Java program; a blueprint for which individual objects can be created Each class is an abstraction of similar objects in the real world E.g., dogs, songs, houses, etc Once a class is established, multiple objects can be created from the same class. Each object is an instance (a concrete entity) of a corresponding class E.g., a particular dog, a particular song, a particular house, etc
event handler
Code that executes when a certain event occurs.
statement
Code that instructs the computer to perform a task. Every statement ends with a semicolon ( ; ) character. Most applications consist of many statements.
declaration
Code that specifies the name and type of a variable.
dir command
Command typed in a Command Prompt window to list the directory contents.
If two classes are not in the same class tree and an instanceof operator compares them what will be the output?
Compilation Error
GridBagLayout
Components placed in a grid. - given distinct sizes (# rows and # columns assigned to component. Most common for sophisticated GUIs.
BoxLayout
Components placed in box. Can be aligned left, centre, right, top, middle, bottom etc.
Intermediate Swing Level
Components used for laying out the UI (User Interface). JPanel, JInternalFrame, JScrollPane, JSplitPane, JTabbedPane (e.g. chrome browser has tabs at top)
Connection interface (JDBC)
Connection to DB through connection object Uses Singleton pattern = only one instance of connection. connection = DBConnection.getInstance(); try { Statement st = connection.createStatement();
What is a constant?
Constants are variables that cannot be changed.
What is constructor?
Constructor is just like a method that is used to initialize the state of an object. It is invoked at the time of object creation.
If method A calls Method B, and method B calls method C, and method C calls method D, when method D finishes, what happens?
Control is returned to method C
JTextArea
Control that allows the user to view multiline text.
A _ is a variable that helps control the number of times that a set of statements will execute.
Counter
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x++; System.out.println(x); 1. Sums the even elements in a. 2. Finds the largest value in a. 3. Counts the even elements in a. 4. Finds the smallest value in a.
Counts the even elements in a.
What does the following loop do? int[] a = {6, 1, 9, 5, 12, 3}; int len = a.length; int x = 0; for (int i = 0; i < len; i++) if (a[i] % 2 == 0) x++; System.out.println(x); 1. Sums the even elements in a. 2. Counts the even elements in a. 3. Finds the smallest value in a. 4. Finds the largest value in a.
Counts the even elements in a.
BufferedReader stdin = new BufferedReader(new InputStreamReader(system.in)) input = stdin.readLine();
Create BufferedReader instance containing a InputStreamReader instance with byte stream as input.
inheritance
Creating a new class based on an existing class (also called *extending a class*). This action is called ____.
extending a class
Creating a new class based on an existing class (also called *inheritance*). This action is called ____.
To print the last element in the array named ar, you can write : A. System.out.println(ar.length); B. System.out.println(ar[length]); C. System.out.println(ar[ar.length]); D. None of these
D
To print the last element in the array named ar, you can write : A. System.out.println(ar.length); B. System.out.println(ar[length]); C. System.out.println(ar[ar.length]); D. None of these
D. None of these
Suppose we have these two array definitions in main(): String[] hospName = new String[100]; int[] hospCode = new int[100]; hospCode[I] stores the code for a specific hospital. hospName[J] stores the name of the hospital that has code J. Suppose the code 24 is stored at position 13 of hospCode. Which expression below references 24's corresponding name? A. hospName[13] B. hospCode[24] C. hospCode[hospName[13]] D. hospName[hospCode[13]] E. hospName[hospCode[24]]
D. hospName[hospCode[13]] General Feedback: What we want is the name for hospital with code 24. We could get that with hospName[24], but that's not one of the options. However, we know that hospCode[13] contains the value 24, so we can use that instead.
set
Debugger command that is used to change the value of a variable.
stop
Debugger command that sets a breakpoint at the specified line of executable code.
run
Debugger command to begin executing an application with the Java debugger.
format
DecimalFormat method that *takes a double*, *returns a String* containing a *formatted number*.
How do you declare a String Builder/ String Buffer
Declaration: StringBuilder S2 = new StringBuilder("Test String") or by using the default constructor.
selected
Defines if a component has been selected. (property)
Counter-controlled repetition is also called _.
Definite repetition
Counter-controlled repetition is also called _____ because because the number of repetitions is known before the loop begins executing.
Definite repetition
In a @return tag statement the description
Describes the return value
In a @return tag statement the description A. Describes the return value B. Must be longer than one line C. Cannot be longer than one line D. Describes the parameter values
Describes the return value
JTextArea
Display textual data or accept large amounts of text input.
case sensitive
Distinguishes between uppercase and lowercase letters in code.
Define the keyword "static"
Does not change. Cannot make an instance of.
Creating Objects: Reference Variable
Dog is the data type. That's what reference allows us to do. It makes it user friendly by letting us make our own data types. We tell the computer to set aside a chunk of space for the data type, Dog. The size of the chunk will be big enough to hold an address, because reference is indirect. No actual amount will go in like with primitive datatypes where we know the amount of storage being used. It will just leave space (a placeholder)
Suppose we want to store a tic-tac-toe board in a program; it's a three-by-three array. It will store "O", "X" or a space at each location (that is, every location is used), and you use a two-dimensional array called board to store the individual tiles. Suppose you pass board to a method that accepts a two-dimensional array as a parameter. If the method was designed to process two-dimensional arrays of various sizes. What information about the size of the array would have to be passed to the method so it could properly process the array? A. the number of columns in the array B. the number of rows in the array C. the number of cells in the array D. Both A and B E. No additional information is needed, as the array carries its size information with it.
E. No additional information is needed, as the array carries its size information with it.
Suppose we define a class called NameInfo. It has several private fields, including String hospName; and several public methods, including one that accesses hospName: String getName(); Now, we define an array like this: NameInfo[] listOfHospitals = new NameInfo[100]; Which expression below correctly accesses the name of the hospital that's stored in position 5 (that is, the 6th element) of the listOfHospitals? A. listOfHospitals.getName(5) B. listOfHospitals.hospName[5] C. listOfHospitals[5].hospName D. listOfHospitals[getName(5)] E. listOfHospitals[5].getName()
E. listOfHospitals[5].getName()
What is the stack? What kinds of variables are created there?
Each Java virtual machine thread has a private Java virtual machine stack, created at the same time as the thread. A Java virtual machine stack stores frames. A Java virtual machine stack is analogous to the stack of a conventional language such as C: it holds local variables and partial results, and plays a part in method invocation and return. Because the Java virtual machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated.
How to Execute Programs
Each type of CPU executes only a particular machine language A program must be translated into machine language before it can be executed Compiler: translates only once Most high-level languages: C, C++, etc. Interpreter: translates every time you run programs Most scripting languages: python, perl, etc. The Java approach is somewhat different. It combines the use of a compiler and an interpreter.
Users cannot edit the text in a JTextArea if its _ property is set to false.
Editable
What are Encapsulation, Inheritance and Polymorphism?
Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions.
The following code fragment reads in two numbers: (Choose all that apply.) Scanner input = new Scanner(System.in); int i = input.nextInt(); double d = input.nextDouble(); What are the correct ways to enter these two numbers?
Enter an integer, a space, a double value, and then the Enter key. Enter an integer, two spaces, a double value, and then the Enter key. Enter an integer, an Enter key, a double value, and then the Enter key.
When is an instance block executed?
Every Time an instance of the class it was created is made. Before the constructor.
The string class
Every character string (enclosed in double quotation characters) is an object in Java defined by the String class Every character string can be used to create a string object Because strings are so common, we don't have to use the new operator to create a String object (special syntax that works only for strings) String name1 = "Steve Jobs"; It is equivalent to String name1 = new String("Steve Jobs");
What does the substring method written like this return - stringName.subString(1,5)?
Everything in that string starting from index one and up to 5-1 or 4.
What does the substring method written like this return - stringName.subString(6,5)?
Exception
What happens when you divide 0 by 0?
Exception
What happens when you divide and Int by 0?
Exception
Throwing & Catching Exceptions
Exceptions can be thrown either by the Java API or by your code. To throw an exception examples: throw new Exception(); throw new Exception("Some message goes here"); throw new LoginFailedException("User not authenticated"); Once an exception is thrown, the JVM starts looking for a handler in the call stack to transfer execution of the program. Exception handlers are declared in the context of a try/catch block. Catching Exceptions Java supports the catching of exceptions in what's known as a try/catch block or also known as a try/catch/finally block. Syntax for a try/catch block: try { ... } catch (SomeException e) { ... } The interpretation of the try/catch block is the following: the statements between the try and catch are executed sequentially, and if no exception occurs, then execution continues with the first statement that follows the try/catch block. On the other hand, if an exception occurs while executing the statements between the try/catch, execution transfers to the catch block, and then once the catch block finishes executing, execution continues with the first statement after the try/catch block.
redundant parentheses
Extra parentheses used in calculations to clarify the order in which calculations are performed. Such parentheses can be removed without affecting the results of the calculations.
What is final class?
Final class can't be inherited.
What is final method?
Final methods can't be overriden.
What is the ONLY modifier local variables can use?
Final, anything else will be a compilation error.
Jar
For the amount of code that contains thousands of classes is in keeping proof, they store them in compressed archives.
event source
GUI object where the event occurs
Quick Check: The Random Class
Given a Random object reference named gen, what range of values are produced by the following expression?
What does the method .toString do from the class object?
Gives a string representation of an object. This is usually overridden and if not will print the area memory.
Arrays
Group (or collection) of items that are the same type. declares an array object, daysOfWeek, as an array of seven String objects: String [ ] daysOfWeek = new String[7]; assign the seven elements as follows: daysOfWeek[0] = "Sunday"; daysOfWeek[1] = "Monday"; daysOfWeek[2] = "Tuesday"; daysOfWeek[3] = "Wednesday"; daysOfWeek[4] = "Thursday"; daysOfWeek[5] = "Friday"; daysOfWeek[6] = "Saturday"; values could be initialized at the point of declaration: private String [ ] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday" , "Thursday", "Friday", "Saturday"}; The size of the array is available via the length property (e.g., daysOfWeek.length), allowing you to iterate through its values in a "for loop": for (int i = 0; i<daysOfWeek.length; i++) { System.out.println(daysOfWeek[i]); } Array downside, once declared, their size is fixed. Can create a new, larger array and move the contents of the first array into the second, but that is clumsy. Typically used only for grouping items whose size is fixed.
Java Collection Framework
Group of interfaces, classes, and algorithms that together provide a rich set of abstractions for grouping objects. Maps - A collection whose entries are accessed by some unique identifier. Lists - A collection whose entries can be accessed with an index. Sets - A collection whose entries are guaranteed to be unique. Queues - A collection whose entries are ordered, based on some scheme.
________ is the physical aspect of the computer that can be seen.
Hardware
Creating objects
How to create objects once a class is established? How to "hold" those created objects? For primitive types (such as byte, int, double), we use a variable of that particular type as a cup to store its actual value BUT Objects are different There is actually no such thing as an object variable, because we can't put a number on it. There is only an object reference variable An object reference variable holds something like a pointer or an address that represents a way to get to the object. When you copy a string object, you're really copying it's address.
HTTP
Hypertext Transfer Protocol; the protocol that defines communication between web browsers and web servers
JOptionPane.WARNING_MESSAGE
Icon containing an exclamation point, cautions the user of potential problems.
Java Identifiers
Identifiers are the "words" in a program -Name of a class: Dog, MyFirstApp, and Lincoln -Name of a method: bark and main -Name of a variable: args (later in this course) Rules: A Java identifier can be made up of -letters -digits (cannot begin with a digit) -the underscore character ( _ ), -the dollar sign ($) Java is case sensitive: -Total, total, and TOTAL are different identifiers By convention, programmers use different case styles for different types of identifiers, such as title case for simple class names - Lincoln camel case for compound words - MyFirstApp upper case for constant variables - MAXIMUM
What is method overriding?
If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to provide the specific implementation of the method.
The body of a while statement executes _____.
If it's condition is true
Basic Program Execution
If there are errors the compiler will complain and not let us go onto the next step. We must trace back to the source and fix the problem in our code. It's important to understand why you're getting errors. LOOK IT UP debuggers can help you find errors in your code
How does the garbage collector know when to return memory to the heap?
If there is a pointer to the memory
What is final variable?
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Double
If... else is a ____-selection statement.
The Main Method
In Java, everything goes in a class (object-oriented) After you compile the source code (.java) into a bytecode or class file (.class), you can run the class using the Java Virtual Machine (JVM) When the JVM loads the class file, it starts looking for a special method called main, and then keeps running until the code in main is finished
Under what conditions can a local class access variables in the enclosing scope?
In addition, a local class has access to local variables. However, a local class can only access local variables that are declared final. When a local class accesses a local variable or parameter of the enclosing block, it captures that variable or parameter.
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Where is identifier x (block three's local variable) visible? 1. In two and block three 2. In block three and main 3. In block three only 4. In one and block three
In block three only
Classpath
Indicates where you can find another self-written classes
A(n) _ loop occurs when a condition in a while statement never becomes false.
Infinite
Access Modifiers
Information hiding is achieved through the use of access modifiers, which are keywords that are used to augment the visibility of various constructs. Public Default (no modifier) Protected Private
Binary Numbers
Information is stored in memory in digital form using the binary number system A single binary digit (0 or 1) is called a bit A single bit can represent two possible states, like a light bulb that is either on (1) or off (0) Permutations of bits are used to store values Devices that store and move information are cheaper and more reliable if they have to represent only two states
What is Inheritance?
Inheritance is a mechanism in which one object acquires all the properties and behaviour of another object of another class. It represents IS-A relationship. It is used for Code Resusability and Method Overriding.
git init
Initialise an empty repository
Inner & Anonymous Classes
Inner classes are defined within the context of another class. package domain; public class Book extends LibraryItem implements AuthorableItem, PrintedMaterial { BookReader reader = new BookReader(); // .rest of Book definition public String nextLine() { return reader.readNextLine(); } // Note that this is not a "public" class- //only an instance of Book can access the BookReader class BookReader { public BookReader() { } public String readNextLine() { // Implementation of this method. } } // BookReader } // Book Anonymous classes are also inner classes that are defined within the context of another class, but these classes do not have a name, hence the name anonymous. Anonymous inner classes are often used as event handlers in the implementation of graphical user interfaces.
Each class declares Instance Variables and Methods (Unique Values for the Objects in the Class)
Instance variables: descriptive characteristics or states of the object Ex. students are an instance variable of a class Methods: behaviors of the object (the actual doing thing of each instance variable) Ex. doing homework or taking exams are the methods of the instance variable "student"
What is static block?
Is used to initialize the static data member. It is excuted before main method at the time of classloading.
What is the advantage of putting an image in a JLabel instance?
It becomes part of the component and is laid out automatically
What is super in java?
It is a keyword that refers to the immediate parent class object.
In the following list, which statement is not true regarding Java as a programming language? 1) It is a relatively recent language, having been introduced in 1995 2) It is a language whose programs do not require translating into machine language before they are executed 3) It is an object-oriented programming language 4) It is a language that embraces the idea of writing programs to be executed using the World Wide Web 5) all of these are true
It is a language whose programs do not require translating into machine language before they are executed
Why we cannot override static method?
It is because the static method is the part of class and it is bound with class whereas instance method is bound with object and static gets memory in class area and instance gets memory in heap.
String Indexes
It is occasionally helpful to refer to a particular character within a string This can be done by specifying the character's numeric index The index begins at zero in each string In the string "Hello" H is at the index 0 and o is at the index 4
Scanner Class
It is often useful to design interactive programs that read input data from the user The Scanner class provides convenient methods for reading input values of various types A scanner object can be set up to read input values from various sources including the user typing values on the keyboard The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner(System.in); Once created, the Scanner object can be used to invoke various input methods, such as: String answer = scan.nextLine(); The nextLine method reads all of the input until the end of the line is found, and return it as one String
What b before calling method m1() that returns an int? int b = m1();
It is one
What is the object type of a polymorphic object instance and what does it have to be?
It is the initialization of the instance. The stuff after the equals sign. It has to be a child of the reference type.
What is the package with no name?
It is the package that is created by default if a class is not put in a package.
What does the method .finalize do from the class object?
It is used to make something ready for garbage collection.
What is overriding?
It is when a subclass uses the same name and same signature as a method in the parent class.
When instantiating a new instance of a class and you use final what does this mean?
It means you cannot allocate a new space in memory for that instance.
What does the method .clone do from the class object?
It throws an exception which must be caught.
What happens if their is no break in a switch statement?
It will continue down the case statements until a break is found.
Package
Items of related functionality, each item in the package has a unique name. Thus, a package is a namespace, where a namespace is a collection of uniquely named items. One of main packages is "java", does not contain any data types, it's used to aggregate other packages that are nested within it. java.applet java.awt java.beans java.io java.util nested package example: java.util.concurrent.locks other nested packages do contain type definitions: - java.util contains the Date class (and other classes) - java.util.concurrent contains the Semaphore class (and other classes) - java.util.concurrent.locks contains the LockSupport (and other classes)
When an argument is passed to a method,
Its value is copied into the method's parameter variable
The ___ constant can be used to display an error message in a message dialog.
JOptionPane.ERROR_MESSAGE
The ________ method displays a message dialog box.
JOptionPane.showMessageDialog(null, "Welcome to Java!", "Example 1.2 Output", JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(null, "Welcome to Java!");
The _ component allows users to add and view multiline text.
JTextArea
Which of the following GUI components is used to accept input into a JFrame? 1) JLabel 2) JPanel 3) JInput 4) JTextField 5) JInputField
JTextField
Why main method is static?
JVM creats object first then call main() method that will lead to the problem of extra memory allocation.
What is difference between JDK,JRE and JVM?
JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed. JRE stands for Java Runtime Environment. It is the implementation of JVM and physically exists. JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.
________is interpreted.
Java
________is an object-oriented programming language.
Java C++
Swing
Java GUI programming toolkit - Native code windows - 4 heavyweight components - lightweight - look and feel can be changed (can be set or depend on platform) - wide range of widgets
Abstract Windowing Toolkit (AWT)
Java GUI programming toolkit - native widgets - heavyweight components - small range of widgets - look and feel can not be changed. - Dependent on platform. OLD.
JSE JEE JME Java Card
Java Standard Edition - Contains the core functionality of the Java language; used to develop desktop applications. Java Enterprise Edition - Provides additional functionality required of enterprise applications, including web applications. Java Micro Edition - A scaled-down version used for mobile phones and other handheld devices. Java Card - The smallest Java footprint used for integrated circuits (e.g., memory and microprocessor cards).
Java Development Kit (JDK)
Java compiler and interpreter. includes JRE and JSE API
________is a technical definition of the language that includes the syntax and semantics of the Java programming language.
Java language specification
Java portability
Java source code (.java) > Java compiler > Java bytecode program (.class or .jar) > OS Just In Time (JIT) compiler > OS machine code
Implicit cast
Java takes the value of a variable of the narrower type and stops this value in a variable with a different type with more storage options.
________ is a software that interprets Java bytecode.
Java virtual machine
String class
Java's String class is used to represent a sequence (i.e., string) of characters. A simplified class diagram of String is shown below: STRING count : int value : char[] String() String(orig:String) length : int charAt(index:int) : char concat(st : String) : String equals(obj : String) : boolean indexOf(str : String) : int isEmpty() : boolean lastIndexOf(str : String) : int length() : int replace(oldChar : char , newChar : char) : String substring(beginIndex : int, endIndex : int) : String toLowerCase() : String toUpperCase() : String toString : String * Extends class Object and thus inherits Object's properties and behavior, including method equals(Object); * Encapsulates private fields (e.g., count and value), prevents direct access to these fields by other objects; indirect access is provided through public methods; e.g., the method length() provides access to the count field; * Has two overloaded constructors, String() and String(String s). The first constructor takes no parameters, and the second takes a String object that is copied into the new String object; * Overrides methods toString() and equals() inherited from class Object by providing its own implementations; * Exhibits polymorphism (one interface, multiple behaviors) with methods toString() and equals();
Who will do the Java compiling?
Javac is the complier, not Eclipse. Eclipse is the software that runs javac. The Java virtual machine (the executable response) is called java For one class... what is the mechanism that allows us to run it? Answer: we are using an existing object
What is JIT compiler?
Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
Event Listeners (Observer?)
Listen for events in components. Instances of Listener classes. Provided in interfaces.
Which of the following is a constant, according to Java naming conventions? (Choose all that apply.) 1) MAX_VALUE 2) Test 3) read 4) ReadInt 5) COUNT
MAX_VALUE COUNT
Benefits of Encapsulation*
Maintainability, Flexibility and Extensibility.
In order to preserve encapsulation of an object, we would do all of the following except for which one?
Make the class final
How many types of memory areas are allocated by JVM?
Many types: Class(Method) Area, Heap, Stack, Program Counter Register, Native Method Stack
Since you cannot take the square root of a negative number, you might use which of the following instructions to find the square root of the variable x?
Math.sqrt(Math.abs(x));
kilobyte
Maximum memory size is 2^10 memory bytes
megabyte
Maximum memory size is 2^20 memory bytes
gigabyte
Maximum memory size is 2^30 memory bytes
Difference between method Overloading and Overriding.
Method Overloading Method Overriding 1) Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its super class. 2) method overlaoding is occurs within the class. Method overriding occurs in two classes that have IS-A relationship. 3) In this case, parameter must be different. In this case, parameter must be same.
polymorphism
Method overloading is an example of polymorphism. polymorphism can be defined as "one interface with multiple behaviors." Another form of polymorphism is method overriding, which is an example of dynamic binding. Method overriding is discussed later in this topic.
Define the keyword "return"
Method that returns.
What are the two things classes have?
Methods and Variables.
Mocking
Mocks objects that exist outside the program. Use for TDD.
Abstract Data Types
Model of a data structure e.g. Stack(). Describes the behaviour of the data type.
formatting
Modifying the appearance of text for display purposes.
Thread communication
Multiple threads notify each other when conditions change, when to wait or stop waiting. - void wait(), wait(long time), wait(long time, int nano) - void notify() - void notifyAll()
What happens when you divide 0.0 by 0.0 or 0?
NaN(Not a Number)
Can a class be private?
No
Can a local variable be protected?
No
Can a local variable be static?
No
Can a short be passed to the append method in String Builder?
No
Can a static method be overridden without the static modifier and vise versa?
No
Can an abstract method be static?
No
Does the StringBuilder class override the equals method in object?
No
If a class has a private constructor can their be an instance of that class(object) outside of the class?
No
Can a class be protected(Given it is not an inner class)?
No - Inner classes can be private or protected regular classes cannot.
Is it legal to have the same method with the same parameters but a different return type?
No - The parameters have to be different.
Can you override Strings methods if yes why?
No because String is a final class.
Will this compile and if not why? Short ss = new Short(9);
No, 9 is automatically an int and their is no int constructor for short.
Is constructor inherited?
No, constructor is not inherited.
Is it possible for an interface to be an object type in a polymorphic object?
No, interfaces can't be instantiated.
Can local variables use the static modifier?
No, local variables can only use the final modifier.
Can you call a non static method in main without using an instance of the class?
No, main is static and therefore cannot call non static variables or methods.
Are primitive data types considered objects in Java?
No, primitive types are the only elements of the Java language that are not modeled as objects.
Can local variables use access modifiers?
No, since local variables are local they will not be seen outside of the class.
Is it legal for a non-static method to be called in a static one?
No, static methods and variables cannot be called in non static methods and vice versa.
Can you statically import a package?
No, you can only import classes statically.
Does Java have multiple inheritance?*
No. Instead deal with interfaces.
Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Which of these fields or methods are inherited by the Person class? 1. getName(), setName(), studentID, getID() 2. getName(), setName(), name 3. None of them 4. studentID, name, getName(), setName(), getID() 5. name, getName(), setName(), getID()
None of them
To print the last element in the array named ar, you can write : A. System.out.println(ar.length); B. System.out.println(ar[length]); C. System.out.println(ar[ar.length]); D. None of these
None of these
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 1; if (j > 2) alpha[j - 1] = alpha[j] + 2; }
None of these
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 1; if (j > 2) alpha[j - 1] = alpha[j] + 2; } 1. alpha = {1, 2, 3, 4, 5} 2. alpha = {4, 5, 6, 7, 9} 3. alpha = {1, 5, 6, 7, 5} 4. None of these
None of these
Define "Null"
Null means nothing. It's a place holder.
What does String Buffer extend?
Object
What is difference between object oriented programming language and object based programming language?
Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc.
Which class is the superclass for every class.
Object class.
Object class
Object is base class of all Java classes. All Java classes extend (inherit) class Object either directly or indirectly. these 2 definitions are exactly the same: public class Book {...} public class Book extends Object {...}
Assignment Operators
Often we perform an operation on a variable, and then store the result back into that variable Java provides assignment operators to simplify that process For example, the statement num += count; is equivalent to num = num + count; Other assignment operators: -=, *=, /=, %=
Inheritance
One class can be used to derive another via inheritance Classes can be organized into hierarchies
Inheritance
One of the 3 main pinnacles of object-oriented programming (the others being encapsulation and polymorphism). Inheritance is a means by which a class extends another class, it acquires the properties and behavior of the class that's being extended. Sometimes called generalization/specialization, also called an "is a" relationship. For example, the class declarations of Book, Audio, and Periodical are shown below: package domain; public class Book extends LibraryItem { // properties and behavior of Book go here } package domain; public class Audio extends LibraryItem { // properties and behavior of Audio go here } package domain; public class Periodical extends LibraryItem { // properties and behavior of Periodical go here } class can only extend one other class -- cannot extend multiple classes
Breakpoint
One reason to set a _____ is to be able to examine the values of variables at that point in the application's execution.
Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following sets of statements are valid (both syntactically and semantically) in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); 1. Both (i) and (ii) 2. Only (ii) 3. Only (i) 4. None of these
Only (i)
Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following sets of statements are valid (both syntactically and semantically) in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); 1. Only (ii) 2. None of these 3. Only (i) 4. Both (i) and (ii)
Only (i)
Suppose you have the following declaration. int[] beta = new int[50]; Which of the following is a valid element of beta. (i) beta[0] (ii) beta[50]
Only (i)
Which of the following about Java arrays is true? (i) All components must be of the same type. (ii) The array index and array element must be of the same type.
Only (i)
Which of the following statements creates alpha, an array of 5 components of the type int, and initializes each component to 10? (i) int[] alpha = {10, 10, 10, 10, 10}; (ii) int[5] alpha = {10, 10, 10, 10, 10}
Only (i)
Consider the following declaration. int[] alpha = new int[3]; Which of the following input statements correctly input values into alpha? (i) alpha = cin.nextInt(); alpha = cin.nextInt(); alpha = cin.nextInt(); (ii) alpha[0] = cin.nextInt(); alpha[1] = cin.nextInt(); alpha[2] = cin.nextInt(); 1. Only (i) 2. Only (ii) 3. None of these 4. Both (i) and (ii)
Only (ii)
Which of the following creates an array of 25 components of the type int? (i) int[] alpha = new[25]; (ii) int[] alpha = new int[25];
Only (ii)
Which of the following creates an array of 25 components of the type int? (i) int[] alpha = new[25]; (ii) int[] alpha = new int[25]; 1. Only (ii) 2. None of these 3. Only (i) 4. Both (i) and (ii)
Only (ii)
Which of the following statements creates alpha, a two-dimensional array of 10 rows and 5 columns, wherein each component is of the type int? 1. Both (i) and (ii) 2. Only (ii) 3. None of these 4. Only (i)
Only (ii)
Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Which of the following statements correctly instantiate the Rectangle object myRectangle? (i) myRectangle Rectangle = new Rectangle(10, 12); (ii) class Rectangle myRectangle = new Rectangle(10, 12); (iii) Rectangle myRectangle = new Rectangle(10, 12); 1. Only (ii) 2. Only (iii) 3. Only (i) 4. Both (ii) and (iii)
Only (iii)
Which properties are true of String objects? 1) Their lengths never change 2) The shortest string has zero length 3) Individual characters within a String may be changed using the replace method 4) The index of the first character in a string is one 5) Only Their lengths never change and The shortest string has zero length are true
Only Their lengths never change and The shortest string has zero length are true
relational operators
Operators < (less than), > (greater than), <= (less than or equal to) and >= (greater than or equal to) that compare two values.
equality operators
Operators == (is equal to) and != (is not equal to) that compare two values.
Another Example
Output A quote by Abraham Lincoln: Whatever you are, be a good one.
Overriding*
Overriding and overloading support polymorphism. - Abstract class (or concrete class) implement method - subclass with same signature override superclass method. - JVM begins at bottom of type hierarchy and searches up until match found to determine which method to run. - within subclass can call superclass method with super.method()
FlowLayout
Place components in the window from left to right, top to bottom.
Nesting
Placing an if...else statement inside another one is an example of ____ if-else statements.
Why Java does not support pointers?
Pointer is a variable that refers to the memory address. They are not used in java because they are unsafe(unsecured) and complex to understand.
Head pointer (GIT)
Points to the current branch.
PreparedStatement (JDBC)
Precompiled SQL statements at object creation time rather than execution time. - Use ? to indicate parameters for the statement and fill in later. public static final String SELECT_SQL = "SELECT * FROM names ORDER BY age"; select = connection.prepareStatement(SELECT_SQL); ResultSet rs = select.executeQuery(); insert.setString(1, "Zaphod Beeblebrox"); insert.setInt(2, 26); insert.executeUpdate(); // So 1 is names and 2 is age.
Declare the data type of a variable.
Primitive types are used to declare the data types of variables where a variable is a named memory location. datatype variableName = initialvalue; The following statements illustrate the use of Java's eight primitive data types in variable declarations: char c = 'a'; Boolean succeeded = false; byte age = 0; short index = 0; int ssn = 0; long length = 0; float pi = 3.14159f; double d = 0.0; floating point literals are defaulted to a "double" data type. To compile certain types, such as float, add a suffix to the literal: float pi = 3.14159f;
OO definitions
Programming paradigm that views programs as cooperating objects, rather than sequences of procedures Focuses on design of abstract data types, which define possible states and operations on variables of that type
Promotion Conversion
Promotion happens automatically when operators in expressions convert their operands Example: int count = 12; double sum = 490.27; double result = sum / count; The value of count is converted to a floating point value to perform the division calculation
What is a well defined class?
Public interface (clearly defined responsibility --single-responsibility principle--Cohesion: the defined responsibilities of the class are meaningful - they make sense -- Delegation: if a task falls outside the responsibility of that class, the task is delegated to another class) Private Implementation (Encapsulation: data-hiding - fields are private (only accessed by getters and setters) and methods not a part of the user interface are private)
What does array.asList do?
Puts an array as an array list.
wait() (Thread Communication)
Puts current thread into blocked state. - can only call from method that has a lock (is synchronized) - Releases lock - Either waits specified time or until notified by another thread. - Best to put in while loop. - useful when all threads
Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (size < capacity && value > 0) { a[size] = value; } 1. Reads up to 3 values and places them in the array in the unused space. 2. Reads one value and places it in the remaining first unused space endlessly. 3. Reads up to 3 values and inserts them in the array in the correct position. 4. Crashes at runtime because it tries to write beyond the array.
Reads one value and places it in the remaining first unused space endlessly.
Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object) int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6; int value = cin.nextInt(); while (size < capacity && value > 0) { a[size] = value; size++; value = cin.nextInt(); } 1. Reads one value and places it in the remaining first unused space endlessly. 2. Crashes at runtime because it tries to write beyond the array. 3. Reads up to 3 values and places them in the array in the unused space. 4. Reads up to 3 values and inserts them in the array in the correct position.
Reads up to 3 values and places them in the array in the unused space.
CallableStatement (JDBC)
Relies on a stored procedure. Can contain ? placeholders. public static final String INSERT_SQL = "call addName(?, ?)"; insert = connection.prepareCall(INSERT_SQL); ResultSet rs = select.executeQuery(); insert.setString(1, "Zaphod Beeblebrox"); insert.setInt(2, 26); insert.executeUpdate();
What does the following loop do? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; a[pos] = a[size - 1]; size--;
Removes the 1 from the array, replacing it with the 7. Array now unordered.
Which of the following is not part of a method call? A. Return type B. Parentheses C. Method name D. All of the above are part of a method call
Return type
executeQuery (SQL command)
Returns ResultSet. Use for SELECT. ResultSet rs = st.executeQuery("SELECT * FROM names")
What does the method .compareTo do from the class String?
Returns a integer when comparing to strings. Ex: String s = new String("sam"); String s1 = new String("Sam"); s.compareTo(s1); ------- Returns 32 because S and s are 32 unicode codes away.
execute (SQL command)
Returns boolean use for RENAME, DROP TABLE etc. st.execute("DROP TABLE names");
What does the method .getClass do from the class object?
Returns class name of an object.
What does the substring method written like this return - stringName.subString(3,3)?
Returns nothing
What does the .indexOf() method return?
Returns the first occurrence of the char, or string. If a number is provided this is where the method starts looking for the specified string/char.
operator precedence
Rules of ____ ____ determine the precise order in which operators are applied in an expression.
What happens if their is no main method?
Runtime Error.
What Java Can Do
Science and Technology -Popular machine learning libraries are written in Java: Mahout, Weka -Has been adopted in many distributed environments (Hadoop) Web development -Most web backend are developed using Java Mobile application development -Android development platform Graph user interface (GUI) design: menu, windows, ...
What is scope?
Scope refers to the lifetime and accessibility of a variable. How large the scope is depends on where a variable is declared. For example, if a variable is declared at the top of a class then it will accessible to all of the class methods. If it's declared in a method then it can only be used in that method.
setEditable
Sets the editable property of the JTextArea component to specify whether or not the user can edit the text in the JTextArea.
Design patterns
Smart solutions for complex problems, which are given to us in the form of abstract descriptions.
________ are instructions to the computer.
Software Programs
return
Some methods, when called, __ a value to the statement in the application that called the method. The returned value can then be used in that statement.
Data Conversion
Sometimes it is convenient to covert data from one type to another For example in a particular situation we may want to treat an integer as a floating point value These conversions do not change the type of a variable or the value that's stored in it - they only convert a value as part of a computation Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) In Java, data conversions can occur in three ways: -assignment conversion -promotion -casting
White Space
Spaces, new lines, and tabs are called white space White space is used to separate words and symbols in a program Extra white space is ignored by the computer A valid Java program can be formatted many ways Programs should be formatted to enhance readability, using consistent indentation
isSelected
Specifies whether the JCheckBox is selected (true) or deselected (false): JCheckBox._____. (method)
BorderLayout
Splits area into 5 predefined spaces: South, north, west, east and center
jdb
Starts the Java debugger when typed at the Command Prompt.
Static Variables and Threads
Static Variables are NOT thread safe. - Use ThreadLocal or InheritableThreadLocal type declaration
What do static imports import?
Static variables and static methods.
Following Java naming convention, which of the following would be the best name for a class about store customers? 1) StoreCustomer 2) Store Customer 3) storeCustomer 4) STORE_CUSTOMER 5) Store-Customer
StoreCustomer
Distributed version control
Stored local, everyone has a copy of the entire repository and its history. - very low latency for file inspection, copy and comparisons.
public static String exampleMethod(int n, char ch) Based on the method heading above, what is the return type of the value returned? 1. char 2. String 3. int 4. Nothing will be returned
String
Some String Methods
String name1 = new String("Steve Jobs"); int numChars = name1.length(); char c = name1.charAt(2); String name2 = name1.replace('e', 'x'); String name3 = name1.substring(1, 7); String name5 = name1.toLowerCase();
Syntax to create a String
String s1 = new String("Hello World"); Can be created and initialized without using new: String s2 = "Hello World"; Can be concatenated with the + operator: String s3 = "Hello " + "World"; Operator == compares object references (and not the object's state), and since s1, s2 and s3 reference different String objects, == returns false: (s1 == s2); // returns false (s2 == s3); // returns false (s1 == s3); // returns false String's implementation of equals(Object) examines the values of the strings, this is true: s1.equals(s2); s2.equals(s3); s1.equals(s3); Strings objects created with the "new" operator that have the same value (the same string of characters) are always "equals()" to each other, but since they are different objects, they are never "==" to each other. One last subtle point: strings created using the double quote syntax with the same value without the new operator are always = = to each other. String s4 = "Hello World"; String s5 = "Hello World"; (s4 == s5); // returns true
UML Diagrams - list the structure diagrams
Structure Diagrams - CCCODPP Composite Structure Class Component Object Deployment Profile Package
Von Neumann architecture
Structure and organization of virtually all modern computers are based off this design. Consists of 3 major characteristics. 1 - Four major subsystems called memory, input/output, arithmetic/logic unit, and control unit. 2 - stored program concept. 3 - sequential execution of instructions
Signature rule (subtypes)
Subtypes must have signature-compatible methods for all of the supertypes methods. ArrayList<String> is a subtype of List<String>
Properties rule (subtypes)
Subtypes must preserve all of the provable properties of the supertype. Anything provable about A is provable about B.
Example of the Dot Operator in Use
System.out.println revisited There is a class called System, which contains an object reference variable out as one of its instance variables The object referenced by out has a method called println
Which of the following statements is correct to display Welcome to Java on the console? (Choose all that apply.) 1) System.out.println('Welcome to Java'); 2) System.out.println("Welcome to Java"); 3) System.println('Welcome to Java'); 4) System.out.print('Welcome to Java'); 5) System.out.print("Welcome to Java");
System.out.println("Welcome to Java"); System.out.print("Welcome to Java");
Which of the following statement prints smith\exam1\test.txt?
System.out.println("smith\exam1\test.txt");
To print the last element in the array named ar, you can write : A. System.out.println(ar[length-1]); B. System.out.println(ar[length()-1]); C. System.out.println(ar[ar.length-1]); D. System.out.println(ar[ar.length]);
System.out.println(ar[ar.length-1]);
how to pass an object to a method
System.out.println(new Date()):
Assume that x is a double that stores 0.362491. To output this value as 36%, you could use the NumberFormat class with NumberFormat nf = NumberFormat.getPercentInstance( ); Which of the following statements then would output x as 36%?
System.out.println(nf.format(x));
git add
Tells git to track files. Tells git to stage tracked files that have been modified. Recursive.
@Test(expected = X.class)
Test is expected to throw exception X.
In the Swing GUI framework use event handlers to respond to GUI based actions. Case of component responding to button click, models works by requiring:
That the component implement the actionListener interface, that the JButton add the component as an active listener in its collection and that the component provide suitable responses to be called from within the actionPerformed method once the event is triggered.
Multiplies
The *= operator ____ the value of its left operand by the value of the right one and store it in the left one.
*decision*
The *diamond-shaped* symbol in a UML activity diagram that indicates a ____ is to be made.
The + Operator
The + operator is also used for arithmetic addition The function that it performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation If both operands are numeric, then it adds them The + operator is evaluated left to right, but parentheses can be used to force the order If both of its operands are strings, or if one is a string and one is a number, it performs string concatenation. But if both operands are numeric, it performs addition.
What is the main difference between Java platform and other platforms?
The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms.It has two components: Runtime Environment, API(Application Programming Interface)
The Math Class
The Math class is part of the java.lang package The Math class contains methods that perform various mathematical functions These include: absolute value square root exponentiation trigonometric functions The methods of the Math class are static methods (also called class methods) Static methods never use instance variable values Math class does not have any instance variables Nothing to be gained by making an object of Math class Static methods are invoked through the class name - no object of the Math class is needed value = Math.abs(90) + Math.sqrt(100);
The Random Class
The Random class is part of the java.util package It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values nextFloat() generates a random number [0, 1) nextInt() generates a random integer over all possible int values (positive or negative) nextInt(n) generates a random integer [0, n-1]
Diamond (in the UML)
The UML symbol that represents the decision symbol or the merge symbol, depending on how it is used.
size
The ____ of a variable holds the number of bytes required to store a value of the variable's type. For example, an int is stored in four bytes of memory and a double is stored in eight bytes.
name
The ____ of a variable is used in an application to access or modify a variable's value.
type
The ____ of a variable specifies the kind of data that can be stored in a variable and the range of values that can be stored, such as an integer holding 1, and a double holding 1.01.
+=
The _____ operator assigns to the left operand the result of adding the left and right operands.
==, <= and <
The ______ operators return false if the left operand is greater than the right operand.
workflow
The activity of a portion of a software system.
RGB value
The amount of red. green and blue needed to create a color.
Title bar
The area at the top of a JFrame where its title appears.
initialization value
The beginning value of a variable.
{}
The body of an if statement that contains multiple statements is placed in _____.
What gives Java its 'write once and run anywhere' nature?
The bytecode. Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform.
Which of the following statements about strings is NOT true? 1. The class String contains many methods that allow you to change an existing string. 2. A String variable is actually a reference variable. 3. When a string is assigned to a String variable, the string cannot be changed. 4. When you use the assignment operator to assign a string to a String variable, the computer allocates memory space large enough to store the string.
The class String contains many methods that allow you to change an existing string.
class declaration
The code that defines a class, beginning with the class keyword.
How Java Works
The compiled bytecode is not the machine language for traditional CPU and is platform-independent javac and java (two command-line tools) can be found in the directory of bin/ of Java Development Kit (JDK) you will install
JLabel
The component that displays text or an image that the user cannot modify.
The header of a value-returning method must specify this. A. The method's local variable name B. The data type of the return value C. The name of the variable in the calling program that will receive the returned value D. All of the above
The data type of the return value
What is the purpose of default constructor?
The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class.
making your first object - The dot operator explained
The dot operator (,) give access to an object's state and behavior ( instance variables and methods). // make new object Dog d= new Dog(); //tell the dog to bark by using dot operator //om the variable d to call the bark() d.bark(); //set its size using the dot operator d.size=40;
Decimal points
The double type can be used to store numbers with ____ ____.
keyPressed event
The event that occurs when any key is pressed in a JTextField.
What does a finally block do?
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
class name
The identifier used as the name of a class.
The if Statement
The if statement has the following syntax: if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression (must evaluate to either true or false) If the condition is true, the statement is executed. If it is false, the statement is skipped. An if statement with its boolean condition: if (total == sum) system.out.println("total equals sum"); Another if statement with its boolean condition: if (total != sum) system.out.println("total does NOT equals sum");
Enumeration constants
The individual values that can take a variable of data type enumeration.
What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references.
setBounds
The location and size of a JLabel can be specified with _____.
Logical NOT
The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then !a is false; if a is false, then !a is true Logical expressions can be shown using a truth table. A truth table shows all possible true-false combinations of the terms.
Program Development
The mechanics of developing a program include several activities: -writing the program (source code) in a specific programming language (such as Java) using an editor -translating the program (through a compiler or an interpreter) into a form that the computer can execute -investigating and fixing various types of errors that can occur using a debugger Integrated development environments, such as Eclipse, can be used to help with all parts of this process
What happens when you call the .equals method for a StringBuilder?
The memory location is shown.
The 2nd argument passed to method JOptionPane.showMessageDialog is ____.
The message displayed by the dialog
Consider the following enumeration enum Speed { FAST, MEDIUM, SLOW };
The name of the Speed enumeration whose ordinal value is zero is FAST
Objects and the Heap
The number of objects that a program creates is not known until the program is actually executed Java uses a memory area called the heap to handle this situation, which is a dynamic pool of memory on which objects that are created are stored When an object is created, it is placed in the heap -Two or more references that refer to the same object are called aliases of each other -One object can be accessed using multiple reference variables -Changing an object through one reference changes it for all of its aliases, because there is really only one object
Conditional Statements
The order of statement execution is called the flow of control A conditional statement lets us choose which statement will be executed next The Java conditional statements are the: -if and if-else statement -switch statement
value of a variable
The piece of data that is stored in a variable's location in memory.
Sequential
The process of application statements executing one after another in the order in which they are written is called ____ execution.
Functional decomposition is
The process of breaking a problem down into smaller pieces.
nondestructive
The process of reading from a memory location, which does not modify the value in that location.
Decrementing
The process of subtracting 1 from an integer.
Say you write a program that makes use of the Random class, but you fail to include an import statement for java.util.Random (or java.util.*). What will happen when you attempt to compile and run your program.
The program won't compile-you'll receive a syntax error about the missing class.
bounds property
The property that specifies both the location and size of a component.
horizontalAlignment property
The property that specifies how text is aligned within a JLabel is called:
horizontalAlignment property
The property that specifies the text alignment in a JTextField (JTextField.LEFT, JTextField.CENTER, or JTextField.RIGHT).
text property
The property that specifies the text displayed by a JLabel.
Syntax
The rules of a language that define how we can combine symbols, reserved words, and identifiers to make a valid program -Identifiers cannot begin with a digit -Curly braces are used to begin and end classes and methods
When implementing an interface's method that throws an exception what must the implemented exception throw?
The same exception or a subclass or no throw clause at all.
What must be the return type of a method overriding a subclass of another method from a superclass.
The same or a subclass of it. if the method was returning object the subclass method could return String.
Semantics
The semantics of a program statement define what that statement means (its purpose or role in a program) A program that is syntactically correct is not necessarily logically (semantically) correct A program will always do what we tell it to do, not what we meant to tell it to do
program control
The task of executing an application's statements in the correct order.
functionality
The tasks or actions an application can execute.
Sequence, selection and repetition
The three types of program control are _____.
.java file
The type of file in which programmers write the Java code for an application.
.class file
The type of file that is executed by the Java Runtime Environment (JRE). A ____ file is created by compiling the application's .java file.
Language Levels
There are four programming language levels. Each type of CPU has its own specific machine language The other levels were created to make it easier for a human being to read and write programs
Comments
There are two forms of comments, which should be included to explain the purpose of the program and describe processing steps They do not affect how a program works
Another way to generate a Random Number
There is another way to generate a random double number [0,1) double newRand = Math.random(); as opposed to import java.util.Random; Random generator = new Random(); float newRand = generator.nextFloat();
double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is the value of vals[4][1] in the array above? 1. 7.1 2. There is no such value. 3. 7.3 4. 1.1
There is no such value.
Logical Operators
They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands)
What does the term generic mean?
They allow "a type or method to operate on objects of various types while providing compile-time type safety."[1] This feature specifies the type of objects stored in a Java Collection. List<String> v = new ArrayList<>();
EJB
They run on the server are not graphically oriented, but rather will perform tasks in database manipulation, network, ...
When designing a class what should you think about
Think about things the object does , and things the object does
if...else statement
This double-selection statement performs action(s) if a condition is true and performs different action(s) if the condition is false.
multiplication operator
This operator is an asterisk (*), used to ____ its two numeric operands.
assignment operator
This operator, =, copies the value of the expression on the right side into the variable.
If a parent throws an exception what must its child constructor do?
Throw that exception or a subclass of it or don't throw anything at all.
TCP
Transport Control Protocol; the two programs at the source and destination node need to establish a connection; that is, they must first inform each other of the impending message exchange, and they must describe the "quality of service" they want to receive. TCP uses the ARQ algorithm
Observable
Use instead of Subject interface for Observer pattern, Observable aware of its status and it's Observers unlike Subject.
Scanner keyboard = new Scanner(System.in); x = keyboard.nextInt(); y = keyboard.nextLine();
Use scanner for keyboard input. nextInt() scans in next token as an integer nextLine() scans in current line
How do you find the length of a String?
Use the .length() method.
JDesktopPane
Use to create a virtual desktop or multiple-document interface. Use as main frame when you want to have internal frame.
Throwable
Used to define own exceptions.
showMessageDialog
Used to display a message dialog: JOptionPane.____.
JDBC (Java Database Connectivity)
Used to interface DBMS and Java code. - Gives database vendor independence. - Java gives platform dependence Allows: 1. Making connection to database 2. Creating SQL or MySQL statements 3. Executing SQL or MySQL queries to database 4. Viewing and modifying the resulting records.
ResultSet (JDBC)
Used to store the result of an SQL query. // get all current entries ResultSet rs = select.executeQuery(); // use metadata to get the number of columns int columnCount = rs.getMetaData().getColumnCount(); // output each row while (rs.next()) { for (int i = 0; i < columnCount; i++) { System.out.println(rs.getString(i + 1)); }
JTextField.CENTER
Used with setHorizontalAlignment to center align the text in a JTextField.
JTextField.LEFT
Used with setHorizontalAlignment to left align the text in a JTextField.
JTextField.RIGHT
Used with setHorizontalAlignment to right align the text in a JTextField.
The comparing method: equals(Object)
Using equals(Object): boolean areEqual = book1.equals(book2); It compares object references, compares to see if book1 and book2 reference the same Book object in memory. In the example above, book1 and book2 reference different Book objects, so the boolean variable areEqual is set to false. This one would be true: Book book1 = new Book(); Book book2 = book1; boolean areEqual = book1.equals(book2);
How do you declare a CONSTANT in Java?
Using the keyword "final": final float pi = 3.14159f;
This type of method method performs a task and sends a value back to the code that called it.
Value-returning
This type of method method performs a task and sends a value back to the code that called it. A. Local B. Void C. Complex D. Value-returning
Value-returning
double
Variable type that is used to store floating-point numbers.
Which of the following is NOT an actual parameter? 1. Expressions used in a method call 2. Constant values used in a method call 3. Variables used in a method call 4. Variables defined in a method heading
Variables defined in a method heading
Thread safe variables
Variables that belong to only one thread. - Local variables are thread safe! - Instance and static variables are not thread safe
How are Servlets and JSP Pages related?
When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.
Garbage Collection
When an object no longer has valid references to it, it can no longer be accessed by the program The object is useless and therefore is called garbage Java performs automatic garbage collection periodically, returning and object's memory to the system for use In other languages the programmer is responsible for performing garbage collection
What does it mean when something is passed by reference?
When something is passed by reference, changes made to it will be changed. You are passing the reference of the object and therefore changing it.
truncating
When you are ____ in integer division, any fractional part of an integer division result is discarded.
The Import Statement
Why didn't we import the System or String classes explicitly in earlier programs? All classes of the java.lang package are imported automatically into all programs It's as if all programs contain the following line: import java.lang.*; The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported
Dog Example
Will see the syntax of creating objects (with unique instance variables) and then calling methods from the class later The computer will read this and decide which bark to use Just think of it like you name something (object) and give it variables and then it takes the information and outputs something (method)
Increment and Decrement
Write four different program statements that increment the value of an integer variable total. Count ++ Count = Count + 1 Count = ++ Count Count += 1
In the StringMutation program shown in Listing 3.1, if phrase is initialized to "Einstein" what will Mutation #3 yield if Mutation #1: mutation1 = phrase.concat(".")?
XINSTXIN.
Can an abstract class extend a concrete one?
Yes
Can an abstract class have a constructor?
Yes
Can array use all of the methods that object can?
Yes
Can you compare a byte with a float by using ==?
Yes
Can you compare an int with a double by ==?
Yes
Can you forget some parts of a for loop?
Yes
Can you have an array of objects?
Yes
Can you use short in a switch statement?
Yes
Can you use underscores in primitives not including char or boolean?
Yes
Does every object have their own copies of instance variables and non static method?
Yes
If an array list is of type integer and you try to set it as an array with the method .asList that has a type of int will it compile?
Yes
Is the String class final?
Yes
Is this valid code? boolean b = false; while(b){ System.out.println("Hey"); }
Yes
Can you assign an integer to a character?
Yes - Only if it is put as an integer like 5 not if it assigned a variable that stores an int.
Can an object have more than one type?
Yes - it can implement n-amount of interfaces as well as extend a class thereby taking on the type of many other classes
Can we overload main() method?
Yes, You can have many main() methods in a class by overloading the main method.
Can you have virtual functions in Java?
Yes, all functions in Java are virtual by default.
Can we intialize blank final variable?
Yes, only in constructor if it is non-static. If it is static blank final variable, it can be initialized only in the static block.
Is Empty .java file name a valid source file name?
Yes, save your java file by .java only, compile it by javac .java and run by java yourclassname
Can you make your own types of exceptions? If so,how? If not why?
You can create a custom exception classes by inheriting the Exception class
You can examine the value of an expression by using the debugger's ____ command.
Refactor - split loop
You have a loop doing two things - duplicate the loop. for(Tree tree : trees) // do x // do y Will be separated into two loops, one doing x and the other doing y.
Book-Title
You should use _____ capitalization for a JButton's name.
Which character below is not allowed in an identifier? 1) $ 2) _ 3) 0 (zero) 4) q 5) ^
^
Pseudocode
____ is an artificial and informal language that helps programmers develop algorithms.
output JTextField
a JTextField used to display calculation results. The editable property of an output JTextField is set to false with setEditable.
Which of the following is true regarding Java syntax and semantics? 1) a Java compiler can determine if you have followed proper syntax but not proper semantics 2) a Java compiler can determine if you have followed proper semantics but not proper syntax 3) a Java compiler can determine if you have followed both proper syntax and semantics 4) a Java compiler cannot determine if you have followed either proper syntax or semantics 5) a Java compiler can determine if you have followed proper syntax and can determine if you have followed proper semantics if you follow the Java naming convention rules
a Java compiler can determine if you have followed proper syntax but not proper semantics
Class
a class is a template in which state and behavior are defined for the instances of that class (objects)
Single Responsibility Principle
a class should do one thing and do it well - which is to say it should be cohesive
Inheritance
a class the inherits gets all the methods and variable of the parent class
Cohesion
a cohesive class is one whose defined responsibilities are meaningful - an OrderFactory class shouldn't be used to create an order as well as parse dates. - it should do one thing and do it well, delegating task outside of its responsibility to other classes
As presented in the Software Failure, the root cause of the Mars Climate Orbiter problem was
a communication issue between subsystems
Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long If you define a subclass of Person, like Student, and add a single constructor with this signature Student(String name, long id), that contains no code whatsoever, your program will only compile if the superclass (Person) contains: 1. an explicit constructor of whatever type 2. a setName() method to initialize the name field 3. an implicit constructor along with a working constructor 4. a default or no-arg constructor
a default or no-arg constructor
while loop vs do while
a do while runs through at least once while a while loop may never run
A URL (Universal Resource Locator) specifies the address of
a document or other type of file on the Internet
What is JavaDoc?
a documentation generator from Oracle that can create API documentation in HTML from java source code using annotations.
repetition statement
a loop; control a block of code to be executed for a fixed number of times or until a certain condition is met
static method
a method with no implicit parameter (a method that is not invoked on an object)
protocol
a mutually agreed upon set of rules, conventions, and agreements for the efficient and orderly exchange of information
A containment hierarchy is
a nested collection of relationships among containers
Run-time errors (Error Type 2/3)
a problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally
Logical or semantic errors (Error Type 3/3)
a program may run, but produce incorrect results, perhaps using an incorrect formula
class
a programmer-defined data type; the user can create this data type and make objects of this type
What value will z have if we execute the following assignment statement? int z = 50 / 10.00;
a run-time error arises because z is an int and 50 / 10.00 is not
interface (in Java)
a type with no instance variables, only abstract methods and constants
What is the difference between procedural and object-oriented programs?
a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOP program, it is accessible with in the object and which in turn assures the security of the code.
Polymorphism
ability of an object to take many forms
Abstract Classes & Interfaces
abstract class - class that is never intended to be instantiated as an object. Its purpose is to serve as a base class that provides a set of methods that together form an API. classes that inherit the abstract class can override its base behavior as necessary. Because the derived classes can be instantiated, they are referred to as concrete classes. This combination of an abstract base class and one or more concrete derived classes is widely used in industry and is known as the "Template" design pattern. class is identified as being abstract by pre-pending the keyword "abstract" to the class definition. package domain; public abstract class LibraryItem { } abstract keyword prohibits a LibraryItem from being instantiated with the "new" keyword. When a class is denoted as abstract, it typically means that one or more of its methods are also abstract, which implies they have no implementation. method is declared to be abstract by using the "abstract" keyword: public abstract boolean validate(); there's no {...} following the signature; rather, a semicolon is present. method must not have an implementation following its signature, the enclosing class must be declared to be abstract. implementation of validate() in one of the concrete derived classes: Book. package domain; public class Book extends LibrarayItem { public boolean validate() { if (id <= 0) return false; if (title == null || title.equals("")) return false; if (author == null || author.equals("")) return false; if (pages <= 0) return false; return true; } } another technique for declaring "abstract" interfaces by way of the "interface" keyword: package domain; public interface IValidator { public boolean validate(); } interface construct is used to capture zero or more method signatures without specifying their implementation details. methods enclosed within an interface definition must be "abstract" in the sense that they must not provide an implementation (i.e., {...}), but the abstract keyword is not necessary. interfaces are implemented in classes with the "implements" keyword. User and Login are not defined as abstract since implementations are provided for the validate() method. package domain; public abstract class LibraryItem implements IValidator { public abstract boolean validate(); } uniform interface for validating objects. package domain; public class User implements IValidator { public boolean validate() { } } package domain; public class Login implements IValidator { public boolean validate() { } } while Java does not support multiple class inheritance , it does support the implementation of multiple interfaces in a single class. To serialize Login objects across a secure network Login class needs to implement the Serializable interface. package domain; public class Login implements IValidator, Serializable {...} Serializable does not contain any methods, known as a Marker Interface. Marker interfaces, used to "mark" classes (and hence their objects) as "one of those," but without any additional methods. In summary, interface constructs are used to separate interface abstractions from implementation details.
ACK
acknowledgement message that contains the sequence number of a correctly received packet; this lets the sender know the packet was received
The expressions that are passed to a method in an invocation are called
actual parameters
GridLayout
all components are placed in a table like structure and are the same size.
What are the objects needed in order to create a Java GUI (graphical user interface)? 1) components 2) events 3) listeners 4) all of these 5) only classes from AWT and/or Swing are needed
all of these
Consider a method defined with the header: public void doublefoo(double x). Which of the following method calls is legal? 1) doublefoo(0); 2) doublefoo(0.555); 3) doublefoo(0.1 + 0.2); 4) doublefoo(0.1, 0.2); 5) all of these are legal except for doublefoo(0.1, 0.2);
all of these are legal except for doublefoo(0.1, 0.2);
Associations
allow classes (and their objects) to form relationships with one another. These relationships facilitate object collaboration. two types of associations: "Has a" relationships: Abstracts/models the concept of containment (e.g., a Customer has an Account; or in other words, the Customer contains an Account). "Uses a" relationships: Abstracts/models the concept of using (e.g., a Workflow manager uses various services to accomplish a task [to get some work done]). "has a" relationship with another class if it has a data member of that particular type. package domain; public class User { private Account account = new Account(); } abstracting a Login class that contains the user's credentials (username, password) and associating it with the User by declaring Login data member: package domain; public class User { private Login login = new Login(); private Account account = new Account(); } Once you declare a data member as an object type, you have essentially created a "has a" relationship between the two objects. "uses a" relationship, only difference between a "has a" and "uses a" relationship is where the declaration is made. "uses a" relationships are defined within method declarations (and not as data members of the enclosing class). So for instance, suppose a particular method needs to use a Date object to timestamp a message: package domain; public class Logger { public generateLogMessage(String message) { Date date = new Date(); } } The above method instantiates a Date object locally within the scope of the method, not as a data member (at the class/object level). "uses a" relationship. So we can summarize "has a" and "uses a" relationships as follows: "Has a" relationships are realized as object declarations located at the class level (i.e., as data members). "Uses a" relationships are realized as object declarations located within the scope of a method.
Java.text's NumberFormat class includes methods that
allow you to format currency, allow you to format percentages, round their display during the formatting process, but not truncate their display during the formatting process
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = 2 * j; if (j % 2 == 1) alpha[j - 1] = alpha[j] + j; } 1. alpha = {0, 2, 4, 6, 8} 2. alpha = {0, 2, 9, 6, 8} 3. alpha = {3, 2, 9, 6, 8} 4. alpha = {0, 3, 4, 7, 8}
alpha = {3, 2, 9, 6, 8}
What is stored in alpha after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) { alpha[j] = j + 5; if (j % 2 == 1) alpha[j - 1] = alpha[j] + 2; }
alpha = {8, 6, 10, 8, 9}
what is an abstract base class?
an abstract base class differs from a base class in that it cannot be instantiated - only used to enforce certain fields and methods
abstract
an abstract class can not be instantiated. It can act as a parent class where the child class implements the abstaract methods of the abstract class
computing agent
an abstract entity that can carry out the steps of the algorithm. They 1) accept input, 2) Store information and retrieve from memory, 3) Take actions according to algorithm instructions, 4) Produce an output.
Private Keyword
an access modifier that only allows access to that member from the class in which it resides
what is an array?
an array is a container object of fixed length that holds values of one type
logic gate
an electronic device that operates on a collection of binary inputs to produce a binary output.
What is an object?
an instance of a class
Iterator
an iterator is an object that visits each element in a collection once - order off iteration is not guaranteed (every type in the Collections Framework has an iterator)
Polymorphism
an object can take on multiple types, therefore having the capacity to be referred to in multiple ways
instance
an object of a particular class
What is a Collection?
an object that stores multiple elements in a single unit
software life cycle
analysis, design, coding, testing, operation
&&
and operator, control statement executed when all the statements are true
If two variables contain aliases of the same object then
answers the object may be modified using either alias and the object will become an "orphan" if both variables are set to null are correct
Java ________ can run from a Web browser.
applets
Method body
area within the brackets of a method
Assertion code
assert boolean_expression; assert boolean_expression : displayable_expression;
ARQ algorithm
automatic repeat request; basis for all data link control protocols in current use -> a message is sent from A to B, A holds on the the message until an ACK is sent back from B
Iterable Interface
base interface for all interfaces of the Java collection framework (excluding Map). Iterable defines exactly one method, namely: Iterator iterator(); This allows you to get an Iterator for iterating over the elements of a collection. Since all other collection interfaces extend Iterable (either directly or indirectly), they all inherit the above method; that is, they all provide an iterator for iterating over their elements. For example, the Collection interface directly extends Iterable, and hence, if you have a Collection, you can get an iterator to iterate over its elements: Collection<Book> coll = getOverdueBooks(); Iterator<Book> iter = coll.iterator(); while (iter.hasNext()) { Book book = iter.next(); } Because the need to iterate over all items in a collection is a common practice, the method iterator() is placed in the base interface Iterable, and then through inheritance, it's made available to all collections that extend Collection (because Collection extends Iterable). The extension of Iterable by Collection (and then List, Set, and Queue) is known as interface inheritance.
Java is an example of
both high-level language and fourth generation language
You specify the shape of an oval in a Java applet by defining the oval's
bounding box
A block is enclosed inside ________.
braces
What does pass by reference mean?
by reference means the called functions' parameter will be the same as the callers' passed argument (not the value, but the identity - the variable itself)
What are all the primitives?
byte,short,int,long,float,double,char,boolean.
A unique aspect of Java that allows code compiled on one machine to be executed on a machine of a different hardware platform is Java's
bytecodes
this.method()
calls an instance method in the current class.
What is casting a variable?
casting is to override the compiler by declaring your variable as a certain (Type) - this can only be used to make an object higher in a class hierarchy a more specific subclass (i.e. (Integer)Number or (ArrayList)Collection)
A single character
char
Of the following types, which one cannot store a numeric value? 1) int 2) byte 3) float 4) char 5) all of these can store numeric values
char
postcondition assertion
checks a condition that must be true after method execution
assertion
checks for a condition that must be true
precondition assertion
checks for a condition that must be true before a method is executed
Constructors have the same name as the ____. 1. data members 2. package 3. class 4. member methods
class
Write a class and write a tester for that class
class Dog { int size; String breed; String name; void bark() { System.out.println("ruff! Ruff!"); } } 2) write the tester (TestDrive) class class DogTestDrive { public static void main (String [] args) { Dog d=new Dog(); d.size=40; d.bark(); } }
Declaring a class to a package
class is declared to belong to a package by including a package statement at the beginning of the source file, it must be the first statement in the file: package mypackage; public class MyClass { ... } If package is not declared, the class will belong to the "default package". Not recommended for larger programs.
abstact base class
class that can not be initialized but has class inhert from it
Application defined classes
classes that you create for your specific application Login -username : String -password : String +setUsername : (username : String) +getUsername () : String +setPassword : (password : String) +getPassword () : String +validate() : boolean +equals(Login Login) : boolean two private data members: username and password; the minus sign means the properties are hidden in the class, cannot access them outside of class. When a class does not explicitly provide a constructor, Java implicitly provides a default constructor (one that takes no arguments). The default constructor is available for use even though it's not shown.
What is a constructor
constructors always have the same name as the class name. The constructor for the Date class is called Date.. to construct a Date object, you combine the constructor with the "new" operator as follows: new Date() -this expression constructs a new object.
Method
contains a collection of programming instructions that describe how to carry out a particular task; consists of a sequence of instructions that can access the internal data of an object
Memory Data Registrar (MDR)
contains the data value being fetched or stored
control flow invariant
control must flow must flow invariably to a case
nested conditional
control statement within another control statement
Postincrement
counter++
Which of the following would be a good variable name for the current value of a stock? 1) curstoval 2) theCurrentValueOfThisStockIs 3) currentStockVal 4) csv 5) current
currentStockVal
Data Hiding
data hiding is the concept of maintaining private fields within a class - if they are not meant to be modified, don't provide a setter - if they aren't meant to be accessed don't provide a getter
HashSet
data is stored in a table with an associated hash code. Has code is used as an index. Contain NO duplicates, elements kept in order.
A Java variable is the name of a
data value stored in memory that can change its value but cannot change its type during the program's execution
properties
data values(members) -variables -constants
method toString()
default behavior is to return the object's fully qualified name followed by the object's hash code. book1.toString(); //returns: Book@1ea2df3 book2.toString(); //returns: Book@1ea2df3 this information is typically not useful, it's common to override toString().
overload a method
defining methods with the exact same name put with different sets of arguments/parameters -method will have a different body
Abstract keyword
denotes a class that cannot be instantiated and provides no implemntation for its member methods and fields - used to define certain behaviors and properties of subclasses
object-oriented programming
designing a program by discovering objects, their properties, and their relationships
primitive data type
determines the values a variable can contain; int, byte, short, long, double, float, char, boolean
The line of Java code "// System.out.println("Hello");" will
do nothing
64 bit real number
double
If you attempt to add an int, a byte, a long, and a double, the result will be a ________ value.
double
Do loop
do{ code here } while ( argument here);
ArrayList
dynamic data structure items can be added or removed
Encapsulation
effective information hiding -programmers do not have to concern themselves with details of program components
Assume that you have an ArrayList variable named a containing 4 elements, and an object named element that is the correct type to be stored in the ArrayList. Which of these statements assigns the first object in the collection to the variable element?
element = a.get(0);
_______________—the specification of attributes and behavior as a single entity—allows us to build on our understanding of the natural world as we create software.
encapsulation
What does encapsulation mean?
encapsulation is a term that refers to the separation of the public interface and private implementation of an object - the objects inner implementation should be hidden from the user. hide data by using the private keyword on fields and methods that users do not need to know about
An example of passing message to a String where the message has a String parameter would occur in which of the following messages? 1) length 2) substring 3) equals 4) toUpperCase 5) none of these, it is not possible to pass a String as a parameter in a message to a String
equals
short circuit evaluation
evaluation in which the programmer puts the conditions more likely to cause the control statement to not execute first
delegation based event model
event handling implemented by two types of objects: event source and event listener objects
Exception Handling
events (e.g., errors) that disrupt the normal flow of execution. Examples of software exceptions: - Dividing by zero. - Using an unassigned object reference (that points to null) to invoke a method. - Failure to open/read/write/close a file. - Failure to open/read/write/close a socket connection. - Database errors. when a program executes, described as a call stack, ordered list of the active methods called up to the current point in time. stack starts with the main entry point and documents the active methods that are currently under call. once an exception occurs, it must be handled, or the program aborts. the JVM marches through the call stack looking for the nearest handler for the exception. If one is found, control is transferred. Otherwise, the program terminates.
exception catcher
exception thrower that includes a matching catch block for the thrown exception
Defining Exceptions
exceptions are classes that extend the class Exception either directly or indirectly. For example, just a few of the many exceptions defined by the Java API. public class ClassNotFoundException extends Exception {...} public class IOException extends Exception {...} public class NullPointerException extends Exception {...} public class NumberFormatException extends Exception {...} The Exception class, most of its behavior is inherited from a base class named Throwable, which defines a message (String) property and a corresponding accessor, getMessage(). defining a custom exception that denotes a failed login: public class LoginFailedException extends Exception { public LoginFailedException() { super(); } public LoginFailedException(String msg) { super(msg); } } when defining your own exceptions, provide at least two constructors, default constructor and a constructor that takes a message string as a parameter. In both cases, the base constructor of Exception is invoked using the keyword super.
exchange sort
exchange or transposition which systematically interchanges pairs of elements that are out of order until no more such pairs exist
Polymorphism
exhibiting different designs for the same behavior (ie method name) as a result of objects of different classes; not the same as overriding
cast
explicitly converting a value from one type to a different type
In order to create a constant, you would use which of the following Java reserved words?
final
What is the only modifier that a local variable can be?
final
To declare a constant MAX_LENGTH inside a method with value 99.98, you write
final double MAX_LENGTH = 99.98;
flops
floating-point operations per second, this is used to see how many arithmetic operations a computer can do in a second (testing speed)
The main difference between a frame and a panel is
frames can have a title bar; panels cannot
Hamcrest
framework to help write JUnit test cases. assertThat("HelloClass", is(equalTo(Greeter.greeting())))
Collection Interface
general abstraction for a collection of objects. It provides a handful of methods that operate over all interfaces that extend Collection. <<interface>> Collection +add(E) : boolean +addAll(Collection) : boolean +clear() : void +contains(Object) : boolean +containAll(Collection) : boolean +isEmpty() : boolean +remove(Object) : boolean +size() : int Java API does not provide any direct class implementations of interface Collection. Instead, implementations are provided for interfaces that extend Collection, namely, List, Set, and Queue. Nevertheless, the Collection interface is often used to pass collections around since it represents the base behavior of all collections. We'll now take a look at List, Set, and Queue and see how they might be used in our Library application.
Accessor instance method names typically begin with the word "____" or the word "____" depending on the return type of the method. 1. set, is 2. get, can 3. set, get 0% 4. get, is
get, is
Programming style is important, because ________. (Choose all that apply.) 1) a program may not compile if it has a bad style 2) good programming style can make a program run faster 3) good programming style makes a program more readable 4) good programming style helps reduce programming errors
good programming style makes a program more readable good programming style helps reduce programming errors
binary tree
graph with edges, connected nodes such that there is a root node and no node has more than two children nodes
GUI
graphical user interface
When you define a subclass, like Student, and don't supply a constructor, then its superclass must: 1. have no constructors defined 2. have no constructors defined or have an explicit default (no-arg) constructor defined. 3. have an explicit copy constructor defined 4. have an explicit default (no-arg) constructor defined 5. have an explicit working constructor defined
have no constructors defined or have an explicit default (no-arg) constructor defined.
instruction register
holds a copy of the instruction fetched from the memory. It holds both the op code and the addresses
A class' constructor usually defines
how an object is initialized
What is the standard convention for un-named variables?
i
Which of the following is a legal Java identifier? 1) i 2) class 3) ilikeclass! 4) idon'tlikeclass 5) i-like-class
i
Abstraction
identification of properties and behavior of objects relevant to solving the problem at hand
Write an if then else statement where i=10
if (i=10) { //do something } else { //do something else }
selection statement
if-else statements; chooses which step to do based on the parameters in the statements
coding
implement the design into a program; result is a program
How is the import keyword used?
import keyword is used to import from other files in order to use outside classes.
quick sort
in-place, divide-and-conquer, massively recursive sort; array is split in two parts based on a pivot point (one with elements larger than the pivot, one with elements smaller than the pivot) and is recursively repeated
pseudocode
informal programming language with English-like constructs modeled to look like statements in a java-like language
object
instance of exactly one class, and belongs to that class
stored program concept
instructions to be executed by the computer are represented as binary values and stored in memory
You can create an array of three integers by writing :
int ar[] = new int[3];
Write an endless do loop where i=10
int i = 10; do{ i = i + 5; System.out.print(i); } while (i > 5);
Write an endless while loop where i=10
int i = 10; while(i > 5){ i = i + 5; System.out.print(i); }
To declare an int variable number with initial value 2, you write
int number = 2;
Which of the following assignment statements is illegal? (Choose all that apply.) 1) float f = -34; 2) int t = 23; 3) short s = 10; 4) int t = (int)false; 5) int t = 4.5;
int t = (int)false; int t = 4.5;
IDE
integrated development environment; a programming environment that includes an editor, compiler, and debugger
What is a constructor?
is a bit of code that allows you to create objects from a class. You call the constructor by using the keyword new , followed by the name of the class, followed by any necessary parameters. For example, if you have a Dog class, you can create new objects of this type by saying new Dog()
What is JavaDoc?
is a documentation generator from Oracle Corporation for generating API documentation in HTML format from Java source code. The HTML format is used to add the convenience of being able to hyperlink related documents together.
local variable
is a variable that is declared in the body of a method
The ____________ relationship occurs when members of one class form a subset of another class, like the Animal, Mammal, Rodent example we discussed in the online lessons. 1. encapsulation 2. composition 3. is-A 4. has-A
is-A
What is super()?
it calls the superclass constructor.
If a method does not have a return statement, then
it must be a void method
what is the objects state
its how the object reacts when you invoke those methods
Which library package would you import to use the class Random?
java.util
How do you run a program using commands.
javac ClassName.java java ClassName
The JDK command to compile a class in the file Test.java is
javac Test.java
reconstruction step
last child is moved to root node, check and update the heap to satisfy the value-relationship constraint starting at the root
LAN
local area network; network that is located in a geographically contiguous area such as a room; It is composed of personal computers and servers all connected with coaxial or fiber optic cables. Characteristics: bus, star, ring topology. Message broadcast on shared channel and all nodes receive.
Which of these data types requires the most amount of memory? 1) long 2) int 3) short 4) byte
long
Instance data for a Java class
may be primitive types or objects
exception handling
mechanism used to improve a program's robustness
object reference
memory location of an object
exception thrower
method that may directly or indirectly throw an exception
constructor
method with no return type; same name as class; default data members and values for instances of the class
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } What is the name of the method above?
minimum
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is a valid call to the method above?
minimum(5, 4);
public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } Which of the following is a valid call to the method above? 1. minimum(int x, int y); 2. minimum(int 5, int 4); 3. minimum(5, 4); 4. public static int minimum(5, 4);
minimum(5, 4);
It is important to dissect a problem into manageable pieces before trying to solve the problem because
most problems are too complex to be solved as a single, large activity
Why is it a good idea to split your application into layers?
n tier design allows for further separation of concerns among parts/layers of our appplication - this provides the ability to reuse parts of the application in other programs by having loosely coupled classes/layers
Internet Protocol
network layer in the Internet; the IP uses 32-bit addresses to identify different nodes.
Which of the following reserved words in Java is used to create an instance of a class? 1) class 2) public 3) public or private, either could be used 4) import 5) new
new
Keyword: new
new - creates Class objects and a constructor as shown below: Book book1 = new Book(); Book book2 = new Book("SomeTitle", "SomeAuthor", false); Constructors are invoked with the "new" keyword as shown below: Book book1 = new Book(); Book book2 = new Book(1); Book book3 = new Book(1, "Gone with the Wind", "Margaret Mitchell"); Using a constructor that allows you to initialize the object with passed-in parameters. Using the default constructor, followed by the invocation of set(...) methods.
New
new is a Java reserved word that triggers all kinds of actions. goes back to the heap (free memory space), reserves a chunk of the memory for the real value (address) Java actually invokes a special method called constructor, provided by programmer, which does the proper initialization new is the only thing that produces a reference type
Thread Life Cycle
new process > WAITING > RUNNING > BLOCKED - waiting starts and runs or times out - runs unless blocked until unblocked or until complete
iterator
object that enables steping through a container
Method overloading
occurs when a class contains more than one method with the same name. Within a class, methods can have the same name if there's difference: The number of parameters. And/or the type parameters. And/or order of parameters. The determination of which overloaded method to invoke is a compile-time decision; hence, it is sometimes referred to as static binding. Library library = new Library(); Book book = new Book(); library.add(book); User user = new User(); library.add(user); Notice that the statement library.add (book) is clearly targeting the add (Book) method because of the parameter data type, Book. Similarly, the statement library.add(user) is clearly targeting the add(User) method because of the parameter data type, User. Since these decisions can be determined at compile time, the binding is said to be static.
event
occurs when the user interacts with a GUI object
boolean operator
operator that can be applied to boolean values: &&, ||, !
Service Threads
or daemon threads - Contain never ending loop - Receive and handle service requests - Terminates only when program terminates. So detects when all non-daemons finished then kills daemons and programs terminate.
Inheritance
organization of relevant classes into an hierarchy of parent and child classes; inherit some common base of data members and method from the parent class; maintainability, readability, extendability
What does overriding mean?
overriding is to create a unique implementation of a method inherited from a supertype or interface
procedure
performs an action but doesn't return anything;
variable
points to a object in the heap
protected
protected members can only be accessed by own class, class's sub class or classes from same package
the reserved words
public static void class
What must the access modifier of a method that is implementing an interface be?
public - since all interface methods are automatically public methods that override it have to have the same or higher visibility rank.
Constructor syntax
public class Book { // properties private String title = null; private String author = null; private boolean isCheckedout = false; // constructors public Book() { } public Book(String title, String author, boolean isCheckedout) { this.title = title; this.author = author; this.isCheckedout = isCheckedout; } } Two constructors: Book(), which is known as the default constructor Book(String title, String author, boolean isCheckedout) Default constructor - typically used to initialize properties to their "null" values, unless it is done when they are declared, then there is no need to have the first constructor. The 2nd constructor above, takes the passed parameters and assigns them to the class's properties (i.e., data members) using the keyword "this".
Basic definition of class for Book (library program)
public class Book { // properties private String title = null; private String author = null; private boolean isCheckedOut = false; // behavior public void checkOut () { isCheckedOut = true; } public void checkIn () { isCheckedOut = false; } }
Example of Event Listener and Event Handler
public class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println(e); } } // Listens for button action, if action occurs then will print the action.
Syntax to define a class
public class SomeClassName { // class properties and behaviors (methods) go here } keyword "public" is an access modifier, keyword "class" identifies the construct (i.e., the item) as a class definition, class name may contain alpha numeric characters, underscore, and $ (last two are rarely used). By convention, class names always start with an upper case letter, using CamelCase if there are more than one word.
Class lock (synchronization)
public static synchronized void displayMessage(JumbledMessage jm) throws InterruptedException { for (int i = 0; i < jm.message.length(); i++) { System.out.print(jm.message.charAt(i)); Thread.currentThread().sleep(50); } System.out.println();}
Visibility modifiers include
public, private, protected
List all the access modifiers in order from most visible to least?
public, protected, default, private.
If a method has a public access modifier and a subclass overrides that method, what must its access modifier be?
public. If it where default it could be either public or protected.
What is a try/catch?
put in spots where uncheck exception may accure to catch the excception if it dose occur
overriding a method
redefining a method in a subclass
string
reference data type; array of characters; immutable; pass-by-value
interface
reference data type; includes only constants and abstract methods
Object
refers to a particular class
Inheritance gives your programs the ability to express _______________ between classes. 1. encapsulation 2. relationships 3. composition 4. dependencies
relationships
extraction phase
remove the root node to the output list then reconstruction step is executed
Set Interface
represents a collection of objects with no duplicates. By default, duplicates are identified by their equals(Object) method whose default behavior is defined in the root class Object. In other words, if equals(Object) is not overridden, object references will be used to determine if list entries are equal. If this behavior is not desired, equals(Object) needs to be overridden in the class for which objects are added to the set. A portion of the Set API is shown below. <<interface>> set +add(E) : boolean +addAll(Collection) : boolean +clear() : void +contains(Object) : boolean +containAll(Collection) : boolean +isEmpty() : boolean +remove(Object) : boolean +size() : int suppose the Library system has a business rule that prevents users from checking out more than one copy of a given book. During the checkout process, the user's books could be added to a Set collection where duplicate books are not added to the set. private Set booksCheckedOut = new HashSet(); public boolean checkout(Book book) { return booksCheckedOut.add(book); } The above method returns true if the book is not already in the set; otherwise, it returns false. If false is returned, the user would be notified that the duplicate book could not be checked out. Implementations of the Set interface include HashSet and TreeSet. The order of elements in a Set depends on the underlying implementation, and thus, will vary across implementations. If order is important, the interface SortedList should be used.
Queue Interface
represents an ordered collection based on some known order: e.g., first in first out (FIFO), last in first out (LIFO, a.k.a. a stack), priority. A subset of the Queue API is shown below (not including the methods inherited from interface Collection). <<interface>> Queue +element() : E +offer(E) : boolean +peek() : E +poll() : E +remove() : E order of the queue is determined by the implementing class. Classes that implement the Queue interface include LinkedList and PriorityQueue. As an example, suppose the Library system solicits user suggestions, and these suggestions need to be processed in a FIFO basis. private Queue suggestions = new LinkedList(); public void addSuggestion(Suggestion suggestion) { suggestions.add(suggestion); } The above method adds the new Suggestion to the Queue. Because the implementing class is a LinkedList, each suggestion is added to the end of the queue.
List Interface
represents an ordered sequence of objects. That is, elements are added to the list in a particular order, and the list maintains that order. suppose we have a List, booksCheckedIn, which contains all the books that are checked-in on a given day. Then, if we add books to the list as they are checked-in, the list will maintain the order in which they were checked-in. private List booksCheckedIn = new ArrayList(); public void checkin(Book book) { booksCheckedIn.add(book); } Implementations of the List interface include ArrayList, LinkedList, Stack, and Vector. List collections do not check for duplicate entries, so if an object is added multiple times, it will appear in the list multiple times (i.e., have multiple entries). Therefore, if it's important for a given object to appear only once in the collection, the Set interface should be used as explained below.
Declaring Exceptions
required that if a method throws an exception without catching it, the exception must be declared in the method signature to notify users. method that authenticates logins, throws an exception named LoginFailedException without catching it: public bool authenticate(Login login) throws LoginFailedException {...} Any exception that occurs in a method must either be handled (caught) by that method or be declared in its signature as "throws" (see above). method throws (and does not handle) multiple exception types, instead of listing all the exceptions in the method signature, the base exception class Exception can be listed: public bool authenticate(Login login) throws Exception {...} declaration covers all possible exception types, and thus prevents you from having to list the individual exceptions when multiple exceptions can be thrown.
design
requirements specification turned into a detailed design of the program; result is a set of classes that fulfill the requirements
Bounded generic types
restrict the actual type parameter allowed and can be specified by saying which class the allowed types extend. - effect = permits subtypes of the class. can have: - object of subtype B where object of its supertype A is expected.
Syntax to define a method (behavior (function in C++))
returntype methodName(optional_list_of_arguments) { ...} Names of properties (variables) and methods should start with a lower case letter, using camelCase if multiple words.
construction phase
satisfy the structural constraint (numbers places in heap); satisfy the value relationship constraint (start w/ last parent node)
What is scope?
scope is the concept of the access granted to a variable depending on where it is seen. class level variables can be 'seen' or accessed anywhere within their given class whereas variables declared in the body of a method cannot be accessed from other methods in the same class.
notify() (Thread Communication)
sends wake up call to a single blocked thread. Cannot specify which thread to wake.
notifyAll() (Thread Communication)
sends wake up call to all blocked threads - if called when thread does not have lock = Illegal MonitorStateExpectation
method
sequence of instructions that a class or an object follows to perform a task
loop
sequence of instructions that is executed repeatedly
SASD
sequential access storage device does not require that all units of data be identifiable via unique addresses; to find the data, we must search sequentially, asking "Is this what I'm looking for?"
linear search
sequential search; n/2 comparisons; array is searched from the first position to the last position
initialize
set a variable to a well-defined value when it is created (primitive data types)
Method Parameters
set in a method declaration - specify the number and type of arguments to be passed into the method
Package
set of classes with a shared scope, typically providing a single coherent 'service' e.g. FilmFinder package
Clock -hr: int -min: int -sec: int +Clock() +Clock(int, int, int) +setTime(int, int, int): void +getHours(): int +getMinutes(): int +getSeconds(): int +printTime(): void +incrementSeconds(): int +incrementMinutes(): int +incrementHours(): boolean +equals(Clock): boolean +makeCopy(Clock): void +getCopy(): Clock According to the UML class diagram above, which method is public and doesn't return anything? 1. getCopy() 2. setTime(int, int, int) 3. incrementHours() 4. equals(Clock)
setTime(int, int, int)
variable assignment
sets where the varaible is pointing
I/O buffer
small amount of memory that the I/O controller has
selection sort
smallest (or largest) value is found and transferred to the output area
computability
something that can be done by symbol manipulation algorithms,; Turing machines define the limits of these
insertion sort
sort in which we assumed preceding records have been sorted, and the number is simply inserted into its proper place
Class Constructors
special methods that are called when a class is created. Must have the same name as the enclosing class, and are declared with no return value (the implied return type of the constructor is the enclosing class type). public Book() {...} public Book(int id) {...} public Book(int id, String title) {...} public Book(int id, String title, String author) {...} public Book(int id, String title, String author, int pages) {...} Constructors can be overloaded. Once you define at least one constructor (whether default or not), the implicit, hidden default constructor is not provided for you. used to initialize the data members of the newly created object either by assigning default values or by using the passed-in parameters. Constructors can also invoke other constructors either in the same class or in a base class. public Book(int id) { super(id); } Above uses "super" keyword to invoke a constructor in the base class LibraryItem. Constructors are invoked with the "new" keyword
I/O controller
special-purpose computer whose responsibility is to handle the details of input/output and to compensate for any speed differences between I/O devices and other parts of the computer
In the type-safe version of the ArrayList class, you specify the type of each element by: 1. None of these; an ArrayList can hold any object type 2. specifying a generic type parameter when defining the ArrayList variable 3. using the special type-safe version of the subscript operator 4. passing a Class parameter as the first argument to the constructor 5. using the setType() method once the ArrayList is constructed
specifying a generic type parameter when defining the ArrayList variable
merge sort
splits the list into two equal halves and places them in separate arrays, each array is recursively sorted then merged back together to form the final sorted list
What does API stand for?
stands for Application Programming Interface and it's simply a way to get information and pass information to trusted partners.
In addition to their usage providing a mechanism to convert (to box) primitive data into objects, what else do the wrapper classes provide?
static constants
What is static variable?
static variable is used to refer the common property of all objects (that is not unique for each object) . static variable gets memory only once in class area at the time of class loading.
register
storage cell that holds the operands of an arithmetic operation and when the operation is complete holds its result
A cast is required in which of the following situations? 1) using charAt to take an element of a String and store it in a char 2) storing an int in a float 3) storing a float in a double 4) storing a float in an int 5) all of these require casts
storing a float in an int
To add number to sum, you write (Note: Java is case-sensitive) (Choose all that apply.) 1) number += sum; 2) number = sum + number; 3) sum = Number + sum; 4) sum += number; 5) sum = sum + number;
sum += number; sum = sum + number;
Maps
supports the ability to add and retrieve items from a collection using a key value pair. The key (K) is the lookup identifier and the value (V) is the item being looked up. The methods for inserting/retrieving items in/out of the Map are put(...) and get(...). General accounts - For general public use. Business accounts - For commercial organizations. Nonprofit accounts - For nonprofit organizations. The above account types can be abstracted as a Java enum (enumerator): enum AccountType {general, business, nonprofit}; Each user is allowed to have one account of each type. Accounts for a given user could be contained in a Map data structure where the key for each account is one of the above enum values (general, business, or nonprofit) as shown below: Account generalAccount = new Account(); Account businessAccount = new Account(); Account nonprofitAccount = new Account(); //... Map<AccountType, Account> accountsMap = new HashMap<AccountType, Account>(); accountMap.put(AccountType.general, generalAccount); accountMap.put(AccountType.business , businessAccount); accountMap.put(AccountType.nonprofit , nonprofitAccount); Retrieval of the accounts from the map is then achieved with the key: Account generalAccount = accountMap.get(AccountType.general); Account businessAccount = accountMap.get(AccountType.business); Account nonprofitAccount = accountMap.get(AccountType.nonprofit); In summary, the key is used to place values in the map and also to retrieve values from the same map. advantage, code readily accommodates additional account types. simply add to the enum type: enum AccountType {general, business, nonprofit, government, education};
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is visible in block three? x (one's formal parameter) t (before main) z (before main) local variables of main
t (before main)
truth table
table used in logic to compute the functional values of logical expressions; this table has input columns that list all combination of true/false values and the corresponding outputs for those
class
template for instantiating objects; dictates what an object can or cannot do; defines the properties and behaviors for an object
Mocks
test objects that know how they are meant to be used.
Stubs
test objects whose methods return fixed values and support specific test cases only.
Fakes
test objects with working methods but have limited functionality.
Dummies
tests objects that are never used but exist only to satisfy syntactic requirements.
protocol stack
the Internet protocol hierarchy that has 5 layers (physical, data link, network, transport, application); also referred to as TCP/IP
Method Body
the code held bw the curly braces following the method
Compile-time or syntax errors (Error Type 1/3)
the compiler will find syntax errors and other basic problems
portability
the computer program is independent of the details of each particular computer's machine language because each compiler takes care of the translation
Inheritance
the concepts that one class can take on the fields, methods and nested classes of another object by using the extends keyword
What is the default constructor?
the constructor the exist if none is created. the defualt constructor is empty
The System.currentTimeMillis() returns ________.
the current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time)
formal parameter
the data type and variable name of a reference or value that is defined in a method definition
What does it mean if one class is derived from another?
the derived class extends from its ancestor class - inherits state and behavior
what is a subclass?
the descendant of a superclass
What does it mean to be loosely coupled?
the implementation of one class is not dependent on that of another - well defined classes with only one responsibility are easier to test and are not dependent on the implementations of other classes - by programming to the behavior of interfaces, the implementation behind the interface is irrelevant as any class that implements that interface can interact with those that are programmed to the behavior of the interface
software
the intangible instructions and data that are necessary for operating a computer or another device
To use an ArrayList in your program, you must import: 1. the java.collections package 2. the java.awt package 3. Nothing; the class is automatically available, just like regular arrays. 4. the java.util package 5. the java.lang package
the java.util package
Method Signature
the method name and parameter list (cannot overload a method by changing the return type if all other properties of the method are equals)
implicit parameter
the object on which a method is invoked
operating system
the program that controls the overall operation of the computer; it communicates with the users and carries out their requests
Protected Keyword
the protected keyword limits the access of a class member to only those classes which reside within the same package
computer science
the study of algorithms including their formal and mathematical properties, hardware realizations, linguistic realizations, and applications
Dynamic binding
the subclass' behaviour will occur even though the client does not know it is using the subclass object.
What is composition? How is it used?
the way in which you model objects that contain other objects . To use composition in Java, you use instance variables of one object to hold references to other objects
Keyword: this
this - used to disambiguate the overloaded use of variable names; in particular, "this" can be used to reference a data member (defined in the class) when that name is identical to a passed parameter. assigns the input parameter, title, to the data member, title: private String title = ""; public void setTitle(String title) { this.title = title; } inside the method setTitle(String title), the passed parameter, title, hides the data member, title, defined in the class. To access to the title data member, the keyword "this" is used to indicate a data member of the object is being referenced (and not a local variable inside the method).
Variable Assignment
to assign a value (using the assignment operator - " = ") to a variable name
Describe how to work with objects and variables
to work with objects, you first construct them and specify their initial state. Then you apply the methods to objects
Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long 1. toString() 2. None of them 3. getName(), setName(), name 4. name, getName(), setName(), getID() 5. getName(), setName(), studentID, getID() 6. studentID, name, getName(), setName(), getID()
toString()
Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Assume that pete is a Person object variable that refers to a Person object. Which method is used to print this output: pete is Person@addbf1 1. getClass() 2. getAddress() 3. getName(), getID() 4. getID() 5. getName() 6. None of them 7. toString()
toString()
Examine the following UML diagram: Person -name: String +setName(String name): void +getName(): String ^ I Student -studentID: long +Student(String sname, long sid) +getID(): long Which of these fields or methods are inherited by the Person class? 1. toString() 2. getName(), setName(), studentID, getID() 3. studentID, name, getName(), setName(), getID() 4. name, getName(), setName(), getID() 5. getName(), setName(), name 6. None of them
toString()
What does it mean to cast a variable?
treat an object as if it has a different class.
Every letter in a Java keyword is in lowercase.
true
address
unique identifier for a cell, this is how memory is divided
testing
unit testing or integration testing; debugging
Long
unsigned long
final keyword
used to denote a variable whose value is contant - can also be used in method declaration to assert that the method cannot be overridden by subclasses
Define the keyword "implements"
used to implement an interface.
class data value
used to represent information shared by all instances or to represent collective information about instances
Method parameter
variable input to method
static
variable or function is shared between all instances
protected
variables/methods available to any class that extends the original
For overriding a method in an interface that throws an exception of type IOException what must that method declaration be? Lets say that method was void m1() throws IOException
void m1() void m1() throws IOException void m1() throws FileNotFoundException
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is visible on the line marked // main block? 1. All identifiers are visible in main. 2. local variables of method two 3. w (before method two) 4. z (before main)
w (before method two)
Method Overriding
when a method in a base class is repeated (redefined) in a derived class signature of both methods must match identically override its behavior in the LibraryItem to output the item's id and title as shown below: public class LibraryItem { ... public String toString() { return "LibraryItem, id=" + id + ", title: " + title; } } can invoke toString() to get a meaningful description of the object. Also true if the object is a Book, Audio, or Periodical because they inherit LibraryItem. Object obj = new Book(1, "Catch-22", "Joseph Heller", 485); String s = obj.toString(); actual instance is a Book and Book "is a" LibraryItem which overrides toString(), the LibraryItem's toString() method is called. Example of polymorphic dynamic binding; dynamic because it's not known until runtime which toString() method is invoked; it depends on whether the method is overridden, and if so, where. Can override toString in each of the more specialized classes: Book, Audio, and Periodical: public class Book extends LibraryItem { public String toString() { return super.toString() + ", Author, =" + author; } } super.toString() in the above return statement; its purpose is to invoke the toString() method in the base class LibraryItem. So the Book's overridden toString() method calls the LibraryItem's toString() method and then appends to it the author information that's contained in the Book. This time, since Book has overridden toString(), which overrides LibraryItem.toString(), which overrides Object.toString(), it's Book.toString() that gets called, and not the ones declared in Object or LibraryItem: Object obj = new Book(1, "Catch-22", "Joseph Heller"); String s = obj.toString(); another example of method overriding, consider the method equals(Object obj) defined by the Object class. to compare the state of two objects, overriding equals(Object obj) as shown below for LibraryItem: public class LibraryItem { public boolean equals(Object obj) { if (this == obj) return true; if ( ! (obj instanceof LibraryItem)) return false; LibraryItem item = (LibraryItem)obj; if ( this.id != item.id ) return false; if ( ! this.title.equals(item.title)) return false; return true; } } @override annotation - applied to methods that are intended to override behavior defined in a base class. annotation forces the compiler to check that the annotated method truly overrides a base class method. package domain; public class LibraryItem { @Override public String equals(Object obj) { ... } @Override public String toString() { ... } }
Importing packages
when classes are in defined in different packages. In order for ClassA, in packageA, to have visibility to ClassB, in packageB, one of three things must happen; either: - the fully qualified name of ClassB must be used, - fully qualified name of ClassB be must be imported with an import statement, - entire contents of packageB must be imported with an import statement. first technique is to use the FQN of the class. The FQN of ClassB is packageb.ClassB. to declare: package packagea; public class ClassA { packageb.ClassB b = new packageb.ClassB(); } better technique is to use an "import" statement: package packagea; import packageb.ClassB; public class A { ClassB b = new ClassB(); } import statements must appear after the package statement, and before the data type (class, interface) definition more efficient technique is to import all the data types from a given package using the * notation: import packageb.*; if multiple packages have classes with the same name, use long way (FQN) of importing package: package1.ClassXYZ xyz = new package1.ClassXYZ()
WAN
wide area network that connects devices that are not in close proximity but rather are across town, across the country, or across the ocean. Characteristics: Store-and-forward, packet-switched technology. Message transmitted by packets. Failure of a single node doesn't bring down the entire network.
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is NOT visible in method two?
x (variable in block three)
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int z = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is NOT visible in method two? 1. x (variable in main block) 2. w (before method two) 3. rate (before main) 4. one (method name)
x (variable in main block)
To add a value 1 to variable x, you write (Choose all that apply.) 1) 1 + x = x; 2) x += 1; 3) x := 1; 4) x = x + 1; 5) x = 1 + x;
x += 1; x = x + 1; x = 1 + x;
To assign a double variable d to a float variable x, you write
x = (float)d;
To assign a value 1 to variable x, you write
x = 1;
If x is an int and y is a float, all of the following are legal except which assignment statement? 1) y = x; 2) x = y; 3) y = (float) x; 4) x = (int) y; 5) all of these are legal
x = y;
What is x after the following statements? int x = 1; int y = 2; x *= y + 1;
x is 3
What is an abstract class?
- An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.
Boolean
true or false
At
10. When application execution suspends at a breakpoint, the next statement to be executed is the statement ____ the breakpoint.
Empty String
3. The ____ is represented by "" in Java.
Size, style, and name
3. The font property controls the ____ of the font displayed by the Jlabel.
asterisk (*)
An arithmetic operator that performs multiplication.
What is a lambda?
using anonymous classes Lambda expressions let you express instances of single-method classes more compactly
argument
value passed into an object
double[][] vals = {{1.1, 1.3, 1.5}, {3.1, 3.3, 3.5}, {5.1, 5.3, 5.5}, {7.1, 7.3, 7.5}} What is in vals[2][1]? 1. 3.3 2. 3.5 3. 1.3 4. 5.3
4. 5.3
used to surround perimeters
()
What is the length of TEXT?
4
setIcon
4. Use ____ to specify the image to display on a JLabel.
pixel
A point on your computer screen. ____ is short for "picture element".
When an object, such as a String, is passed as an argument, it is
Actually a reference to the object that is passed
Predefined Java classes
Example of 2: Object class & String class
If Integer xx = 10 and Integer yy = 10, is this true or false? xx==yy?
False
The text that appears alongside a JCheckBox is referred to as the ____.
JCheckBox Text
instance
an object; created from a class
boolean expression
an expression that evaluates to either true or false
What are the two categories of nested classes?
static and none static
What is a mutator?
ways to set variables in class
public class ScopeRules //Line 1 { static final double rate = 10.50; static int z; static double t; public static void main(String[]args) //Line 7 { int num; double x, z; char ch; // main block... } public static void one(int f, char g) //Line 15 { // block one... } public static int w; //Line 20 public static void two(int one, int i) //Line 22 { char ch; int a; //Line 25 //block three { int x = 12; //Line 29 //... }//end block three // block two... //Line 32 } } Which of the following identifiers is NOT visible in block three? 1. t (before main) 2. z (before main) 3. local variables of method two 4. main
z (before main)
What does a contain after the following loop runs? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, value = 5; int pos = 0; for (pos = 0; pos < size; pos++) if (a[pos] > value) break; for (int j = size; j > pos; j--) a[j] = a[j - 1]; a[pos] = value; size++; 1. { 1, 3, 5, 7, 0, 0 } 2. { 1, 3, 5, 0, 0, 0 } 3. { 1, 3, 7, 5, 0, 0 } 4. { 5, 1, 3, 7, 0, 0 }
{ 1, 3, 5, 7, 0, 0 }
What does a contain after the following loop? int[] a = {1, 3, 7, 0, 0, 0}; int size = 3, capacity = 6, pos = 0; for (int i = pos; i < size - 1; i++) a[i] = a[i + 1]; size--;
{3, 7, 7, 0, 0, 0}
Defines a block of code
{}
How do servlets handle multiple simultaneous requests?
- The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost() and service()) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.
How many ways can we track client and what are they?
- The servlet API provides two ways to track client state and they are: a) Using Session tracking and b) Using Cookies.
What is the class and interface in java to create thread and which is the most advantageous method?
- Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because thread class implements Runnable.
What are the states associated in the thread?
- Thread contains ready, running, waiting and dead states.
What is the difference between abstract class and interface?
- a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods.Interface methods are by default public and abstract.Interfaces can have constants, which are always implicitly public,static, and final.Interfaces can extend one or more other interfaces
What is difference between overloading and overriding?
- a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.
What are drivers available?
- a) JDBC-ODBC Bridge driver b) Native API Partly-Java driver c) JDBC-Net Pure Java driver d) Native-Protocol Pure Java driver
What are the different servers available for developing and deploying Servlets?
- a) Java Web Server b) JRun g) Apache Server h) Netscape Information Server i) Web Logic
What is a reflection package?
- java. lang. reflect package has the ability to analyze itself in runtime.
What is the difference between constructor and method?
Constructor will be automatically invoked when an object is created whereas method has to be called explicitly. Constructor doesn't have return types and its name must be the same as the Class' When constructor is invoked, it may invoke the constructors of the super classes.(call stack)
What is the difference between process and thread?
- Process is a program in execution whereas thread is a separate path of execution in a program.
How do you pass data (including JavaBeans) to a JSP from a servlet?
- (1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either "include" or forward") can be called. This bean will disappear after processing this request has been completed. Servlet: request. setAttribute("theBean", myBean); RequestDispatcher rd = getServletContext(). getRequestDispatcher("thepage. jsp"); rd. forward(request, response); JSP PAGE:<jsp: useBean id="theBean" scope="request" class=". . . . . " />(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it. Servlet: HttpSession session = request. getSession(true); session. putValue("theBean", myBean); /* You can do a request dispatcher here, or just let the bean be visible on the next request */ JSP Page:<jsp:useBean id="theBean" scope="session" class=". . . " /> 3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it. Servlet: GetServletContext(). setAttribute("theBean", myBean); JSP PAGE:<jsp:useBean id="theBean" scope="application" class=". . . " />
What are JSP Directives?
- A JSP directive affects the overall structure of the servlet class. It usually has the following form:<%@ directive attribute="value" %> However, you can also combine multiple attribute settings for a single directive, as follows:<%@ directive attribute1="value1? attribute 2="value2? . . . attributeN ="valueN" %> There are two main types of directive: page, which lets to do things like import classes, customize the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the time the JSP file is translated into a servlet
Who is loading the init() method of servlet?
- Web server
What is the difference between Reader/Writer and InputStream/Output Stream?
- The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented.
What is a stream and what are the types of Streams and classes of the Streams?
- A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are: Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.
What is a package?
- A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.
What is the difference between superclass and subclass?
- A super class is a class that is inherited whereas sub class is a class that does the inheriting.