JAVA FINAL 10
Operator
A special symbol (+, *, ++, --) that is used to indicate an operation to be performed on one or more values. Study the order of operations in Java!!!
Constructor?
A special type of method that is called when an object is created to initialize variables.
switch...case form
'switch ([argument]) { case [selector]: [statements;] break; default: [statements;] break; }'. Where many cases can be written and the 'default' case is selected if none of the other cases are selected.
s is a string. Expression whose value is true if & only if the value comes bw "mortgage" & "mortuary" in the dictionary.
(s.compareTo("mortgage") > 0 && s.compareTo("mortuary") < 0 )
*REFERENCE TYPE and* *OBJECT TYPE*
*REFERENCE TYPE and OBJECT TYPE*
Life Cycle - Suspended
-A thread is waiting for an outside event to occur...-Common events: other threads complete execution, or if a thread receives a resume from another thread
Hacking
-Act of exhibiting rare problem-solving abilities - Today: term is negative and describes a thief stealing information via internet
comment format
// Single-line comment, /**/
byte
1 byte, stores an integer
Variable
A location in memory used to hold a data value.
Local variable
A variable declared inside a method that is accessible only in that method.
Loop Variant
An assertion whose truth changes between the first and final execution of the loop. ex: During a loop when executed Such as a for loop when a value has matched the final requirement either by making a value true or proving it false.
classpath
An enviroment variable that includes an argument set telling the Java virtual machine where to look for user defined classes/packages.
Why is a static variable also referred to as a class variable? A) There is a single copy available to all objects of the class. B) It is encapsulated within the class. C) Each class has one and only one static variable. D) It is stored in the separate class area of each object.
Ans: A Section Ref: 8.7
Which of the following describes an immutable class? A) A class that has no accessor or mutator methods. B) A class that has no accessor methods, but does have mutator methods. C) A class that has accessor methods, but does not have mutator methods. D) A class that has both accessor and mutator methods.
Ans: C Section Ref: 8.3
Declaring a variable
Associates variable's name with type ~DOES NOT ALLOCATE MEMORY FOR STORAGE
Layering Reader Classes
BufferedReader in = new BufferedReader( new FileReader(path))
/
Division
Surround all String text with?
Double Quotes
True or False: A class can not implement multiple interfaces.
False.
True or False: A class with a private constructor can be inherited.
False.
True or False: An object of a base class can be referred to using a reference variable of its derived class.
False.
True or False: Private members of a base class can be inherited in the derived class.
False.
#119 True or false? method and variables can be declared as final, but a class cannot be declared as final
False. A final class is a class which can NOT be subclassed, It is the end of the line in the inheritance tree.
True or False: An abstract method can not be overridden.
False. Abstract methods are meant to be overridden by subclasses.
#156 True or false? An interface can extend at most one interface.
False. An Interface may extend multiple interfaces. A class is however, limited to extending only one class.
True or False: A class uses the keyword extends to implement an interface.
False. It uses the keyword implements to implement an interface.
True or False: constructors are inherited by the subclass.
False. Never.
Reasons to use "float"
127 digits after the decimal point
Example of how to "get" a vector element using an index:
String s1 = (String)v.get(0); ( you must cast the returned element bc by default vectors are designed to work with the Object class
this Reference
A reference variable that lets an object refer to itself
API
Application Program Interface (API) • Set of classes & interfaces that can be used to develop Java programs.
-
Subtraction
#80 Can one object access a private variable of another object of the same class.
Yes. private means "to the class", NOT "private to the object". So two object of the same class could access each other's private data.
identifier
a name
parameter
a value or expression passed in a method call
Instance variables can't be ...
abstract, synchronized, native, or strictfp.
A class implementing an interface can itself be ...
abstract.
int
data type integer
Pass by value
for primitive data types
*IS-A* refers to ...
inheritance.
If a superclass member is public, the subclass ...
inherits it - regardless of package.
If a class cannot be accessed, its members ...
cannot be accessed.
Build a void method
public void main
Bounds Checking
Makes sure that the index is within the range of the array being referenced. If the index is not valid, an ArrayIndexOutOfBoundsException is thrown. Automatically performed by the index operator.
Encapsulation
Making some data and methods inaccessible to outsiders ~public: visible anywhere ~private: visible only to other class members ~protected: visible to class and subclass w/i pkg
degrees to radians
Math.toRadians();
pass by value
It really means 'make a copy'.
Binary Search
More efficient than a linear search, but only works if the indexes are in order/ are sorted.
\n
New line
!=
Not equal to
How many dimensions can standard Java arrays have?
Standard Java arrays can have one or many dimensions.
-Must end with a ; (semicolon)
Statements
draw filled circle at (x, y) radius = r
StdDraw.filledCircle(x, y, r);
draw an image, starfield.jpg at (0, 0)
StdDraw.picture(0, 0, "starfield.jpg");
Enclosing Classes
The class that the nested class is nested in
What are single array variables capable of doing?
They can reference a large collection of data
true or false
A boolean value can be ____ __ _____
+=
Increment operator - Increases value of operand by whatever number is placed after
Collision
Two or more data values that hash to the same cell.
applet
a java program that can be downloaded and run on a web browser
System.out.println("ab\"\\c"); prints out
ab"\c
not equal
!=
What package is the ArrayList part of?
" java.util package " The ArrayList class is part of the java.util package.
String combination identifier
"+"
What does the greek word polymorphism mean?
"changeable".
How many classes can a subclass extend directly?
1
random number between 1 and n
1 + Math.random() * n;
short
2 bytes, stores integer values
2000
20 + '0' + 0=
Method
A way of doing something
&&
AND Operator. If both boolean operands are true, the condition becomes true
LinkedList
Makes it easy to create structures like stacks or queues.
return function?
Returns and expression. ex. return first + " " + middle + " " + last;
What word is always capitalized in java syntax?
String
/** */
opening comments
charAt
stringname.charAt(positionStartingAtZero)
statements
change the state, ie change the value of a variable
System.out.println("fun\tny"); prints out
fun ny
Chapter 1: Patterns give us a shared _______
vocabulary
Mutator method
(Setter) - changes the value of a private field of an obj.
Which two reference types *cannot be instantiated*?
*Abstract classes and interfaces*
long
4 bytes, stores long integer values
"Explain inheritance."
"Inheritance means that objects of one class can derive state and/or behavior from another (base or parent) class."
"What is the common superclass from which all Java classes derive directly or indirectly?"
"Object."
remainder
%
Logical Operators
&& ||
Compiler
A highly specialized piece of software that takes a programming language understandable by humans and converts it into a language that computers can understand.
The BitSet class also provides other methods for performing comparisons and bitwise operations on sets such as:
AND, OR, and XOR
name [row] [col]
Access an element
.java
All Java file names have to have this extension.
Work with Java Arrays
Chapter 6 Objective 1
Graphical User Interface
GUI - PC users view of the "out" screen
Does polymorphism make objects more specific or general?
General
Natural logarithm of a number?
Math.log()
larger value of x and y?
Math.max(x,y)
False
True or False? + and - have higher precendence than *,/, and %
else
Used in conjunction with if. Checks if the condition is false
Can a class implement multiple interfaces.
Yes
public
an access specifier
An open brace is always followed by a close
brace }
-8 bits Range: -128 to 127 No rules
byte
variables
computer memory locations that hold values
Chapter 1: Patterns aren't invented, they are
discovered
\\
escape character for backslash
What keyword is used to extend or inherit a class?
extends
expressions
have values
if
if (Boolean expression) { Statements; } conditional statement
The first concrete class to extend an 'abstract' class must ...
implement all of its 'abstract' methods.
______\n______ is the escape sequence for
new line
instantiation operator
new, third highest precedence, right to left association
hardware
physical computer and peripheral devices
Prints to a new line and flushes the buffer.
println
I shouldn't be used with instance variables
public
What *access modifier* is used for *methods* that were defined *in an interface*?
public
'final' variables cannot be ...
re-initialized once assigned a value.
removes an element based on the element itself rather than on an index:
removeElement("Inkster");
syntax
rules of a computer language
-16 bits Range: -32,768 to 32,767 No rules
short
if-else construct
tests value of var/expr
WAN
undisciplined; unrestrained; reckless
run-time errors
when a computer is asked to do something that is considered illegal
variable declaration statement
when a program declares the type of a variable
An increment operator
x+++
Can you have 2 action listeners?
yes, but not ideal
Upcasting is when ...
you can assign a reference variable that refers to a subtype object to a supertype reference variable explicitly or implicitly. This is an inherently safe operation because the assignment restricts the access capabilities of the new variable.
Modulus operator
% returns remainder
What is method polymorphism?
The actual method that is executed depends on the type of an object, not the reference type of its variable.
==
Used to equal a value
Instance Variables
Variables associated with each object from a class - stored in separate mem location
Primitive and Reference
Variables come in two flavors.
New tab character
\t
Tab
\t
A thread can be created in two ways:
by subclassing the Thread class or implementing the Runnable interface in another class.
What is a local variable?
can be used only in the method that declares it from point of declaration to end of method
contains()
method from hashtable class that checks whether an object is stored in the hash table.
int input
nextInt()
short input
nextShort()
floating point numbers
numbers where a fractional part is required
When using the BitSet class "0" represents ______
off or false(boolean)
When using the BitSet class "1" represents ______
on or true(boolean)
A class can extend only ...
one class (no multiple inheritance), but it can implement many interfaces.
Interfaces can extend ...
one or more other interfaces.
Inheritance allows a class to be a subclass of a superclass, and thereby ...
inherit public and protected variables and methods of the superclass.
By definition, I take one argument.
setter
String
~Set of characters that are treated as objects ~Are immutable
ArrayList
~Subclass of Collection ~Works like an array, but SIZE can be EXPANDED easily. Very efficient for random accessing, but not so for inserting in the middle.
A remote control
What does a reference variable liken to?
Chapter 1: We often try to take what varies in a system and
encapsulate it
Parallel Arrays
Two arrays with corresponding elements.
blank.
Value
"
\"
while
while (true) { }
Hash Table
An array used for hashing.
Object
An instance of a class.
Exception
An object defining a problem that can usually be fixed
What is the type of a variable that references an array of integers? A) int[] B) integer() C) integer[] D) int()
Ans: A Section Ref: Section 7.1 Arrays
A class that cannot be instantiated is called a/an ____. A) Abstract class. B) Anonymous class. C) Concrete class. D) Non-inheritable.
Ans: A Section Ref: Special Topic 10.1
Which of the following statements about a superclass is true? A) An abstract method may be used in a superclass when there is no good default method for the superclass that will suit all subclasses' needs. B) An abstract method may be used in a superclass to ensure that the subclasses cannot change how the method executes. C) An abstract method may be used in a superclass when the method must have identical implementations in the subclasses. D) An abstract method may not be used in a superclass.
Ans: A Section Ref: Special Topic 10.1
A static method can have which of the following types of parameters? A) Only implicit parameters. B) Only explicit parameters. C) Both implicit and explicit parameters. D) A static method cannot have parameters.
Ans: B Section Ref: 8.6
pre-test loops
- for construct - while construct
The Parts of a typical class
...
Polymorphism allows an object to be referred to as?
1. any base class it *extends* 2. any interface that it *implemented*
Which of the following statements generally describes the scope of a variable? A) The ability of a variable to access other variables in the same program. B) The amount of data in bytes that the variable can contain. C) The range of data types that the variable can legally be cast into. D) The region of a program in which the variable can be accessed.
Ans: D Section Ref: 8.8
Which of the following statements about an inner class is true? A) An inner class may not be declared within a method of the enclosing scope. B) An inner class may only be declared within a method of the enclosing scope. C) An inner class can access variables from the enclosing scope only if they are passed as constructor or method parameters. D) The methods of an inner class can access variables declared in the enclosing scope.
Ans: D Section Ref: 9.8
Abstract data type
= class
What is the assignment statement
= its the equal sign
assignment operator
=, lowest precedence, right to left association
Comparison operators: Equal to, Not equal to, greater than, greater than or equal to, less than, less than or equal to
== != > >= < <=
double
A data type of real numbers (1/2, 99.9, -0.1).
reusability
A feature of object-oriented programming that reduces development time and decreases the likelihood of bugs.
Method
A group of programming statements given a name.
return
A method can have only one of these.
Abstract Method
A method that does not have an implementation (no body of code defined)
abstract method
A method that has been declared, but not implemented. Abstract methods appear in abstract classes. They are implemented in a subclass that inherits the abstract class.
Combinatorial Explosion
A multiplicative growth. ex: If in A is introduced it has two possible states true or false. When B is introduced there are 4 possible states.
Output Assertion
A postcondition for a loop ex: As in a do-while loop, the while is post conditional, therefore the final value (if not instantiated correctly) will contain a off-by-one error. A do-while loop performs postcondition
Assembly Language
A programming language that uses letters and numbers to represent machine language instructions
An object is this type of variable
A reference variable
Declaration
A request to set aside a new variable with a given name of type; you must do this before assigning a value to a variable.
String
A sequence of characters
Escape Sequence
A sequence used to represent special characters.
Expression
A simple value or a set of operations that produces a value.
Empty String
A special string literal, denoted by "".
Assignment Statement
A statement assigning a value to a variable.
Static (Class) Variable
A variable shared among all the objects in a class. If the value changes in one object, it changes in all of the others.
Byte
A variable type that is a sequence of 8 bits (enough to represent one character of alphanumeric data) processed as a single unit of information, Range [-127,128]
Equivalence Class
All the sets of test data that exercise a program in the same manner ex: all data types listed.
flow control structures
Allow different segments of code to be executed under different circumstances. Keywords : if...else, switch..case (all selection statements).
StringBuffer
Alters immutability
String Literal
Anything within double quotation marks.
Methods?
Are always public. They return data. Methods are made so that you can call on them so that you can use its functionality.
Parameters are filled in with _________________ when invoking a method.
Arguments
exception that is thrown when your not properly checking to make sure that your code always stays within the bounds of an array
ArrayIndexOutofBounds
One-Dimensional Array
Arrays that store a simple list of values.
Which syntax is correct? A. abstract class Automobile{ void honk(); //(2) } B. abstract class Automobile{ void honk(){}; //(3) } C. abstract class Automobile{ abstract void honk(); //(5)
B and C are correct A is wrong because method honk() does not have any body. So, it should be an abstract method, but then abstract method needs the keyword "abstract" at the beginning of the method declaration. B is correct because a class can be an abstract class even if it does not have an abstract method... strange but true.
Where must all import declarations appear?
Before the first class declaration
Naming Methods?
Begins with public then is whatever data is going to be returned. ex. public String displayname()
Case SenSitive
Capital letters must be capitalized to reference a variable correctly
String literals are made up of
Character primitives
What are the TWO types of data contained by classes?
Characteristics and Behavior
Comparing Characters
Characters in Java are based on the Unicode character set Unicode establishes a particular numeric value for each character, and therefore an ordering We can use relational operators on character data based on this ordering For example, the character 'a' is less than the character 'b' because 'a' comes before 'b' in the Unicode character set In Unicode, the digit characters ('0'-'9') are contiguous and in order Likewise, the uppercase letters ('A'-'Z') and lowercase letters ('a'-'b') are contiguous and in order
Relational Operators
Check relationships between values of *the same type* and will be part of a logical expression. Can be used with floating points, integers and characters (including >, <, <=, >=). booleans only use '==' and '!=' which can also be used with other types.
How do you call a method from a class?
ClassName.methodName(arguments)
//
Comment (??) ignore the elephant
// marks the single line ? /* block ? */
Comments
Chapter 12: The view uses the ____________ to implement the user interface, which usually consists of nested components like panels, frames and buttons.
Composite Pattern
Character types (char)
Contain single character value stored as unicode characters
Chapter 12: The ______ is the strategy for the view.
Controller
new type [nRows] [nCols]
Create a 2D array
throw
Creates a new exception object and indicates that an exceptional situation (usually something unwanted) has occurred.
4) For the following method, what happens if b is 0.0: public static double div(double a, double b) throws Exception { if (b == 0.0) then throw Exception("Divide by zero"); return a / b; } a) 0 is returned b) an exception is thrown c) nothing is returned d) b) and c)
D
What kind of value and how much will be stored?
Data Type
What are the class relationships? Dependency Aggregation
Dependency - method of one class invokes methods of another (depends on other) Aggregation - an object made up of other objects it depends on
Arithmetic Expression Type
Depends on the types of the variables or literals used in the expression. E.g 3/4 would be 0, integral, and the fractional part discarded. However if an expression mixes integrals and floating points, the expression will return a floating point type.
/=
Divides value of operand by whatever number is placed after
Exception that occurs when you're reading from a file and the file ends before you expected it to end.
EOFException
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.
Representing a character using a binary code.
Encoding
return
Ends execution of a method and possibly returns a value to the calling code.
Pseudocode
English-like descriptions of algorithms.
What are the two subclasses of the throwable class?
Error & Exception
In particular, exceptions of either the ______or ____________ class or any of their subclasses do not have to be listed in your throws clause.
Error & RuntimeExceptions
Logical Expression
Evaluates to either 'true' or 'false' (boolean literals). Can be used for conditional processing in flow control structures.
int value = matrix [3] [2]; Pixel pixel = pixels[r] [c];
Example: Accessing two elements
int [] [] matrix Pixel [] [] pixels
Examples of 2D array declarations
new int [5] [8] new Pixel [numRows] [numCols]
Examples of creation of 2D arrays
True or False: If a method defined in a base class is overloaded in the derived classes, then these two methods (in the base class and the derived class) are called polymorphic methods.
False. Only overridden methods can be called polymorphic.
Creating a File object
File f = new File(pathName);
How is the filename of a public class formatted?
Filename.java
Data Type Sizes
Fixed in Java, to ensure portability across implementations.
Difference bw floating type vs. double type
Float → 6-7 sig. digits of accuracy Double → 14-15
Relational Operators and Floating Points
Floating point values have limited precision, they are approximations, therefore using relational operators requires care (e.g. might be best to check within a precision range).
Time Efficiency
How long it takes an algorithm to run.
4
How many times does HI print?: int x = 3; int y = ++x; for(int a=0; a<y; a++){ System.out.println("HI"); }
3
How many times does HI print?: int x = 3; int y = x++; for(int a=0; a<y; a++){ System.out.println("HI"); }
Inheritance
How one class can be created from another.
Bit
I binary digit, either 0 or 1
encapsulation
I prefer my instance variables private.
switch fall-through
If a 'break' keyword is missing after a case, processing will continue through to the next case and until it reaches a break statement or the end of the switch statement.
What syntax error should you be aware of when entering parameters for a method?
If you set two variables as the same type, but don't use two type indentifiers then it creates a syntax error. You should always use a type identifier for each variable: double x, y = NO double x, double y = YES
When are static instance blocks executed in an objects lifecycle?
Immediately after the call to super's constructor and before the instance constructor's code. Blocks are called in top to bottom order.
List Interface
Implemented by classes that represent an ordered collection of element such as numbers or strings.
volatile
Imposes strict rules on the use of a variable by more than one thread at a time.
non-static nested class (inner class)
In Java, a *nested class* that is *not static* is called an *inner class*. An inner class can interact with the instance of its enclosing class—it has access to private variables and methods of the enclosing class. An inner class, being 'bound' to an enclosing instance, *cannot declare static* members of its own. An inner class may be named or it can be anonymous (often used a a crude way to approximate closures prior to Java 8).
:
In a ternary operation, if the boolean condition is false, the value after the _ is returned.
?
In a ternary operation, if the boolean condition is true, the value after the _ is returned.
curly brackets and ;
In general, Java doesn't require code blocks delimited by '{..}' to be followed by a ';' as would normally be the case for a statement.
double
Indicates that a value is a 64-bit number with one or more digits after the decimal point.
static
Indicates that a variable or method belongs to a class, rather than to any object created from the class.
difference between absttract class and interface instance and static block
Inside abstract class we can take instance and static block. Inside interface we can not take instance and static block.
Integer Literals
Integers embedded into Java source code, can be expressed as a decimal number by any sequence of digits 1-9. Are considered 32 bits long but can be converted by following them with a "L".
Which *reference type* cannot contain implementation?
Interface
class
Introduces a class — a blueprint for an object.
Java Program
Is a sequence of statements(smallest executable unit) that have to be formed in accordance with a predefined syntax.
Just-in-Time Compilation
JIT - Technique used to translate byte code into machine language - Once program is saved, computer remembers it and program will run faster
HashMap
Lets you store and access elements as name/value pairs.
Instance Variables are
Lifetime: instance variables exist as long as the object exists Scope: instance variables can be referenced by all methods in that class
A constant value that appears directly in the program
Literal • may be numeric, character, boolean, or **null** for object type.
Define how java classes are connected.
Loosely connected objects that interact with each other.
Smaller value of x and y?
Math.min(x,y)
x^y
Math.pow (x, y);
Random Number
Math.random()
random number between 0 and n
Math.random() * (n + 1);
random number between 0 and 1
Math.random();
Sine?
Math.sin(#)
sin x
Math.sin(x);
Square Root
Math.sqrt
Tangent?
Math.tan(x)
radians to degrees
Math.toDegrees();
%
Mod/Remainder. Where: 1) Numerator is smaller than the denominator, % returns the numerator. 2) Numerator is 0, % returns 0. 3) Denominator of 0, % returns an error.
...
Multi-dimensional arrays can declared with the new operator by placing the size of each dimension in square brackets. Example: int[ ][ ][ ] threeDArray = new int[3][2][2]
...
Multi-dimensional arrays do not have to declare the size of every dimension when initialized. Example: int[ ][ ][ ] array5 = new int[3][ ][ ]
What is multiplicity?
Multiplicity refers to the number of objects that a part of a relationship. The three general classifications of multiplicity are *one-to-one, one-to-many, and many-to-many*.
*=
Multiplies value of operand by whatever number is placed after
IS-A relationship example
Mustang IS A Horse, Subaru IS A Car, Subaru IS A Car IS A Vehicle, etc. IS-A relationship is expressed through "extends" and "implments" keywords. Credit: Most of these note cards are taken from OCA/OCP Java SE 7 Programmer I & II Study Guide (Exams 1Z0-803 & 1Z0-804) and Enthuware.com java se 7 mock exams. I highly recommend these sources in order get the OCAJP SE 7 certification.
A no-argument constructor has....
No parameters.
Does Java allow multiple inheritance?
No. C++ allows multiple inheritance but Java doesn't. Each class can inherit from just one Parent class. However a class can have mutliple ancestors, Ex: C could extend B, B could extend A, and so on. Multiple inheritance might lead to "Deadly Diamond of Death" issue.
Is casting needed when going from a primitive type to its wrapper classl?
No. Java's autoboxing/unboxing does it automatically.
Ways to handle an exception
Not handle it at all - program will crash and and produce a message describing the exception
*** If a variable is used as an argument...
ONLY the value of the the argument is plugged into the parameter, NOT the variable itself
Chapter 1: defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
OO Patterns: Strategy
Chapter 1: Patterns show you how to build systems with good
OO design qualities
A class is a type whose values are ______
Objects
By Value
Objects passed to a method "by value" meaning that the current value of the actual parameter is copied to the formal parameter in the method header
Chapter 12: The model (MVC) makes use of the _______ so that it can keep observers updated yet stay decoupled from them.
Observer Pattern
Question: If the class Manager extends the class Employee, and a reference variable emp of type Employee is used to refer to an object of the class Manager, what operation can be done to access the derived class variables and methods of Manager?
Perform a cast operation: ((Manager)emp)
What is a fundamental concept of object-oriented languages like JAVA and stimulates code reuse?
Polymorphism
if...else if... statement
Possible to chain many if..else statements by using 'else if...' statements. In the form 'if(logical_expression) { statements; } else if (logical_expression) { statements; } else { statements; }'. Note that you can have as many 'else if' statements as you like, and you don't have to end with an else code block.
What is assumed to be true when a method is called
Precondition
HashSet
Prevents duplicates in the collection, and given an element, can find that element in the collection quickly.
Java Type Categories
Primitive Types & Reference Types. It is possible for the user to create further reference types but there is a limited number of pre-defined Java primitive types.
Stores a specific type of value
Primitive data types
Integral Types
Primitive types, all signed : byte, short, int, long. Fixed length, regardless of platform. Can all take integer literals. An integer variable can hold the result of an *arithmetic expression*.
Layering Writer Classes
PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter(path)));
If an instance variable or method is _____ then it cannot be directly referenced anyplace except in the definition of a method of the same class.
Private
Caching truth or falsity
Rather than constantly checking the truth of a logical expression, sometimes it is better to store the result in a boolean and use that subsequently. For example 'boolean isFlying = height > 0.5f; if(isFlying == true) { flapWings(); }'
Stores (points to) the memory address of an object
Reference variable
boolean
Relational operators always result in a ________ value.
Java1
Result? "Java" + 1
Iteration
Returning an object that can be used to cycle through all of the elements in a list
%=
Returns remainder of value of operand after divided by whatever number is placed after
String method length()
Returns the number of characters in a string, counting from 1. E.g. "12345".length() would return 5. An empty String has length 0.
implements
Reuses the functionality from a previously defined interface.
exceptions that usually occur because of code that isn't very robust.
Runtime Exceptions
When something goes wrong while the program is running. (Also known as exception)
Runtime error
Data Type 'String'
Sequence of characters, a reference data type.
Instance variables
Set to 0 a = 0; b = 0; c = 0;
Operators
Sets of which are associated with primitive datatypes, can be either unary or binary, depending on whether they require one variable or two (operands). E.g. addition, multiplication or increment.
Object
Special kind of variable containing DATA and METHODS
What is program control?
Specifying the order in which statements(actions) execute in a program.
What are standard Java arrays and when must they be initialized?
Standard Java arrays are objects and must be initialized after they are declared.
set x and y window scale to -R , R
StdDraw.setXscale(-R , R); StdDraw.setYscale(-R, R);
0 or more characters surrounded by double quotes?
String (always capital "S")
String declaration
String name = "";
nextLine()
String of words
Promotion
Term used when casting a smaller memory type to a larger memory type and therefore a cast is not needed (in the reverse case, a cast is needed).
assert
Tests the truth of a condition that the programmer believes is true.
What does empty Parenthesis at the end of a method declaration mean?
That the data for the method will be put in later.
both
The & and | operators always evaluate ____ operands.
true
The && and & operators return true only if both operands are _____.
short-circuit
The && and || are known as _____-________ operators
What is the ArrayList class a representation of?
The ArrayList class is an object-orientated representation of a standard Java array.
What does it mean in an && operator statement to have a dependent condition?
The dependent condition is the one that gets tested first and must come after the && operator
abstract
The keyword used for declaring a class or a method as abstract.
Index/Subscript
The number for each position of a stored array value. Always starts from zero.
Octal
The numbering system using 8 as its base, using the numerals 0-7 as its digits. In programs written in the Java programming language, octal numbers must be preceded with 0.
Operator Precedence
The rules that govern the order in which operations are done.
Data encapsulation
The separation of the representation of data from the applications that use the data at a logical level; a programming language feature that forces information hiding.
Explain what Scanner input = new Scanner(System.in); does.
The syntax new Scanner(System.in) creates an object of the Scanner type. The whole line Scanner input = new Scanner(System.in) creates a Scanner object and assigns its reference to the variable input.
What restriction applies to the target type when performing reference type casting?
The target type must the object type or a valid supertype.
Element Type
The type of values stored in an array.
Hexadecimal
These digits operate on a base-16 number These numbers use the letters A, B, C, D, E, and F along with the numbers 0 to 9 to create their 16 different digits, where A represents 10 and F represents 15. In programs written in the Java programming language must be preceded with 0x.
Data Fields
These fields (46 to 1500 bytes) contain the encapsulated data from a higher layer, which is a generic Layer 3 PDU, or more commonly, an IPv4 packet. , variables you declare with a class, but outside of any method.
Values passed in and out of methods
They can be implicitly promoted to a larger type or explicitly cast to a smaller type
parts of a program set up to run on their own while the rest of the program does something else.
Threads
java.net.*;
To develop a networking application.
inherit
To receive the methods of a superclass.
True
True or False? The || won't evaluate the right operand if the left operand is true.
True or False: The invocation of the base class' default constructor occurs automatically unless we use the super keyword to invoke an alternative base class constructor.
True.
subclasses of the RuntimeException and Error classes and are usually thrown by the Java runtime itself.
Unchecked exceptions
int
Used to declare and initialize a non fraction interager Ex: int canVolume = 5;
Long
Variable type of 64 bits and with a range of [-9223372036854775808, 9223372036854775807]
The number and type of values
What must match the order and type of the parameters declared by the method?
literal values or values of declared type.
What type of values you can pass as an argument to a method?
A void return type does not return anything
What void return type mean?
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.
Truncation
When casting a larger type to a smaller type there may be a loss of information due to the truncation of additional bits or the fractional part of the number when casting from a floating point number to an integral number.
object
When comparing reference variables, == returns true only if both references refer to the same ______
When naming variables, what is camel case?
When the words following the first word having a captial first letter: alphaQuadron
Initialization
When you first store something in a variables memory location.
will the code below work? public Animal getAnimal() { return new Horse(); }
Yes, because Horse IS-AN Animal
Can main() be overloaded?
Yes, of course.
Can standard Java arrays be multi-dimensional?
Yes, standard Java arrays can be multi-dimensional; each set of square brackets represents a dimension.
#21 Can an abstract class have non-abstract methods?
Yes. Unlike interfaces, abstract classes CAN provide implementations of methods.
\
\\
'final' reference variables cannot refer to ...
a different object once the object has been assigned to the 'final' variable.
low-level programming language
a language that corresponds closely to a computer processors's circuitry
object
a specific concrete instance of a class
import statement
a statement that allows a program to access resources in a library
Local (method, automatic, or stack) variable declarations cannot have ...
access modifiers.
'static' methods do not have direct ...
access to non-static members.
A 'protected' member inherited by a subclass from another package is not ...
accessible to any other class in the subclass package, except for the subclass' own subclasses.
What is an object
an Object is an instance of a class (created by instantiating a class with a new keyword and a constructor invocation) for ex. Point p = new Point(1.0, 2.0);
'synchronized' methods can have ...
any access control and can also be marked 'final'.
How can you specify a string to make a assert statement more meaningful
assert price > 0 : "Price less than 0.";
Computer Simulations
attempt to mimic real-world activities so that their process can be improved or so that users can better understand how the real-world process operates
Value: true/false
boolean
Example of how to use the contains method when working with hashtables:
boolean isThere = hash.contains(new Rectangle(0, 0, 5, 5));
The next() method always returns an object of the class Object.To get around this you can _____ the object into a more appropriate object.~223
cast
-16 bits unsigned Range: 0 to 65535 -Holds one letter -Value enclosed in ' ' -Outputs letter unless addition is in parenthesis
char
Escape Sequence
characters marked by a backslash \ that represent special information such as non-standard unicode characters, e.g. '\u00A9'. Also non-printable characters, e.g. newline '\n'.
Java interpreter
checks the bytecode and communicates with the operating system, executing bytecode instructions line by line within the JVM
public class _____
class header; indicates a publicly accessible class named "_____"
Instantiating an object
class name object name = classname();
Default members can be accessed only by ...
classes in the same package.
abstract class is a
collection of abstract method and concrete methods. it does not support multiple inheritance Abstract class is preceded by abstract keyword.
A variable declared "Final"
constant
Boxing
converting a primitive value to a wrapper obj.
declare and initial double array, points, with length N
double[] points = new double [N];
In Java, the strange events that might cause a program to fail are called
exceptions
procedures
individual operations grouped together for connivence -in Java also called methods
length
int variable = stringname.length();
What is used to define a public interface?
interface
How should we create methods?
method decomposition parameters
hasNext()
method determines whether the structure contains any more elements.(if you've implemented the iterator interface)
public static void main(String [ ] args)
method header;
{ }
opening/closing braces; encloses a group of statements, such as the contents of a class or a method
Abstract method must be ...
overridden by the first concrete (non-abstract) subclass.
to swap values of integers you need a...
place holder
final named constants
private static final double PI = 3.14159;
How to define a class?
public class "class name" (no extension)
Which declaration for concrete class B indicates it implements the interface A?
public class B implements A { }
first line of program, HelloWorld
public class HelloWorld
I always fly solo.
return
This method is the engine of a threaded class.
run()
Java Applications
stand-alone programs which be subdivided into: -console applications which support character output to a computer screen in a DOS window -windowed applications which create GUI with elements such as menus, tool bars, and dialogue boxes
To run a thread what method must be callled?
start() method
source code
statements that you wrote
How do you set up a switch method?
switch () Case #: (statement)(++acount) (break;) Case #: (statement) (break;) Case #: (statement)
_______\t________ is the escape sequence
tab
High cohesion is ...
the desirable state of a class whose members support a single, well-defined role or responsibility.
software
the programs that the computer executes
In a variable, what corresponds to the type in the variable declaration?
the reference type
*IS-A* relationship
the relationship between an object and the class of which it is a member
Tight coupling is ...
the undesirable state of having classes that break the rules of loose coupling.
hacking
the use of clever techniques to write a program, often for the purpose of gaining access to protected resources on networks
A parameter is a local variable initialized to....
the value of the corresponding argument. (Known as Call-by-value)
true or false: a class can only extend a single class
true
to "catch" a exception you must surround it with a ____ & _______
try & catch
What are common errors # 2 with selection statements ?
using a semi colon at the end of an if line
sentinel
value that serves as a signal for termination
integers
whole numbers without a fractional part
keywords
words in java that cannot be used as user-defined symbols
reserved words
words that cannot be used as an identifier
import x.y.z
x - overall name of package, y - name of package subsection, z - name of particular class in subsection
Postincrement
x++ "Give me x, then increment"
Example using compound assignment
x+=1 • which is the same as → x = x + 1
A decrement operator
x--
Scanner methods
~nextInt(),....,nextLine() ~next(): returns next token ~hasNext(): boolean: returns true if source is full; false if empty
Uses a phone line & can transfer data in a speed 20 x faster vs. regular modem.
• DSL (digital subscriber line)
Passing by reference
An Array is - it passes info about where the array is stored in memory
...
An ArrayList object can have any element in it removed and will automatically move the other elements.
What is the proper signature for *class X* if it *inherits class Z*? class Z is the superclass class X is the subcalss
public class *X extends Z* {} *inherits = extends = erbt von
What is the perferred method of storing datat in an array?
In most cases, the ArrayList is the preferred method of storing data in an array.
throws
Indicates that a method or constructor may pass the buck when an exception is thrown.
short
Indicates that a value is a 16-bit whole number.
char
Indicates that a value is a character (a single letter, digit, punctuation symbol, and so on) stored in 16 bits of memory.
byte
Indicates that a value is an 8-bit whole number.
protected
Indicates that a variable or method can be used in subclasses from another package.
private
Indicates that a variable or method can be used only within a certain class.
public
Indicates that a variable, class, or method can be used by any other Java code.
abstract
Indicates that the details of a class, a method, or an interface are given elsewhere in the code.
what is the code to display the current time?
System.currentTimeMillis()
Set of print commands to print to the console on two different lines?
System.out.print("Hello"); //no "ln" System.out.print("World"); //Has the "ln"
System.out.print(...) System.out.println(...) ln prints in new line
!
The ___ operator, called the "inversion" operator, returns the opposite value of the boolean value it precedes.
In an object variable, what does the reference type determine?
The visibility of subtype members
Boolean Literal
The words true and false.
True or False: A class that is inherited is called a parent or base class.
True.
True or False: With inheritance, you can also refer to an object of a derived class using a variable of a base class or interface.
True.
True or False: class that inherits another class is called a derived class or subclass.
True.
Prints x on the same line
print(x)
commands
program statements
write and instance field
public double r;
Classes can have only ...
public or default access.
J2EE
Acronym for Java 2 Platform, Enterprise Edition.
J2ME
Acronym for Java 2 Platform, Micro Edition.
This method is present in all exceptions, and it displays a detailed error message describing what happened.
.getMessage() method
What operator divides two numbers?
/
Life Cycle - Runnable
- A pool of potentially runnable threads...-Not actively running...-Scheduler will select a thread from this group...-The only state a thread can go to from Runnable is the Active State
Nested Loop
A loop as one of the statements in the body of another loop. Random rnd = new Random(); while (true) { System.out.println(rnd) if(true){ } System.out.print(rnd) }
/* */
Used to comment out a paragraph or longer
Class Variables
Variables associated with ENTIRE class
else
Introduces statements that are executed when the condition in an if statement isn't true.
Extreme Condition
Data at the limits of validity ex: When a data type is (almost) overwhelmed by the data value; an int hold (almost) or trying to hold past its 32 bit limit which it will succeed.
What does a boolean data type declare?
Declares a variable that is either true or false
Localizing variables
Declaring variables in the innermost scope possible.
-=
Decrement operator - Decreases value of operand by whatever number is placed after
||
Or
3
Result? 2 + 1
abs
abs() absolute value
modulus
operator
.Java~
- This file cannot be used for anything
What are the two meanings of + sign
1 is for additions, the other is for string concatenation operator. System.out.println("Introduction to Java Programming, " + "by Y. Daniel Liang"); or System.out.println("j is " + j + " and 8 k is " + k);
There are three access modifiers:
1) 'public' 2) 'protected' 3) 'private'
Instance variables can ...
1) have any access control 2) be marked 'final' or 'transient'
There are four access levels:
1) public 2) protected 3) default 4) private
What is the ASCII value of 'a'?
97
key
A ____ is an identifier used to reference, or look up, a value in a data structure.
Anonymous inner class
A local class whose definition and use are combined into a single expression
Data type
A name for a category of data values that are all related. Ex. "int" is the category of integers.
Class constant
A named value that cannot be changed. A class constant can be accessed anywhere in the class. (It's scope is the entire class).
Nested classes/inner classes
A nested class is a class that is a member of another class. Example: class EnclosingClass{NestedClass}}
High-level language
A programming language whose concepts and structures are convenient for human reasoning. Such languages are independent of the structures of computers and operating systems.
Aliases
A reference to an object that is also referred to by another reference. Each reference is an alias of each other.
.....How would a three dimensional array be declared as? (How would it look like?)
A three dimensional array would be declared as int[ ][ ][ ] threeDArray.
Statement
A unit of executable code, terminated by a semi-colon.
Off-by-one Error
An error that occurs because indexes begin at zero and not one.
&&
And
Another Example
Another example: If count equals 1, the "Dime" is printed If count is anything other than 1, then "Dimes" is printed Even when the conditional operator is a viable alternative, you should use it carefully because it may be less readable than an if-else statement.
Consider the following code snippet: Vehicle aVehicle = new Auto(4,"gasoline"); String s = aVehicle.toString(); Assume that the Auto class inherits from the Vehicle class, and neither class has an implementation of the toString() method. Which of the following statements is correct? A) The toString() method of the Object class will be used when this code is executed. B) The toString() method of the String class will be used when this code is executed. C) This code will not compile because there is no toString() method in the Vehicle class. D) This code will not compile because there is no toString() method in the Auto class.
Ans: A Section Ref: 10.7.1
What is the name of the class that is being inherited?
Base of superclass
Hash Function
Calculates the hash code from properties of the data itself.
Strings and escape sequences
Can be included in a string as if they were another character using the backslash \. E.g. "\"This is a string\"" uses \" to include double quotation marks as characters in the sequence.
switch default case
Can be included to perform some processing if none of the other cases in the switch statement are selected, such as throwing an exception. It isn't a requirement but is good style.
Primitive Variables
Can store data values.
Overview of Classes
Classes are the most fundamental structural element of java programs. you cant write a java code without defining a class. Java statements appear within classes, and all methods are implemented within classes
What is camel casing?
Each time a new word begins start it with a capital letter
-Begins with a \ -Always comes in pairs
Escape sequences
Numbers with radix 16
Hexadecimal
What are the 3 selection statements? And the 3 Repetition Statements?
If, If...else, and Switch While, do...while, and for
What are some characteristics of an abstract class?
It can not be instantiated. It must be extended. It may or may not contain abstract methods.
Exception that occurs when a URL isn't in the right format (perhaps a user typed it incorrectly)
MalformedURLException
absolute value?
Math.abs(#)
arc cos x
Math.acos(x);
switch....case use-age
Multi-coniditional branching. Used instead of the 'if' statement when a large number of outcomes need to be tested. Each case contains code that is executed if the switch argument takes on a particular value.
...
Multi-dimensional arrays do not have to have the same size sub arrays. Example: int[ ][ ] oddSizes = {{1,2,3,4},{3 },{6,7}}
Can a static method be overridden?
No.
Reasons to use "int"
Numbers -2 billion to, 2 billion
During runtime, value assigned that exceeds positive bounds of a variable
Overflow error
Variable shadowing vs. Method overriding
Overriding Is Not Shadowing
super
Refers to the superclass of the code in which the word super appears.
==
Relational operator: equals
>
Relational operator: greater than
>=
Relational operator: greater than or equal to
How to declare variables with the same data type on the same line?
Separate them with commas. ex. int number, salary, hoursWorked; (end with semi-colon)
Stream
Sequence of bytes that flow into or out of a program
Method
Set of code that performs well-defined function
name [row] [col] = value
Set the value of an element
Graphical User Interface
Software that lets the user interact with a program or operating system through images and point-and-click mechanisms such as buttons and text fields
What are the local variables/parameters of a method stack known as?
Stack frames/activation records
set pen color
StdDraw.setPenColor();
pen size to 0.05
StdDraw.setPenRadius(0.05);
draw "text" at (x, y)
StdDraw.text(x, y, "text");
boolean for empty
StdIn.isEmpty()
When overriding a method that returns a value, what must be true about the data type?
The data type of the overridden method must be compatible with that of the superclass method.
Polymorphism
The idea that we can refer to objects of different but related types in the same way.
Scope
The part of a program in which a particular declaration is valid. Static methods can be placed in any order; variables, however, are only valid up until the next curly right brace.
javax.swing.*;
To create lightwieght components for a GUI.
False
True or False? If the left-operand is false, the && will go ahead and evaluate the right operand.
final
Variables marked ______ cannot be incremented or decremented.
similar to a traditional Java array, except that it can grow as necessary to accommodate new elements and also shrink.
Vector
Example of a vector that has an initial size of 25 and expands in increments of 5 elements when more than 25 elements are added to it:
Vector v = new Vector(25, 5);
How did we read in files? What is required?
We used a scanner, while loop, and iterator
What is counter controlled repetition?
When a loop is controlled by a counter such as x>3
Is this code below valid? public int foo() { float f = 123.45F; return (int) f; }
Yes.
short hand a = a * n
a *= n;
program statements
a series of sentences that tell a program what to do
instance
an object of a class.
expressions that represent a condition that a programmer believes to be true at a specific place in a program.
assertions
True False data type
boolean
declare a boolean variable, isAscending
boolean isAscending;
Never put a semi-colon before an open
brace{
Use a division assignment operator to make c=4 when c=8
c/=2
Chapter 1: Most patterns and principles address issues of
change in software
Alphabetic characters that can be stored as a numeric value?
char
string manipulations
charAt, toUpperCase, toLowerCase, replace, concat
Method signature
combo of → name of method + its parameters
if a method might throw multiple exceptions you declare them all in the throws clause separated by ______
commas
HAS-A refers to ...
composition.
software
computer programs
Conditional operator
condition?truepath:falsepath; (hours<12 ? "AM" : "PM";)
arithmetic expression
consists of operands and operators combined in a manner familiar from algebra
Interfaces do not have ...
constructors.
-64 bits Range: -big to big
double
For numeric data types what declaration will always be used?
double
casting operators
double a = 5.0; int b; b = (int) a;
declare and define a double, a, from command line argument
double a = Double.parseDouble(args[0]);
How could you define a real number named numero and initialize it to 867.5?
double numero = 867.5
Write code that will return a boolean statement of true since the radius is greater than 0
double radius = 1; System.out.println(radius > 0);
Your classes should generally have both an _______ method and a _____ method.
equals && toString
What is the goal of testing?
find errors, fix them, improve quality to discover problems assess quality of the evolving system
primitive data types
first category of Java variables such as numbers, characters, and Booleans
Traverse a list starting at the beginning.
for ( int inx = 0 ; inx < list.size() ; ++inx ) someMethod( list.get( inx ) );
Traverse an array starting at the end.
for ( int inx = array.length - 1 ; inx >= 0 ; --inx ) someMethod( array[inx] );
Traverse a list starting at the end.
for ( int inx = list.size() - 1 ; inx >= 0 ; --inx ) someMethod( list.get( inx ) );
Example of how to loop through a entire vector using the iterator class :
for (Iterator i = v.iterator(); i.hasNext(); ) { String name = (String) i.next(); System.out.println(name); }
I return something by definition.
getter
network
group of two or more computer systems linked together, the computers can read data and programs from central storage locations or send data to other computers
if / else
if (true) { } else { }
'this . aMethod()' is the same as ...
just invoking 'aMethod()'.
Keyboard integer input
keyboard.nextInt();
Where should the default statement be placed within a switch statement?
last
Number of comparisons in binary search
log(n)
I can have many arguments.
method
What is polymorphism commonly used for?
method arguments
Length method
name.length()
cast
operator that converts one type to another type
Decision Construct
permits program to make logical decisions and choose between alternate execution paths
displays the sequence of method calls that led to the statement that generated the exception.
printStackTrace()
Build a return method
public return
If a class implements the Runnable interface, what methods must the class contain?
run()
Class/Static Method
static keyword
Interface does not implement ...
the methods *of another interface* but just *extends* them.
Why do we use interfaces?
to formally define the way we can edit a class
#24 If a class declares that it implements an interface (class A implements B), must class A the methods of interface B? under all circumstances unless the class A is abstract
unless the class A is abstract
Array
~An ordered set of values of the same time stored in CONTIGUOUS blocks of memory ~non-primitive
Array subscripts
~Anything that evaluates to integer value ~Begin with 0 ~Cannot be negative ~Should not be referenced beyond bounds
Scanner Class
~Scans input from various sources and returns representations of primitive types
PrintWriter Methods
~print(arg) ~println(arg)
Integer value: 97
'a'
An 'abstract' class can have both ...
'abstract' and non-abstract methods.
matrix[0].length pixels[0].length
Example: get the number of columns
What is the end of file indicator for windows? and for UNIX/Linux/Mac OS X?
<Ctrl> z <Ctrl> d
What must every line of code not followed by curly braces end in?
";"
Integer value: 65
'A'
base class
A superclass.
Each source file must have a public class in it.
False. You don't have any public classes in your source files.
*
Multiplication
Two-Dimensional Array
Rows and columns.
b
bb
double
data type decimal value
Abstract methods and classes cannot be ...
declared abstract and final simultaneously
{}
denotes block
java.util.*;
To work with collections framework, event model, and date/time facilities.
Thread
- Process that can run at the same time with another process
method selector operator
., second highest precedence, left to right association
Method call/actual and formal for method name; Return value, no parameters
...
Class visibility revolves around whether code in one class can:
1) create an instance of another class 2) extend (or subclass) another class 3) access methods and variables of another class
Literal
A value represented as an integer, floating point, or character value that can be stored in a variable.
design test code
What do you use prep code for?
draw point at (x, y)
StdDraw.point(x, y);
Command-line Arguments
Stored in an array of String objects and are passed to the main method.
Define an array
Stores a fixed-size sequential collection of elements of the same type .
Value: group of characters -Capitalize the S, enclose value in " "
String
What non-numeric data type can have class operations preformed to it?
String
What is the name of the class the gains functionality from another class?
Subclass
Emergency exit
Sytem.exit(value);
Hash Code
Tells where in the array the data item should be stored.
Iterator
interface that provides a standard means of going through a list of elements in a defined sequence, which is a common task for many data structures.
What is the body of a class
is a set of members enclosed in curly braces
programming vs natural languages
size, rigidity, literalness
Statements
smallest executable unit in Java, each one ends in a semicolon.
Sentinel value
special input value signifying → end of input
Switch statement
switch (variable you're check against) { case label: code; break; default:
The size of a vector is:
the number of elements currently stored in it.
An object reference marked 'final' does not mean ...
the object itself immutable.
In a variable, what corresponds to the instantiated class?
the object type
What is the biggest limitation to using arrays?
they cant adjust in size to accommodate greater or fewer elements.
Chapter 1: Patterns don't give you code
they give you general solutions to design problems. You apply them to your specific application.
What is the definition of a nested if statement
this is when an if statement is inside of an if statement
When should camel case be used?
When defining the type of an input: int greatNumber, dbl, char etc. When naming a method or class: class( QuadraticFormula), Method(equationProcessor)
When you know how many times you want to repeat a loop
When do you choose for loops over while loops?
Before you implement the methods
When do you write test code?
Can we create the following abstract class: public abstract class Student { int x; int getX() { return x; } } even though there is no abstract method in the class?
Yes.
Is the following declaration ok? public class Ball implements Bounceable, Playable, Throwable { } // i.e., can a class implement multiple interfaces?
Yes.
application software
a program that performs tasks for a user -ex. word processing, playing a games
A subclass outside the package cannot access ...
a protected member by using a reference to superclass instance.
System.out.println("ab\\c"); prints out
ab\c
System.out.println("abc"); prints out
abc
The 'volatile' modifier applies only to ...
instance variables.
How do you test a diagram as to whether it is structured?
apply the rules backwards to reduce it to the simplest activity diagram.
Math class
pow, square root: Math.pow(); Math.sqrt();
instance field
public double r; ( any field declared without the static modifier is an instance field)
Write a class method
public static double radiansToDegrees (double radians) { return radians * 180 / PI; }
main loop
public static void main (String[] args)
Life Cycle - Sleeping
-Thread has issued a sleep method call...-Will sleep AT LEAST as long as the time requested (may be longer due to waiting to become Active)...-Once the sleep method is over, thread enters the Runnable state
float
4 bytes, stores less precise floating-point numbers
What symbols are used to make comments in Java? (Both single and block comments)
// and /* */
Thread of creation
1) Create class that extends Thread 2) Override the run() method -Method that the thread executes 3) Create an object of this class 4) Call the start() method -start() invokes the run() method -You choose when the thread starts -Doesn't start when object is created
Encapsulation code has two features:
1) Instance variables are kept protected (usually with the private modifier) 2) Getter and setter methods provide access to instance variables
double
8 bytes, stores floating-point numbers
In Java, every program statement ends with what?
; (a semicolon)
Assignment/Declaration
<type> <name> = <expression> Declares a variable (names it), and assigns it a value.
Logical ops: !expr __ & __ __&&__ __^__ __ | __ __||__
= NOT (evaluates from RIGHT to LEFT) = logical AND' = conditional AND = logical exclusive OR (either not both) = logical inclusive OR = conditional OR
Variable Declarations
A statement that typically specifies two things about a variable: The variable's name and the variable's data type. Must be done before it can be used in a program.
What is method overriding?
A subclass method has the same method signature as the superclass method.
derived class
A subclass.
Control structure
A syntatic structure that controls other statements. Ex. A for loop.
#32 True or false? An inner class must be defined with the opening and closing braces of a class, but outside any method -- just like data members.
False. An inner class can be defined inside a method, or even inside a parameter to an method! (with anonymous inner classes)
#101 True or false? Class defined two methods with the same name as long as the return types are different.
False. An overloaded method can change the return type but return type alone is not enough - it also must schange the argument list.
static
means the method is accessible and useable even though no methods of the class exist
Input Stream
Flows data from some external device into a program
reference variables
Four types of things can be tested with the equality operators: numbers, characters, booleans, and _________ __________
name[0].length
Get the number of columns
name.length
Get the number of rows
for
Gets the computer to repeat some statements over and over again (for instance, a certain number of times).
Command invoking the INTERPRETER to run a Java program from the command line. - vs. invoking the COMPILER
Interpreter → java command Compiler → JAVAC command
....
Standard Java arrays can be declared with square brackets after the type or variable name. Example: int[] myArray or int my Array[]
draw a filled rectangle centered at (x, y) width = w height = h
StdDraw.filledRectangle(x, y, w, h);
draw line from (x, y) to (q, s)
StdDraw.line(x, y, q, s);
Example of how to retrieve the last string added to the vector:
String s = (String)v.lastElement();
Variable names
Strings of any length of letters, digits, underscores, and dollar signs that begin with a a letter, underscore, or dollar sign.
Which declaration for SubClass indicates its superclass is SuperClass?
SubClass extends SuperClass
A class being inherited is referred to by what name(s)?
Super Class or Base Class
switch
Tells the computer to follow one of many possible paths of execution (one of many possible cases), depending on the value of an expression.
if
Tests to see whether a condition is true. If it's true, the computer executes certain statements; otherwise, the computer executes other statements.
Evaluation
The process of obtaining the value of an expression.
restriction for abstract class method
There are no any restriction for abstract class method modifier that means we can use any modifiers.
return, argument
This can be implicitly promoted.
A class that contains one or more abstract method(s)
must be declared abstract
T or F: The name of a local variable can be reused outside of the method in which it is declared ?
True
True
True or False? For interfaces, an object passes the instanceof test if any of its superclasses implement the interface on the right side of the instanceof operator.
True or False: An interface can inherit zero or more interfaces. An interface cannot inherit a class.
True.
Method Overloading
Using methods with the same name but different # and types of arguments
Float
Variable type of 32 bits and a range of [-3.4E38,3.4E38]
Double
Variable type of 64 bits and a range of [-1.7E308, 1.7E308]
Short
Variable type with a size of 16 bits and a range [-32768,32767 ]
Constant
Variable whose value cannot be changed once initialized (final)
substring
newStringName = stringName.substring(startPosition,stopPosition); returns defined part of string
String input
next() nextLine()
byte input
nextByte()
double input
nextDouble()
float input
nextFloat()
what is the syntax for casting an object?
place the class name in front of its parenthesis
Prints a formatted string
printf
Prints x on the same line, then moves the cursor to the next line
println(x)
Post Condition?
What will be true after a method is called
27
What will print (or ERROR)?
ERROR
What will print (or ERROR)?
The animal is a elephant
What will print (or ERROR)?
What is sentinel controlled repetition?
When a loop is controlled by a sentinel value such as s!=3
Void
When a method does not return a value.
Unicode
When comparing characters, Java uses the ________ value of the character as the numerical value
Encapsulation
When each object protects its own information.
When can you not use a (while) statement instead of a (for) statement? How does it differ?
When the (while) statement has an increment after a continue statement, it is different than a (for) statement. they differ in execution.
Mixing types
When you use multiple data types, Java will convert the simpler forms to the more complex ones. Example: 2 * 3.6 will be evaluated as 2.0 * 3.6, where both objects are doubles.
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 can be accessed.
Can an Interface extend another interface? Ex: public interface Bounceable extends Movable { }
Yes. But an interface cannot extend (or) implement another class. For ex, the following is NOT OK: public class Foo { } public interface Bounceable extends Foo { } // wrong
More than One Parameter
You can send more than one thing to a method: first argument is passed to the first parameter, second argument to the second parameter, and so on.
What escape sequence makes the tab character?
\t
System
a class that holds objects/methods to perform system-level operations, like output
Interfaces cannot extend ...
a class, or implement a class or interface.
access specifier
defines the circumstances under which a class can be accessed and the other classes that have the right to use a class
What should methods do?
determine how the class will define its behaviors solve a problem
Declare and define integer a from double, b.
int a = (int) b;
declare a as an int
int a;
When defining a method, the _____ parameter is a name used for the calling object.
"this."
remainder or modulus operator
%, fourth highest precedence, left to right association
Classes can also be modified with ...
'final', 'abstract' and 'strictfp'.
grouping operator
( ), highest precedence
*ABSTRACT CLASSES and INTERFACES*
*ABSTRACT CLASSES and INTERFACES*
;
- Ends a statement - Acts like a period
Byte Code
- Java compiles code into ____ first - Unique to Java
.Java
- Java file created by user
subtraction operator
-, fifth highest precedence, left to right association
unary minus operator
-, third highest precedence
Anatomy of a Java Statement
...
Defining Parameters
...
How to use sub-string function?
...
Java Environment
...
Java reserved keywords
...
UML Notation
...
Work with ArrayList Objects and Their Methods
...
Operate on the digits in an integer, from right to left.
// prints 0 8 6 4 2 for ( int num = 24680 ; num > 0 ; num /= 10 ) System.out.print( num % 10 + " " );
*IS-A* is equivalent to following expressions:
1) "inherits from" 2) "is a subtype of"
Reasons to use "double"
1023 digits after the decimal point
Moden can transfer speed up to ______
56,000 bps (bits per second).
What is the ASCII value of 'A'?
65
byte (signed) short (signed) int (signed) long (signed) float double char boolean
8 bits > -2^7 to 2^7 -1 16 bits > -2^15 to 2^15 -1 32 bits > -2^31 to 2^31 -1 64 bits > -2^63 to 2^63 -1
static nested class
A *static nested class* still has access to private members of its enclosing class, but only if they're also static. That is, it acts like a static method of the enclosing class. To interact with an instance of the enclosing class, it must be passed a reference to that instance—just as with any other class. A technique you might come across is to declare a Builder class as a static nested class of an enclosing Widget class. The Builder class can be instantiated once and used as a factory. Since it has access to private members of the Widget, it can also initialize private members or call private methods to set the state of the Widget instance before returning it to the caller.
Attribute
A value an object stores internally.
null
A value of no value
Private instance variables can be accessed from outside their class through ______ methods and changed with _________ methods
Accessor methods && Mutator methods
+
Addition
Machine Language
Also called Machine code is the most basic set of instructions a computer can execute -a low-level programming language
Blocks
Also known as compound statement, are marked by delimiting with braces { }.
Casting Float Types to Integral Types
Always requires a cast. Will result in the loss of the fractional part of the number.
What is the difference between black box and white box testing?
Black Box - test cases are developed without regard to internal workings - test as if we don't know the working of the program White Box - exercises internal structure and implementation of method - test as if we do know the working of the program
||
Boolean operator meaning only one side has to be true. A Short circuiting logical operator.
Which statement is true? (Choose all that apply.) A. Cohesion is the OO principle most closely associated with hiding implementation details B. Cohesion is the OO principle most closely associated with making sure that classes know about other classes only through their APIs C. Cohesion is the OO principle most closely associated with making sure that a class is designed with a single well-focused purpose D. Cohesion is the OO principle most closely associated with allowing a single object to be seen as having many types
C is correct. A refers to Encapsulation B refers to Coupling D refers to Polymorphism
string.length
Calculates the length of a string.
What is needed to convert an object back to a more detailed object in its inheritance chain?
Casting
Conversion
Changing one type of primitive data to another.
A software program that translates source code (e.g., Java source code) into a machine language program.
Compiler
ArrayList<Type>()
Constructor: Creates an empty ArrayList with an initial capacity of 10
ArrayList<Type>(int n)
Constructor: Initial capacity to hold n objects
enum
Creates a newly defined type — a group of values that a variable can have.
extends
Creates a subclass — a class that reuses functionality from a previously defined class.
var
Creates a variable and optionally gives it an initial value. Cannot start with a number.
new
Creates an object from an existing class.
Declaration
Creating a variable of the type that you want to use, reserves a memory location for that variable.
Instantiating
Creating an object
Encapsulation?
Data and actions combined into a class whose implementation details are hidden
type[] [] name
Declare a 2D array
alert
Displays a message with an ok button
Linear/Sequencial Search
Elements are searched one at a time in the order which they are numbered.
matrix.length pixels.length
Example of getting the number of rows
matrix[3] [2] = 8; pixels[r] [c] = aPixel;
Example of setting the value of elements
switch selector value
Has to be a constant value (usually a literal) that is compatible with the argument type. The statements within the case are executed if it is logically equivalent to the argument '=='.
What must variable names have/not have?
Have: Starts with a lower case letter. Not Have: after initial letter cannot have a symbol other than the underscore (no spaces).
Software
Incudes programs and the data those programs use
Static keyword
Indicates a class variable vs. an instance variable
void
Indicates that a method doesn't return a value.
default
Introduces a path of execution to take when no case is a match in a switch statement.
interface
Introduces an interface, which is like a class, but less specific. (Interfaces are used in place of the confusing multiple-inheritance feature that's in C++.)
case
Introduces one of several possible paths of execution in a switch statement.
catch
Introduces statements that are executed when something interrupts the flow of execution in a try clause.
Inclusion Polymorphism
It refers to the ability an object to invoke a method that it inherits; public class TestRatio{} Ratio x = new Ration(); x.hashCode(); <--- inheritated
Overriding rules: Can the access level be more OR less restrictive than that of the overridden method?
It should be same or less restrictive, but NOT MORE restrictive...
Java Virtual Machine
JVM - Program needed to run Java byte code - Comes with Mac - Acts like a computer
Prompt the user
Java: System.out.println
Read a double from the Scanner object and store it in a double
Java: double varX= input.nextDouble();
Import the Scanner Class
Java: import java.util.Scanner;//at top of the file
TreeSet
Keeps the elements sorted and prevents duplicates.
arc sin x
Math.asin(x);
Round to smallest integer not less than number input(round number up)?
Math.ceil(#) Ex: ceil(9.2)=10
Cosine?
Math.cos(#)
cos x
Math.cos(x);
How do you put e to a power? Ex: e^x
Math.exp(x)
Round to the largest integer not greater than number input?(round down)
Math.floor(#)
find the max
Math.max (x, y);
find the min
Math.min (x, y);
-Segments of code that perform some action -Always followed by parenthesis EX: System.out.println("abc") <--- print is the ?
Methods
#110 Each source file must have a public class in it.
NO. You don't have to have any public classes in your source files.
#121 Can you have a final abstract class?
NO. final and abstarct classes are opposities: a final class can NOT be subclassed, while an abstract class MUST be subclassed... So final abstract class make not sense
Reasons to use "long"
Numbers greater then ±2 billion
4 Java Data Types?
Numeric, String, Character, Boolean.
'if' statement
Of the form 'if( [logical_expression] ) { statements; }'. where the statements in the *body* are executed if the logical expression argument in the header parentheses evaluates to true. Note that the entire structure is considered a single statement.
static
One copy and everyone can see it
Increment and Decrement Unary Operators
Operators available in postfix and prefix forms. The *postfix version* returns the *old value* of the variable before applying the addition or subtraction of 1. Note that these operators *do change* the variable that the y operate on, as well as returning values for the expression to use. E.g. 'int a = myInt++;' where a will be assigned the old value of the variable and the variable will also be incremented.
A _____________ is like a blank in a method definition...
Parameter
Default Class Constructor
Provided by java w/o arguments and invoked when there is no constructor
Initializer List
Provides the initial values for the elements within an array.
Use of the word "this"
Refers to the object itself
Comparing Strings
Remember that in Java a character string is a String object The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order The equals method returns a boolean result if (name1.equals(name2)) System.out.println ("Same name"); We cannot use the relational operators to compare strings The String class contains the compareTo method for determining if one string comes before another A call to name1.compareTo(name2) -returns zero if name1 and name2 are equal (contain the same characters) -returns a negative value if name1 is lexically before name2 -returns a positive value if name1 is lexically after name2
while
Repeats some statements over and over again (as long as a condition is still true).
All objects can be represented by what class
String
When you type something wrong and java doesn't compile (LANGUAGE)
Syntax error
Print statement
System.out.println("");
^
The ___ operator, called the "logical XOR", returns true if exactly one operand is true
instanceof
The ____________ operator is for reference variables only and checks whether the object is of a particular type.
difference between absttract class and interface methods
The default access specifier of abstract class methods are default. There default access specifier of interface method are public. The interface body can contain abstract methods, default methods, and static methods. All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.
if...else statement
The if statement can be extended to include an alternative code block to be executed if the header argument evaluates to false. For example 'if(isFlying) { flapWings(); } else { closeWings(); }'.
Edit, Compile, Run
The three steps to creating a program are ___ (e), ____ (c), and ____ (r).
java.io.*;
To utilize data streams.
java.lang.*;
To utilize the core java classes and interfaces.
double
Used to declare and initialize a fraction interager. Ex: double canVolume = 0.335;
byte
Used to define a primitive variable as an integer with 1 byte of storage. Also a corresponding wrapper class.
break
Used to leave a loop early
Are there standard Java arrays built into the Java language?
Yeah, hell Yeah lol there standard Java arrays are built into the Java language.
'
\'
integrated development environment
a set of software tools that allows you to edit, compile, run and debug programs within one user interface
jGRASP
a source code editor
terminal I/O user interface
a user interface that allows the user to enter input form a keyboarda and view output as text in a window
compile-time error
a violation of the programming language rules that is detected by the compiler; also known as syntax errors
panel
a window object whose purpose is to contain other window objects
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 OOPs program, it is accessible with in the object and which in turn assures the security of the code.
short hand a = a + 1;
a++;
short hand a = a - 1;
a--;
String comparing a to b
a.compareTo("b");
if your method has been declared with a throws clause, don't forget to:
actually throw the exception in the body of your method using the throw statement.
Write an expression that returns the position of the 1st occurrence of the String "Avenue" in address (a String).
address.indexOf("Avenue")
'public' members can be accessed by ...
all other classes, even in other packages.
numeric data types
another name for primitive data types; most commonly int and double
Static variables are not tied to ...
any particular instance of a class.
\\
backslash; causes a backslash to be printed
Polymorphism
describes the way an object or variable my be treated in different contexts as though it was a different type. For example: inheritance allowes an argument of type B to be passed to a parameter of type A if B extends A. It is an object oriented programming feature that allow types to be treated as their parents or extending object.
class definition
describes what attributes its objects will have and what those objects will be able to do
logic
determines the exact order of instructions needed to produce the desired results
What are static methods?
don't need to instantiate an object of the class to invoke the method.
comments
explanations for human readers of your code; not processed by the compiler and is isolated after // for short ones and /* and */ for long ones. /** explains the purpose of a program
how do you define a constant?
final double NUMBER1=4.5; or final double PI=3.14;
optional 3rd block of code in a try/catch that executes NO MATTER WHAT:
finally{ }
Traverse an array starting at the beginning.
for ( int inx = 0 ; inx < array.length ; ++inx ) someMethod( array[inx] );
for loop (use i and N)
for (int i = 0; i < N; i++) { }
/t
horizontal tab; causes the curson to skip over to the next tab stop
Hashable class
implements Dictionary, an abstract class that defines a data structure for mapping keys to values. This is useful when you want to access data through a particular key rather than an integer index.
declare and define command line integer argument, a
int a = Integer.parseInt (args[0]);
statements
lines of code in java
Constants declaration
public static final NAME = value;
Write a class field
public static final double PI=3.14159
Standard Starting, to start code block?
public static void main(String[] args) { //code goes here }
access modifier
public, protected,private
/r
return; causes the cursor to go to the beginning of the current line, not the next line
In as 'IS-A' relationship how do the sub and super classes work together?
the *subclass object 'IS-A'* superclass object.
If some code in your method's body might throw an exception, add the ______ keyword after the closing parenthesis of the method followed by the name or names of the exception
thows
For subclasses outside the package, the protected member can be access only ...
through inheritance.
syntax errors
when a syntax rule is violated
logic errors
when the computer is unable to express an answer accruately
When are the &, |, and ^ operators also bitwise operators?
when they're applied to integral operands
When is the BitSet class useful?
when you need to keep up with a set of Boolean values; you simply assign a bit to each value and set or clear it as appropriate.
Downcasting is when ...
you can assign a reference variable that refers to a supertype object to a reference variable of the subtype but you must make an explicit cast to do this, and the result is that you can access the subtype's members with this new reference variable.
Method overloading
you can define methods w.the SAME NAME in a class IF: • Enough difference in their parameter profiles.
What must every method and class have an open and closed of?
{ } (braces, or curly brackets)
Method With Parameters
A method can use/accept parameters, where the parameter list specifies the type and name of each parameter If a method takes a parameter, the caller must pass argument (the value passed to the method) of the compatible type: Dog d = new Dog(); d.bark(3);
What is a requirements document?
A precise specification of what the software should do.
Class method vs Instance method
An instance method is declared without the static modifier and is invoked using the name of the object to which it is bound.
What is the difference between design state and the implementation stage in the development of software?
Design Stage : identifies the components(classes) to be used and the relationships among them. Implementation Stage: is where the computer program code is actually written.
Quick Check: Are the following assignments valid?
Double value = 15.75; Yes, the double literal is autoboxed into a Double object. Character ch = new Character('T'); char myChar = ch; Yes, the char in the object is unboxed before the assignment. Integer i = new Integer(5); int j = i + 3; Yes, the int value in the object is unboxed before arithmetic computation.
Classes Revisited
Each class declares -Instance variables: descriptive characteristics or states of the object -Methods: behaviors of the object, i.e., what it can do
Quick Check: Nested Loops
How many times will the string "Here" be printed?
What is an abstract data type?
I a specification of the type's operations: what an instance of that type can do.
Overloading Polymorphism : ad-hoc
It means integer addition when used in form 22 + 33; it means floating point addition when used in the form 2.2 + 3.3; and it means string concatenation when used in the form + ", esq."
In Java, data conversions can occur in three ways: -assignment conversion -promotion -casting
Numeric data types: double > float > long > int > short > byte 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)
Coercion Polymorphism : ad-hoc
Occurs when a value of one type is implicitly converted to a value of another type when the context requires that other type. ie: 22 + 3.3 it interprets the plus operator as a floating point addition, requiring both operands to be either type float or type double. So it "coerces" the 22 into being 22.0 and then performs the operation
Parametric Polymorphism
Occurs with generic methods, where an actual type is substituted in for a type parameter. static <T> void print(T[] a) { for(T t : a) { System.out.printf("%s", t); } System.out.println(); }
Promotion
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
Nested Loops
Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop while ( condition1 ) { while ( condition2 ) statement; } For each iteration of the outer loop, the inner loop iterates completely
Suppose that, when you run the following program, you enter input 2 3 6 from the console. What is the output? public class Test { public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); double x = input.nextDouble(); double y = input.nextDouble(); double z = input.nextDouble(); System.out.println((x < y && y < z) ? "sorted" : "not sorted");
Sorted
Infinite Loops
The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program (Control+C) This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally
what is an enum type.
The enum type is a type defined with the enum keyword that list by name each possible value for the type.
The switch Statement
The general syntax of a switch statement is: The type of a switch expression must be char, byte, short and int (Question 4) You cannot use a switch with a boolean or a floating point value The value of each case must be a constant; it cannot be a variable or other expression You cannot perform relational checks (<, >) with a switch statement A switch statement can have an optional default case at the end The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch
Writing Classes
The programs we've written in previous examples have used classes defined in the Java standard class library Now we will begin to design programs that rely on classes that we write ourselves The class that contains the main method is just the starting point of a program True object-oriented programming is based on defining classes that represent objects with well-defined characteristics and functionality
Comparing Object References
To see if two object references are the same (which means they refer to the same object on the heap), use the equality operator (==)
If 1 of the operands of an || is false then the expression is _____?
true -- this is also known as the short-circuit OR operator
"Given an interface, how would you make your class behave like the interface."
"//Where Class A uses interface B public class A implements B { // Must define methods declared in B }"
"What are the four types of nested classes?"
"1. static nested class 2. inner (non-static) nested class 3. local class 4. anonymous class A static nested class is just like a normal Java class. If it is public, it can be accessed or used to create objects just like any other class. A non-static inner class requires an object of the containing class. A local class is declared within and scoped to a block. An anonymous class is defined in place after the new operator without assigning any name to it. It's a way to pass functions as parameters."
"What is an abstract class?"
"An abstract class is a class declared with the abstract keyword. Although references to such a class may be used, the class may not be directly instantiated. Abstract classes may define methods or just declare them and may contain variables."
"What are annotations and how are they useful?"
"Annotations are pieces of metadata that contain information used by the compiler, associated with an object at run time or compile time. For example, @Deprecated, @Override and @SuppressWarnings."
"Explain encapsulation."
"Encapsulation means that objects keep their state information private. Rather than directly manipulating an object's data, other objects send requests to the object, in the form of messages, some of which the object may respond to by altering its internal state."
"What are some advantages of all classes deriving from a common class like Object?"
"Every class inherits all the methods defined in Object. These include methods to get the class name, getClass() and various methods related to synchronization like, wait() or notify() and methods useful for storing an object in a collection like hashCode() or equals()."
"What is the difference between an abstract class and an interface?"
"Interfaces don't define methods. Also, classes cannot inherit from more than one class, abstract or not, while a class may implement many interfaces. Both can have constant declarations but in an interface they are implicitly public static and final."
If the ArrayList object capacity is exceeded what will it automatically do?
"It will automaticallly resize" An ArrayList object will automatically resize if its capacity is exceeded.
What will automatically happen if you add elements at any index in the ArrayList object?
"It will automatically move the other elements" [Orginal below] An ArrayList object can have elements added at any index in the array and will automatically move the other elements.
"Why would you declare a class final?"
"Making a class final adds some security and consistency to the class behaviour. E.g. by making the String class final, you cannot override its length method. The compiler may optimize the code and make it run faster when a class is declared final."
"When should a data field be declared final?"
"Objects with fields declared final can be passed from one thread to another without synchronization. It contributes to robust software design and is slightly faster. Unless there's a good reason why not, all fields should be declared final by default."
"Explain polymorphism."
"This ability of different but related objects to respond, each in its own way, to identical messages is called polymorphism."
What try and catch effectively mean is:What try and catch effectively mean is:
"Try this bit of code that might cause an exception.If it executes okay, go on with the program. If the code doesn't execute, catch the exception and deal with it."
"How do you derive a new class from a class?"
"Where B is a subclass of A, public class B extends A { // class contents }"
"Where would you use the keyword extends and implements?"
"extends is the keyword used to declare that this class is a subclass of the class that follows the extends keyword. Implements is a keyword that designates this class as an implementer of the specified interface."
"What are some methods defined in the Object class and how are they useful?"
"getClass() returns the class object. hashCode() and equals() are useful for comparison and in collections. notify(), notifyAll() and wait() are used in thread synchronization. toString() is used to get a string representation of the object. clone() is used to get a deep copy of the object. finalize() is useful for clean up just before garbage collection."
"Which operator checks the type of an object?"
"instanceof"
Polymorphism means ...
"many forms", in other words subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.
Methods and instance (non-local) variables are known as ...
"members".
and
&&
What are LOGICAL operators of Java? What does each one mean?
&& which is the Conditional AND operator-Statement is only true when both conditions are true (true && true) | |-the Conditional OR operator-Statement is only true as long as one of the statements are true(true || false) (true || true) (false || true) & which is the Boolean logical AND operator-... | which is the boolean logical inclusive OR operator-... ^- the boolean logical exclusive operator OR -Statement is only true when one condition is false and one is true (true ^ false) (false ^ true) ! which is the logical NOT operator- does the same function as != except this operator comes before the statement (!(statement))
'abstract' methods cannot be ...
'private' or 'final'.
Interface methods are by default ...
'public' and 'abstract' - explicit declaration of these modifiers is optional.
order of precedence
(-), *, / , %, +, -
Method Selector
(.) - Selects the method
Assignment Operator
(=) - Assigns right side to left side Ex: celsius = (fahrenheit + 32)
Actual parameter
(i.e. Argument) • the variables or data to substitute formal parameters when invoking a method
What operator multiplies two numbers?
*
*CASTING*
*CASTING*
System.out
- Computer sends message out to screen
Integer
- Name for a whole number Ex: 4, 10
Predecrement
--x "Decrement, then give me x"
Mixed Mode Conversion
-Convert to LARGEST DATA TYPE -does not allow from more accurate to less accurate
Runnable vs Thread
-Extend Thread...-Implement Runnable. Implementing Runnable allows you to extend another thread
Life Cycle - Wait
-Thread can be put into this state by calling wait()...-Will stay in a pool of waiting threads until a notify or notifyAll method is called by another thread
Rules to defining a Java class
-a Java identifier cannot begin with a digit -a Java identifier can only contain letters, digits, underscores, or dollar signs -a Java identifier cannot be a reserved keyword -a Java identifier cannot be one of the following values: true, false, or null
encapsulation
-is the enclosure of data and methods within an object, this allows you to treat all of an objects methods and data as a single entity -also refers to the concealment of an object's data and methods from an outside source
division operator
/, fourth highest precedence, left to right association
Member access comes in two forms:
1) Code in one class can access a member of another class. 2) A subclass can inherit a member of its superclass.
Thread creation via implementing Runnable
1) Create a class that implements Runnable -Runnable only declares the run() method sig 2) Define the run() method 3) Create an object of this class 4) Pass this object to the Thread constructor 5) Call the start() method of the Thread object
Three ways to spot a non-abstract method:
1) the method is not marked abstract. 2) the method has curly braces. 3) the method has code between the curly braces.
int
4 bytes, stores integer values
Make g conditional upon some statement
?:g
Escape Sequences
A character preceded by a backslash is an escape sequence ~ \t = tab ~ \b = backspace ~ \n = new line ~ \r = carriage return
subclass
A class below another class in a class hierarchy. A class that inherits another class.
interface
A class with abstract methods. An interface cannot be inherited, but it can be implemented by any number of classes.
Interface
A collection of constants and abstract methods
ARPANET
A computer network developed by the Advanced Research Project Agency (now the Defense Advance Research Projects Agency) in the 1960s and 1970s as a means of communication between research laboratories and universities. ARPANET was the predecessor to the Internet.
Length
A constant in all Java arrays that keeps an array at its declared size.
int
A data type of integers (whole numbers).
boolean
A data type of logical values (true, false).
char
A data type of single characters ('a', 'b', '?').
boolean
A data type that represents a true or false value.
Interface Comparable
A java.lang interface with the compareTo() method that can be implemented in classes to provide a means for an object to be compared to another object of the same type.
Truth Table
A means of listing all of the possible values of a Boolean expression ex: (based off of the code from page 246) Look up for more detail: Ex:
Variable
A memory location with a name and a type that stores a value. These items are "uninitialized" until they have been given a value.
What must come after a declared class?
A pair of brackets that contain the method(s) between them
What do you attach to a method if it requires more information?
A parameter that represents additional information: Method: public static double _maximum_(Parameters(double x, double y, double z))
Relative Path
A path that is not anchored to the root of a drive. Its resolution depends upon the current path. Example ../usr/bin.
Input Assertion
A precondition for a loop ex: int d; int j = 10; do{ d++ while }(int j<=20);
The bits representing the value
A primitive variable value contains what?
Error
A problem that usually cannot be fixed
Fourth-generation language
A report generator is a type of:
Nested "if" Statement
A selection statement used within another selection statements. ex: ex: if(j<=0) { System.out.println("Example"); if(m<10) System.out.println("Example"); else { System.out.println("Example"); } else { System.out.println("Example"); } } else { System.out.println("Example"); }
this
A self-reference — refers to the object in which the word this appears.
Complete Code Coverage
A set of test in which every line in a program is executed at least once. ex: { int a, b; a=2; b=5; if (a<0) && (b>2) { System.out.println("Example"); } else { System.out.println("Example"); } } this insures quality assurance
Arithmetic Overflow
A situation that arises when the computer's memory cannot represent the number resulting from an arithmetic operation. ex: when an error occurs when trying to do an arithmetic problem when the final result number is too large for the primitive storage type to store. Also, Data too large for the data type chosen
Unicode
A standardized 16-bit character set that represents the character sets of most major languages in the world. The letters entered have to be above 192.
Machine Language
A system of instructions & data executed directly by a computer's CPU.
Hashing
A technique used to efficiently store and retrieve data in an array.
Class
A template in accordance to which objects are created. Includes a data specification and functions operating on these data and possibly on the data belonging to other class instances.
What is a temporary association?
A temporary association is also known as a dependency.Typically, a temporary association will be an object used as a local variable, return value, or method parameter. A temporary association is the weakest form of association.
Boundary Condition
A value at which two equivalence classes meet. ex: (exsampleClassA >= 0 || > exsampleClassB)
Array Element
A value stored in an array.
What is a constant?
A variable that has a set value at compile time that can never be changed. A java constant is made by adding the final keyword to a class variable, e.g. public static final
What are do loops, while loops, etc.
A while loop is a control structure that allows you to repeat a task a certain number of times. -the loop might not ever run. a do...while loop will run at least once before checking the while. A for loop is useful when you know how many times a task is to be repeated.
What can contain unimplemented methods and instance variables and cannot be instantiated?
Abstract Class
Aggregation
Aggregation is a special case of association. A directional association between objects. When an object 'has-a' another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a "Has-a" relationship.
Statements that describe how a problem is solved in terms of the actions to be executed, & specifies the order in which these actions should be executed.
Algorithm - Helps plan a program before writing code
Capital Letter
All java file names must have this at the beginning.
Defining a variable
Allocates memory for storage
...
An ArrayList object can have its internal capacity adjusted manually to improve efficiency.
What is an aggregation association?
An aggregation association is a relationship that represents one object being part of another object. An aggregation association represents a "part of" the whole relationship. In this relationship, even though one is part of the other, each object can maintain its own meaning independently.
modular application
An application that uses components that are separately written and maintained.
JRE
An environment used to run Java Applications. Contains basic client and server JVM, core classes and supporting files.
ClassCastException
An exception thrown when an object variable is cast with an incompatible class.
Reference Variable
An identifier that represents a location in memory which itself has a *reference* to another location in memory where an object resides. Multiple reference variables can reference the same object and so affect its reference count. An object with no references can be garbage collected.
difference between inner class and subclass
An inner class is a class that is created inside of another class. A subclass is a class that extends another class. A subclass has an is a relationship with its parent. It inherits its parents members such as instance variables and methods, and can override some of those methods. A nested class, for the most part, is just that—a class declared in the definition of an enclosing class. It does not inherit anything from the enclosing class, and an instance of the nested class cannot be assigned to a variable reference to the enclosing class.
What is an interface?
An interface is a special form of an abstract class which does not implement any methods. An interface is an empty shell, there are only the signatres of the methods. It can't do anything.
Mutator methods exhibit which of the following types of side effect? A) Modification of the implicit parameter. B) Modification of an explicit parameter. C) Production of printed output. D) Acceptance of text input.
Ans: A Section Ref: 8.4
Which of the following types of side effects potentially violates the rule of minimizing the coupling of classes? A) Standard output. B) Modification of implicit parameters. C) Modification of explicit parameters. D) Modification of both implicit and explicit parameters.
Ans: A Section Ref: 8.4
Which of the following statements describes an assertion? A) A logical condition in a program that you believe to be true. B) A guarantee that the object is in a certain state after the method call is completed. C) A requirement that the caller of a method must meet. D) A set of criteria defined by the caller of a method.
Ans: A Section Ref: 8.5
Which of the following statements about abstract methods is true? A) An abstract method has a name, parameters, and a return type, but no code in the body of the method. B) An abstract method has parameters, a return type, and code in its body, but has no defined name. C) An abstract method has a name, a return type, and code in its body, but has no parameters. D) An abstract method has only a name and a return type, but no parameters or code in its body.
Ans: A Section Ref: 9.1
Which of the following is an event source? A) A JButton object. B) An event listener. C) An inner class. D) An event adapter.
Ans: A Section Ref: 9.7
What is the purpose of this algorithm? double total = 0; for (double element : data) { total = total + element; } A) Computing the sum. B) Finding a value. C) Locating an element. D) Counting matches.
Ans: A Section Ref: Section 7.6 Common Array Algorithms
What is the purpose of this algorithm? for (BankAccount a : accounts) { if (a.getAccountNumber() == accountNumber) return a; } return null; A) Finding a value. B) Counting matches. C) Computing the sum. D) Inserting an element.
Ans: A Section Ref: Section 7.6 Common Array Algorithms
What is the purpose of this algorithm? int m = 0; for (BankAccount a : accounts) { if (a.getBalance() >= atLeast) m++; } A) Counting matches. B) Finding a value. C) Computing the sum. D) Locating an element.
Ans: A Section Ref: Section 7.6 Common Array Algorithms
Consider the following code snippet: public interface Sizable { int LARGE_CHANGE = 100; int SMALL_CHANGE = 20; void changeSize(); } Which of the following statements is true? A) LARGE_CHANGE and SMALL_CHANGE are automatically public static final. B) LARGE_CHANGE and SMALL_CHANGE are instance variables C) LARGE_CHANGE and SMALL_CHANGE must be defined with the keywords private static final. D) LARGE_CHANGE and SMALL_CHANGE must be defined with the keywords public static final.
Ans: A Section Ref: Special Topic 9.1
A class that represents the most general entity in an inheritance hierarchy is called a/an ____. A) Default class. B) Superclass. C) Subclass. D) Inheritance class.
Ans: B Section Ref: 10.1
To override a superclass method in a subclass, the subclass method ____. A) Must use a different method name. B) Must use the same method name and the same parameter types. C) Must use a different method name and the same parameter types. D) Must use a different method name and different parameter types.
Ans: B Section Ref: 10.3
In Java, every class declared without an extends clause automatically extends which class? A) this B) Object C) super D) root
Ans: B Section Ref: 10.7
General Java variable naming conventions would suggest that a variable named NICKEL_VALUE would most probably be declared using which of the following combinations of modifiers? A) public void final B) public static final double C) private static double D) private static
Ans: B Section Ref: 8.2
Why can't Java methods change parameters of primitive type? A) Java methods can have no actual impact on parameters of any type. B) Parameters of primitive type are considered by Java methods to be local variables. C) Parameters of primitive type are immutable. D) Java methods cannot accept parameters of primitive type.
Ans: B Section Ref: Quality Tip 8.3
Fill in the if condition that will only access the array when the index variable i is within the legal bounds. if (____________________) data[i] = value; A) 0 <= i < data.length() B) 0 <= i && i < data.length C) 0 <= i < data.length D) 0 <= i && i < data.length()
Ans: B Section Ref: Section 7.1 Arrays
Which of the following is true regarding subclasses? A) A subclass inherits methods from its superclass but not instance variables. B) A subclass inherits instance variables from its superclass but not methods. C) A subclass inherits methods and instance variables from its superclass. D) A subclass does not inherit methods or instance variables from its superclass.
Ans: C Section Ref: 10.2
Consider the following code snippet: public class Coin { . . . public boolean equals(Coin otherCoin) { . . . } . . . } What is wrong with this code? A) A class cannot override the equals() method of the Object class. B) The equals method must be declared as private. C) A class cannot change the parameters of a superclass method when overriding it. D) There is nothing wrong with this code.
Ans: C Section Ref: 10.7.2
Which of the following statements describes a precondition? A) A logical condition in a program that you believe to be true. B) A guarantee that the object is in a certain state after the method call is completed. C) A requirement that the caller of a method must meet. D) A set of criteria defined by the caller of a method.
Ans: C Section Ref: 8.5
Under which of the following conditions can you have local variables with identical names? A) If their scopes are nested. B) If they are of different data types. C) If their scopes do not overlap. D) If they both reference the same object.
Ans: C Section Ref: 8.8
When you use a timer, you need to define a class that implements the ____ interface. A) TimerListener B) TimerActionListener C) ActionListener D) StartTimerListener
Ans: C Section Ref: 9.10
Consider the following code snippet: class MouseClickedListener implements ActionListener { public void mouseClicked(MouseEvent event) { int x = event.getX(); int y = event.getY(); component.moveTo(x,y); } } What is wrong with this code? A) The mouseClicked method cannot access the x and y coordinates of the mouse. B) repaint() method was not called. C) The class has implemented the wrong interface. D) There is nothing wrong with this code.
Ans: C Section Ref: 9.11
Which of the following statements will compile without error? A) public interface AccountListener() { void actionPerformed(AccountEvent event); } B) public interface AccountListener() { void actionPerformed(AccountEvent); } C) public interface AccountListener { void actionPerformed(AccountEvent event); } D) public abstract AccountListener { void actionPerformed(AccountEvent event); }
Ans: C Section Ref: 9.7
____ are generated when the user presses a key, clicks a button, or selects a menu item. A) Listeners B) Interfaces. C) Events. D) Errors.
Ans: C Section Ref: 9.7
How do you specify what the program should do when the user clicks a button? A) Specify the actions to take in a class that implements the ButtonListener interface. B) Specify the actions to take in a class that implements the ButtonEvent interface . C) Specify the actions to take in a class that implements the ActionListener interface. D) Specify the actions to take in a class that implements the EventListener interface.
Ans: C Section Ref: 9.9
What is the type of a variable that references an array list of strings? A) ArrayList[String]() B) ArrayList<String>() C) ArrayList<String> D) ArrayList[String]
Ans: C Section Ref: Section 7.2 Array Lists
You access array list elements with an integer index, using the __________. A) () operator B) [] operator C) get method D) element method
Ans: C Section Ref: Section 7.2 Array Lists
The ____ reserved word in a method definition ensures that subclasses cannot override this method. A) abstract B) anonymous C) final D) static
Ans: C Section Ref: Special Topic 10.2
Consider the following code snippet: public class Demo { public static void main(String[] args) { Point[] p = new Point[4]; p[0] = new Colored3DPoint(4, 4, 4, Color.BLACK); p[1] = new ThreeDimensionalPoint(2, 2, 2); p[2] = new ColoredPoint(3, 3, Color.RED); p[3] = new Point(4, 4); for (int i = 0; i < p.length; i++) { String s = p[i].toString(); System.out.println("p[" + i + "] : " + s); } return; } } This code is an example of ____. A) overloading B) callback C) early binding D) polymorphism
Ans: D Section Ref: 9.3
Which of the following code statements creates a graphical button which has "Calculate" as its label ? A) Button JButton = new Button("Calculate"). B) button = new Button(JButton, "Calculate"). C) button = new JButton("Calculate"). D) JButton button = new JButton("Calculate").
Ans: D Section Ref: 9.9
prompt
Asks the user a question
=
Assignment Operator
What is the difference between Assignment and Initialization?
Assignment can be done as many times as desired whereas initialization can be done only once.
Scope
Block of code in which a variable is in existence and may be used.
&&
Boolean operator meaning both sides have to be true. A Short circuiting logical operator.
What are the different layout managers? What would you use them for?
Border -NESW Box - organizes in single row or column Card - organizes so that only one is visible at a time Flow - Left to Right Grid - Grid of rows and columns GridBag - Grid of cells
Class Interface Implementation
By providing method implementation for each of the abstract methods defined in the interface. Uses reserved word -implements- followed by the interface name in the class header.
Which statements, when inserted in the code below, will cause an exception at run time? class B {} class B1 extends B {} class B2 extends B {} public class ExtendsTest{ public static void main(String args[]){ B b = new B(); B1 b1 = new B1(); B2 b2 = new B2(); // insert statement here } } A. b = b1; B. b2 = b; C. b1 = (B1) b; D. b2 = (B2) b1; E. b1 = (B) b1;
C. is correct. A. compiles and runs fine B. compile error C. runtime error D. compile error E. compile error
Arithmetic Operators
Can be applied to integral or floating point types, includes multiplication(*), division(/), remainder(%), addition(+), subtraction(-).
String
Can use +, ., and +=
Reference Variables
Can't store data values, but *refer to objects* that do.
to convert data type
Casting
-put data type you want in parenthesis before data you want to convert EX: int x = (int) 12.3; //cast double value of 12.3 as int, now has a value of 12
Casting Rules
do
Causes the computer to repeat some statements over and over again (for instance, as long as the computer keeps getting unacceptable results).
switch break
Causes the switch to terminate by transferring control to the end of the statement. Note that it can be used in a similar way in any statement.
Create a new instance of circle
Circle c = new Circle(); ( this is a member of a class that has the same name as the class and has a body)
String concatenation
Combining several strings into a single string, or combining a string with other data into a new, longer string. Done by System.out.println("Words" + variable + "more words");
Java is Pass-by-value (cont)
Compatible type: you can pass an argument of smaller data type to a parameter of larger data type. So, you can pass a byte where an int is expected.
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.
Instantiation
Creating an object.
Overloading the method?
Creating multiple definitions for the same method name, using different parameter types
confirm
Displays a message and returns true if OK was clicked and false for cancel
String Literal
Enclosed in double quotation marks. E.g. "Jonathan withey". This actually creates a String object to be referenced, for example 'String aString = "Character Sequence";'.
internal problems involving the Java virtual machine (the runtime environment). These are rare and usually fatal to the program; there's not much that you can do about them.
Errors
Class definition
Every Java program is a ___________________________.
What class should be the superclass of any exceptions you create in Java?
Exception
True or False: This statement will compile "( (Object)newString.toString("Foo") )" where class NewString has overloaded method "String toString(String arg)".
False. The cast to Object will fail to compile since the Object class does not have a toString(String) method.
Selection Statements
Flow control structures that allow us to select which segments of code are executed depending on conditions. Includes 'if...else' and 'switch...case'.
Output Stream
Flows data from a program out to some external device
restriction for interface method
For the interface method can not declare method as strictfp, protected, static, native, private, final, synchronized.
restriction for interface variable
For the interface variable can not declare variable as private, protected, transient, volatile.
continue
Forces the abrupt end of the current loop iteration and begins another iteration.
What are common errors # 1 with selection statements ?
Forgetting Necessary Braces - The braces can be omitted if the block of code contains a single statement.
Demarcation and indentation
Good programming style in Java includes clearly showing the body of an if statement by creating a boundary around it with '{..}' curly-brackets. Segments of code can also all start with tabbed whitespace to highlight the structure of a program.
switch argument
Has to be an expression of type int, char, short or byte. Notably not float, double and long (too imprecise or large).
Use the dot operator (.)
How do you access a method or instance variable?
What compilation error should you be aware of when using arguments and parameters?
If the amount of arguments(maximum(a, b, c) does not match the amount of parameters(maximum( double x, double, y, double z, double d) this creates a compilation error
What would cause and exception to be thrown from a cast?
If the object was never instantiated as the object it is being cast to or one of its subclasses.
selection sort
In _____________________ sort the program scans through the list from the first element to the last element and identifies the smallest element in the list (keeping track of that element's index). That element is swapped with the first element. The process repeats starting with the second element to the last element - swapping the next smallest for the second element. And continues to repeat this on ever smaller list sizes until the last element (and hence largest) is in place.
Where is the Scanner Class stored ?
In the java.util package. import java.util.Scanner;
int
Indicates that a value is a 32-bit whole number.
long
Indicates that a value is a 64-bit whole number.
boolean
Indicates that a value is either true or false, in the Java sense.
final
Indicates that a variable's value cannot be changed, that a class's functionality cannot be extended, or that a method cannot be overridden.
transient
Indicates that, if and when an object is serialized, a variable's value doesn't need to be stored.
What is used to place a common code in a base class?
Inheritance
What makes code more modular and easier to maintain?
Inheritance
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.
Explain the 2 instances when the Initialization block runs?
Initialization block runs when the class is first loaded (a static init block runs JUST once) or when an instance is created (instance init block runs whenever an instance is creaed)
difference between absttract class and interface constructor
Inside abstract class we can take constructor. Inside interface we *can not* take any constructor.
Objects have both _______ and _______.
Instance Variables && Methods
Instance v.s. Local Variables
Instance variables always get a default value. If you don't explicitly assign a value to an instance variable, the instance variable still has a value. -integers: 0 -floating points: 0.0 -booleans: false -references: null
IPv4
Internet Protocol version 4, , Uses a header format that is 20 octets and combined with the TCP segment forms an IP PDU or IP Datagram or IP Packet. The source and destination address field is 32 bits. Is now actually obselete.
IPv6
Internet Protocol version 6, IPv6 An extended scheme of IP addresses, using 128-bit IP addresses, that allows for more IP addresses than current system, IPv4, which uses 32-bit IP addresses.
try
Introduces statements that are watched (during runtime) for things that can go wrong.
finally
Introduces the last will and testament of the statements in a try clause.
What is the scope of a variable?
It defines where the variable can be used in a program.
What does JVM stand for?
Java Virtual Machine
What are the three ways to return control to the statement that calls a method?
Let the second bracket of the called method return control use return; to return control use return (expression); to return a variable as well as control
Local Variables
Lifetime: when the method finishes, all local variables are destroyed (including the parameters of the method) Scope: local variables can only be used in that method
LinkedHashMap
Like a regular HashMap, except it can remember the order in which elements (name/value pairs) were inserted, or it can be configured to remember the order in which elements were last accessed.
strictfp
Limits the computer's ability to represent extra large or extra small numbers when the computer does intermediate calculations on float and double values.
π
Math.PI;
absolute value of x - y
Math.abs(x - y);
Static (Class) Method
Methods that can be called through the class name. An example would be the squared method. By Value Objects passed to a method "by value" meaning that the current value of the actual parameters copied to the formal parameter in the method header
-Cannot put a bigger box into a smaller box -Data type on RIGHT side of = has to be less than the type on the LEFT side EX: 64bits = 32bits <---CORRECT EX: 32bits = 64bits <--- WRONG
Mixing Data Types Rules
-Cannot put a decimal into an integer -Integers cannot hold decimal values EX: int = double <---WRONG EX: double = int <--- CORRECT
Mixing Data Types Rules
-short and char are not interchangeable -char is unsigned (only positive values), short has both positives and negatives
Mixing Data Types Rules
...
Multi-dimensional arrays can be initialized by placing the values that will populate the array in curly brackets. Each dimension is represented by a nested set of curly brackets. Example: int[ ][ ][ ] threeDArray = {{{1,2}, {3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}
#22 Can a non-abstract class have abstract methods.
NO. Even a single abstract method tells the compiler that the whole class MUST be declared abstract. If a class has one or more abstract method(s) then the class must be abstract.
#17 Can a top-level class be marked as private?
NO. If a class was private... who could use it? For a normal, top-level class, the only access modifiers that make sense are public and default (package). Only nested inner classes can be private.
!
NOT Operator. Reverses the value of a boolean operand
Can a static variable or method access non-static variable or method?
No. Ex. the following WILL NOT work: void go() { } static void letsGo() { go(); } int x = 3; static void add() { size = x; }
In the example shown in Card #3, will the following call work? Animal a = new Animal(); a.eat("Oats");
No. Compiler error. Compiler sees that the Animal class does not have an eat method that takes a string.
Can a public method be overriden by protected method?
No. Overriding methods can NOT be more restrictive than the original method.
Which class is the implicit superclass of all classes?
Object
package
Puts the code into a package — a collection of logically related definitions.
What happens if you cast an object to an invalid type?
Runtime exception will occur
What is the code to read input from a user using the Scanner class to create an object to read input from System.in ?
Scanner input = new Scanner(System.in);
create Scanner object
Scanner keyboard = new Scanner(System.in);
Bit pattern
Series of 0's and 1's
Why doesn't Java support multiple inheritance?
Simplicity and rare-use. Simplicity: The diamond pattern (one grandparent, two parents, one child) is avoided (resolved in C++ with virtual keyword).
Insertion Sort
Sorts a list of values by repeatedly inserting a particular value into a subset of the list that has already been sorted.
Class Constructors
Special methods commonly used to initialize objects when they are created
if
Specifies a block of code to be executed if a certain condition is true
...
Standard Java arrays can be initialized by placing the values that will populate the array in curly brackets. Example: int[ ] myArray = {1,2,3,4}
...
Standard Java arrays can be initialized with the new operator and their size in square brackets after the type. Example: int[ ] myArray = new int[4]
What can standard Java arrays store?
Standard Java arrays can store both objects and primitives.
play 2001.mid
StdAudio.play("2001.mid");
read double
StdIn.readDouble();
read an integer
StdIn.readInt();
std print
StdOut.println();
Char Type
Store single unicode characters (international character set) and can be initialised with character literals enclosed in '. E.g. 'a'.
Example of variable declaration and explanation.
String firstName; Start with data type then variable name. Must end with the ";".
How could you define a String variable named wrd and initialize it to the word cats?
String wrd = "cats";
declare and initial string array, names, with length N
String[] names = new String [N];
Given SuperClass obj = new SubClass(), what is the *object type* of obj?
SubClass
__________ method cannot throw more exceptions (either exceptions of different types or more general exception classes) than its superclass method.
Subclass
Given SuperClass obj = new SubClass(), what is the *reference type* of obj?
SuperClass
Print format statement to get 3.14 of pi
System.out.printf("%.2f", pi);
print (return) a command line input
System.out.println (args[0]);
Command to print to the console? (what letter is capitalized)
System.out.println("Hello");
prompt user and read from keyboard
System.out.println("What's your name, son?"); son_name = keyboard.nextLine();
What System.out method moves the cursor to the next line?
System.out.println()
print (return)
System.out.println();
instanceof
Tests to see whether a certain object comes from a certain class.
What is the access modifier for the default constructor?
The default constructor is the no-arg one provided by the JVM. It will be assigned the same access modifier as the specified for the class itself.
class hierarchy
The instanceof operator can be used only to test objects (or null) against class types that are in the same _____ ___________
interface (keyword)
The keyword used in a class declaration to declare it an interface.
Quality Assurance
The ongoing process of making sure that a software product is developed to the highest standards possible subject to the ever present constraints of time and money. ex: The Maintenance part of a program's lifetime. As time goes on software companies try and fix bugs or problems with programs. This can be seen with java. When it was first created it had many security hole many of which have been patched up, making the product closer to perfection.
Sorting
The process of arranging a list of items in order.
For overloaded methods, is it the reference type or dynamic runtime object type that determinesl which method gets called?
The reference type (not the object type) determines which overloaded method is invoked!
Explain "Reference Type" and "Object Type"
The reference type corresponds to the type in a variable declaration. The object type corresponds to the instantiated class in an object variable declaration. So "reference type" is the LHS type and "object type" is the actual instantiated type on the RHS of an object variable declaration.
object-oriented development
The solution to a task that is implemented as a system of objects.
Robust
The state in which a program is protected against most possible crashes from bad data and unexpected values. ex: This is part of the maintenance process of a program. There is no such thing as a perfect bug free program, but programs can be created to the best of their own ability. This can be seen with a theoretical perfect program. It should also include valid error messages for invalid data input
What is the difference between the state and the behavior of a class?
The state of a class consists of the values of its fields. The behavior of a class is defined by its methods.
What is the switch statement ?
The switch statement is Java's multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. As such, it often provides a better alternative than a large series of if-else-if statements. Here is the general form of a switch statement:
superclass
The upper-most class in a class hierarchy. A class that has subclasses.
true
The || and | operators return ____ if either or both operands are true.
Methods
Things an object does are and represents the behavior of an object.
Instance Variables
Things an object knows about itself and represent the state of an object.
Error
This Class indicates issues that an application should not try to catch. Subclass of the class Throwable.
What is the definition of the Java class Library A.K.A Java A.P.I(Java Application Programming Interface)?
This is the list of preprocessed classes, packages, and methods that you may use at your disposal such as the Math....() methods.
True or False, by catching a exception superclass you can also catch any subclass exceptions that are thrown?
True
True or False: A class uses the keyword extends to inherit a class.
True.
True or False: A derived class can only inherit members with the default access modifier if both the base class and the derived class are in the same package.
True.
True or False: An interface can extend multiple interfaces.
True.
True or False: An interface uses the keyword extends to inherit another interface.
True.
True or False: If a method defines a local variable or method parameter with the same name as an instance variable, the keyword this must be used to access the instance variable in the method.
True.
True or False: The method signatures of a method defined in an interface and in the class that implements the interface must match; otherwise, the class won't compile.
True.
How about turning a primitive number into a String?
Use string concatenation double d = 30.24; String dString = "" + d; Use toString method in the Double class double d = 30.24; String dString = Double.toString(d); Check Java API for more such methods
Boolean type (boolean)
Used in conditional tests to control execution flow- TRUE or FALSE
Integer.ParseInt()
Used to get a value of a String, usually with a digit.
What are the three ways to call a method?
Using the method name itself within the same class Using the object's variable name followed by a dot (.) and the method name to call a non static method of the object. Using the class name and a dot(.) to call a static method of a class: Math.pow
Boolean
Variable type used to represent a single true or false value. Size of 1 bit.
int
Variable type with 32 bits and a range of [-2147483648 to 2147483647] = 4 bytes of storage
Char
Variable type with a size of 16 bytes whose range is all Unicode characters. It has a minimum value of '\u0000' (or 0) and a maxiumum value of '\uffff' (or 65,534 inclusive)
%
What arithmetic operator returns the remainder of a division?
Null
What does a reference variable have for its value when it is not referencing any object?
The bits representing a way to get to an object on the heap.
What does a reference variable value have?
What an object knows and what an object does
What does an class define
It must return a value compatible with the declared return type.
What happens if a method declares a non-void return type?
A return type
What is always required with a method?
An object
What is an Array always is?
false
What will print (or ERROR)?
true
What will print (or ERROR)?
a high-level design (Sierra 109)
What you should start with a Java Program
At Runtime
When a Java program is nothing more than objects 'talking' to other objects.
What is control statement stacking?
When a number of control statements are placed one after another in a sequence within a program.
Arrays as Parameters
When an array is passed as a parameter, it is actually passing an object reference.
Operator Precedence
When an expression includes one or more operators, this governs in what order the operations are carried out. For example, multiplication has a higher precedence than addition and so is carried out first. Each language has rules of precedence for all of it's operators.
Comparing Data
When comparing data using boolean expressions, it's important to understand the nuances of certain data types Let's examine some key situations: -Comparing floating point values for equality -Comparing characters -Comparing strings (lexicographic order) -Comparing object references
Formatting Output
When printing float point values System.out.println(2.0/3); It prints 0.6666666666666666 to the monitor screen The DecimalFormat class can be used to format a floating point value in various ways For example, you can specify that the number should be truncated to three decimal places It is part of the java.text package
Class
Where all Java code is defined.
Operator Overloading
Where the user can define the behaviour of an operator depending on the *types of its operands*. This isn't possible in Java, although the '+' operator is overloaded by the system to concatenate String objects.
Conditional Processing
Whereby a program can respond to changes due to the data on which it operates.
Strongly Typed
Whereby, in a language (Java), every variable and expression has a type *when the program is compiled*. You cannot arbitrarily assign the value of one type to another.
In polymorphism, what does the object type determine?
Which implementation is executed for overridden methods
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.
Nesting Conditional Constructs
Within a code block, additional flow control structures can be nested. For example an if statement could be nested within the code block of another if statement, or a switch statement within the case of another switch statement. Note that stylistically, nesting results in further indentation so that flow can be followed easily.
What is an iterator? Where have we used them before?
Within the loop, obtain each element by calling next( ). We've used these with scanner and random
Can an interface extend more than one interface?
Yes
Can there be multiple childen (subclasses) of a parent (superclass)?
Yes
will the code below compile? public int foo() { char c = 'f'; return c; }
Yes, because char data type is compatible with int data type.
Can an interface extend more than one interface?
Yes.
#123 Can an abstract method be overriden?
Yes. An abstract method has no choice! It must be overriden.
Will this code compile and execute? class Animal { } class Dog extends Animal { } class DogTest { public static void main(String[] args) { Dog d = new Dog(); Animal a1 = d; Animal a2 = (Animal) d; } }
Yes. This is an upcasting example that works. Dog IS-AN Animal, so anything Animal can do, Dog can do.
#20 Can a private method of a superclass be declared within a subclass?
Yes. Trick Question!!! Private methodscan NOT be overriden, but they CAN be re-declared/redifined in the subclass, and called directly on the subclass object. But polymorphism will not apply.
Is this OK? public Student doHomework() { return null; }
Yes. it is ok to return Null where an object reference is expected as return type.
Comparing Floating Point Values
You should rarely use the equality operator (==) when comparing two floating point values (float or double) because two floating point values are equal only if their underlying binary representations match exactly (0.1 + 0.2) == 0.3 // false To determine the equality of two floats, use the following technique: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); If the difference between the two floating point values is less than the tolerance, they are considered to be equal The tolerance could be set to any appropriate level, such as 0.000001
What escape sequence makes one backslash character in a print or println statement?
\\
Backspace
\b
short hand a = a + n;
a += n;
short hand a = a - n;
a -= n;
bytecode
a binary program
The first statement of every constructor must be ...
a call to either this() (an overloaded constructor) or super().
compiler
a computer program that translates the WHOLE code into machine language and then carries out the statement
final
a constant, or a class that cannot be extended or method that cannot be overridden. Keyword used to declare an identifier a constant. Indicates that a variable's value cannot be changed, that a class's functionality cannot be extended, or that a method cannot be overridden.
load factor
a floating-point number between 0.0 and 1.0 that determines how and when the hash table allocates space for more elements.~258PDF
semantic error
a logical error, for example if you use the correct word in the wrong location
variable
a memory location, referenced by an idetifier, whose value can be changed during execution of a program
println
a method that prints characters to the screen and moves to the next line
interpreter
a program that executes the instructions in another program
system software
a program that manages the computer itself -ex.Windows
panes
a rectangular area wihin a window with its own width, height, color and drawing area
null Reference
a reference that does not refer to any object
literal string
a series of characters that will appear in the output exactly as entered, must be in quotation marks
DOS devleopment environment
a set of software tools that allows you to edit, compile, run, and debug programs using the DOS operating system
developmental environment
a set of tools that help you write programs by providing features such as displaying a languages keywords in color
variable
a storage location with a name; holds a value
procedural programming
a style of programming in which operations are executed one after the other in sequence
class
a term that describes a group or collection of objects with common properties
What is the sentinel value?
a value to be typed in to stop a loop
Which two members are valid in interfaces?
abstract declarations and constants
What does ++c do? and what is it called? And --c?
adds 1 to c then prints out result. Prefix increment subtracts 1 from c then prints out result. Prefix decrement
Iteration construct/Loops
allows program to repeatedly execute instructions
A method can have many of these.
argument
extended classes can be used
as a basis for any other class
b
b
ternary operator
b? e1:e2 conditional (boolean) expression if b is true, e1 if b is false, e2
interface is a
collection of abstract method support multiple inheritance It is preceded by interface keyword.
Method returning an integer greater than, equal to, or less than 0 to indicate whether this string is greater than, equal to, or less than s1.
compareTo(s1) - it compares character by char. until difference in string letters found. - Then → returns an integer representing the difference in characters
hardware
computer equipment such as a keyboard
Chapter 12: These patterns work together to ______ the three players in the MVC model, which keeps designs clear and flexible.
decouple
What are some examples of these class relationships?
dependency - concat method of the string class - str3 = str1.concat(str2); Aggregation - A car is an aggregation of objects (wheels, engine, etc)
polymorphism
describes the feature of languages that allows the same word or symbol to be interpreted correctly in different situations based off context
double b = a / b, but a is an int. Cast int to double
double b = (double) a / b;
Create a program that computes the area of a number and prints it out to the screen
double radius; double area; radius=20; area= radius * radius *3.14; System.out.println(area);
Insert a comment? On multiple lines?
double slash ex. //commented slash asterisk ex. /* one line two lines */ (its the back slash for both)
Which keyword is used to declare a subclass of an existing class?
extends
IS-A is expressed with the keyword ...
extends.
If 1 of the operands of an && is false then the expression is _____?
false--- this is also known as the short-circuit AND operator
else
following if else { Statements; } conditional statement
For loop structure
for ( <initialization>; <continuation test>; <update>) { <statement>; ... <statement>; }
chapter 3 common errors to avoid
forgetting to provide arguments when constructor requires them; putting a semicolon at end of a method header; trying to overload methods by giving them different return types
System.out.println("funny"); prints out
funny
Accessors
get() methods
Naming standard for accessor method?
getABC();
These help create encapsulation.
getter, setter, public, private
The first non-abstract (concrete) class to extend an 'abstract' class must ...
implement all the 'abstract' class' 'abstract' methods.
An 'abstract' implementing class does not have to ...
implement the interface methods (but the first concrete subclass must).
Wildcard import
imports all the classes in a package. EX: • import javax.swing.* imports all classes from package javax.swing. import javax.swing.*;
what are the members of a class?
include fields and methods and may also include constructors and initializers
pseudocode
informal description of a sequence of steps for solving a problem; no strict requirements because it is read by human readers, not a computer program
A for loop is functionally equivalent to the following while loop structure:
initialization; while ( condition ) { statement; increment; }
Only setters should update these.
instance variables
Generate a random integer between 0 (inclusive) and upperLimit (exclusive).
int num = (int)(Math.random() * upperLimit);
How could you define an integer named num and initialize it to 394?
int num = 394;
Example of how to find out how many buts are being represented in a set:
int numBits = connex.size();
conditional operator
int var = expression ? value 1 : value 2; (true/false) (true) (false)
Numeric Data Sub-Types
int, long, float, double
declare and initial int array, number, with length N
int[] number = new int [N];
What is the this reference?
it is used to refer to the currently executing object (static)
literals
items in programs whose values do not change; restricted to the primitive data types and strings
applets
java code that can be located anywhere on the internet
^
logical XOR, effectively returns true if both its operands are different (ie. a mix of true and false) but returns false if they are the same. E.g. 'boolean isHetero = likesWomen ^ likesMen;'.
chapter 2 common errors to avoid
mismatched braces, quotations, parenthesis, misspelling key words, misspelling variable names
syntax error
misuse of the language
'final' is the only ...
modifier available to local variables.
/n
newline; advances the curson to the next line for subsequent printing
Is the break statement on a switch needed for the last statement/default?
no
number literal
notation for representing a fixed value in source code
Chapter 1: Patterns are proven
objectoriented experience
Interface constant declaration of 'public', 'static', and 'final' are ...
optional in any combination.
'protected' members can be accessed by ...
other classes in the same package, plus subclasses regardless of package.
Chapter 1: Patterns provide a shared language that can maximize the value of your communication with
other developers
Methods from a superclass can be ...
overloaded in a subclass.
argument
pieces of information that are sent into a method, usually because the method needs the information to perform its task-arguments always appears within parenthesis
What does c++ do? and what is it called? and c--?
prints result then adds 1. Postfix increment prints result then subtracts 1. Postfix decrement
System.out.println( _____ );
prints the content in the parentheses ( _____ ) and moves to the next line
System.out.print( _____ );
prints the content in the parentheses ( _____) and remains on the same line
editor
program for entering and modifying text; functions like a word processor in which you enter java instructions and then open a console window and type commands to execute the program
source code
programming statements written in a high level programming language
Which two modifiers *are implicit* for methods declared in an interface?
public and abstract
If A is a class.....B and C are interfaces, what is the proper signature for class A implements interfaces B and C?
public class A implements B, C {}
creating class in driver with private instance fields
public class Rectangle { private double length; private double width; }
accessor method
public double getWidth() { return width; }
mutator method
public void setWidth(double w) { width = w; }
What is the method signature of public void setDate(int month, int day);?
setDate(int, int);
aggregation
special form of association representing ownership of a relationship bw obj's
'private' members are not visible to ...
subclasses, so private members cannot be inherited.
A single 'abstract' method in class means ...
the whole class must be abstract.
Are members of a class static or non static?
they can be static or non static. static members belongs to the class itself, while nonstatic members are associated with the instance of the class (fields and methods)
compiler
translates the high-level instructions of programs into the more detailed instructions required by the CPU
escape character
used when including 'special characters' in string literals
BitSet class
useful when you need to represent a large amount of binary data, bit values that can be equal only to 0 or 1. These also are called on-or-off values
Example of how to add a element to a vector:
v.add("Inkster");
final
variable is defined with the reserved word its value can never change. Ex: final double .canVolume = 0.335;
Method call/actual and formal for method name; No value, send parameters
variableName = methodName();
Chapter 1: Most patterns allow some part of a system to
vary independently of all other parts
long type
• represents an INTEGER ranging from -263 to 263-1 • Primitive variable vs. integer - ranges → -231 (-2147483648) to 231-1 (2147483647).
"What is a marker interface?"
"A Marker interface is an empty interface used to indicate that a given class implements a certain functionality. Serializable for example, indicates that a classes non-transient data can be written to an OutputStream. RandomAccess indicates that that a collection supports fast ( almost constant time ) random access."
"Explain how the final keyword is used in Java."
"A method declared final may not be overridden. A class declared final may not be extended. A variable declared final may be assigned only once. A static final variable may be used like a constant. Method arguments declared final can not be changed by the called method."
"What does the *default toString() method* implementation do?"
"Returns the class name and hash code. If this is not the desired representation of the object, the developer should override it."
Integer value: 48
'0'
switch example
'char control = 'a'; switch (control) { case 'a': invokeA(); break; default: invokeError(); break; }' Note that because 'a' is logically equivalent to the switch argument 'control', that case would be selected and, once the statements executed, break would transfer control to the end of the switch statement, skipping the default: case.
A class cannot be both ...
'final' and 'abstract'.
multiplication operator
*, fourth highest precedence, left to right association
*ASSOCIATION, COMPOSITION and AGGREGATION*
*ASSOCIATION, COMPOSITION and AGGREGATION*
How many interfaces can a class extend directly?
*As many as it needs.*
What is a *composition association*?
*Composition association* is used to describe relationships where *an object is composed of one or more objects*. The internal object makes sense only while stored in the internal object.
What is a *direct association* relationship?
*Direct association* describes a *"has a" relationship*. This is a basic association that represents navigability. Direct association is a *weak relationship* and therefore can be generalized to an association. The containing object also has the responsibility of managing the life cycle of the internal object.
*ENCAPSULATION*
*ENCAPSULATION*
*FINAL*
*FINAL*
*INHERITANCE*
*INHERITANCE*
*INTERFACE*
*INTERFACE*
*IS-A and HAS-A*
*IS-A and HAS-A*
*OBJECT ORIENTATION*
*OBJECT ORIENTATION*
*OVERLOADING*
*OVERLOADING*
*OVERRIDING*
*OVERRIDING*
How many classes can a class extend?
*Only one!* a class can only extend a single class
*POLYMORPHISM*
*POLYMORPHISM*
*SUPERCLASS OF ALL CLASSES*
*SUPERCLASS OF ALL CLASSES*
Is polymorphism unidirectional or bidirectional?
*Unidirectional*. More specific objects can act polymorphically only as more general objects.
difference between absttract class and interface fields
*abstract class* may contain either variable or constants. *interface* should contains only constants.
A class that implements an interface must implement what else?
*all the methods contained in the interface.*
#108 Class B extends A. B overrides doStuff() method inherid from A. Which method gets called if you say: A myA = new B(); myA.doStuff(); runtime error or compiler error or doStuff() in A or doStuff() in B?
*doStuff() in B* Java's polymorphism causes instance methods to be bound (chosen) at runtime, not during compilation. At runtime, the overriding method of the 'actual object' (which is a B) is dynamically chosen, even though the reference type is A.
*extends*
*extends*
*implements*
*implements*
*Polymorphic* method invocations apply only to ...
*overridden* instance methods.
Which keyword is used to access superclass members within a subclass?
*super*
Unary operators
+ and - Take a single operand; not binary. Added to the list of precedence: 1) Unary 2) Multiplicative 3) Additive
Preincrement
++x "Increment, then give me x"
addition operator
+, fifth highest precedence, left to right association
unary plus operator
+, third highest precedence
combined operators
+=, -=, *=, /=, %=
Portable
- A programing language is ____ if it can be used on more than one type of computer without having to be changed
.Class
- Byte code form of the program that can be sent to other computer with Java
post-test loop
-do while construct
switch construct
-expr must eval to char, byte, short or int types -case values must be literals/constants + unique -include BREAK after case
Bit
A binary digit 0 & 1. • binary numbers = #'s consists of 0's & 1's.
JDK
A bundled set of development utilities for compiling, debugging, and interpreting Java Applications.
What must a class name always start with?
A capital letter then camel case with no spaces.
fields and methods
A class can be viewed as a collection of data (or state) and code to operate on that state. the data is stored in fields and the cold is organized into methods.
instance variables, getter, setter, method
A class can have any number of these.
Nested Classes
A class written inside another class Enclosing Classes The class that the nested class is nested in
double
A data type that represents decimals.
int
A data type that represents whole numbers.
What conditions must a method meet to be an overridden one?
A derived class is said to override a method in the base class if it defines a method with the same name, same parameter list, and same return type as in the derived class.
The do Statement
A do statement has the following syntax: do { statement-list; } while (condition); The statement is executed repeatedly until the condition becomes false The statement-list is executed once initially, and then the condition is evaluated
driver program
A driver program is often used to test your own written class The DogTestDrive class contains a main method that drives the use of the Dog class, exercising its services
What is the definition of an algorithm?
A procedure for solving a problem in terms of: The actions to execute and the order in which these actions execute
Browser
A program that allows the user to find and view pages on the world wide web.
Consider the following code: class Base{ private float f = 1.0f; void setF(float f1){ this.f = f1; } } class Base2 extends Base{ private float f = 2.0f; //1 } Which of the following options is a valid example of overriding? A. protected void setF(float f1){ this.f = 2*f1; } B. public void setF(double f1){ this.f = (float) 2*f1; } C. public void setF(float f1){ this.f = 2*f1; } D. private void setF(float f1){ this.f = 2*f1; }
A. and C. are correct. An overriding method can be made less restrictive than the overridden method. The restrictiveness of access modifiers is as follows: private>default>protected>public (where private is most restrictive and public is least restrictive).
Which reference type can contain implementation, but does not require it?
Abstract class
What is an abstract class?
Abstract classes, unlike interfaces, are classes. There are more expensive to use because there is a lookup to do when you inherit from them. Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for them.
What is accomplished by reference type casting?
Access to subtype members that are not available through a reference type
J2SE
Acronym for Java 2 Platform, Standard Edition.
Concatenation
Adding one string to another.
Given this: class A { void print() { } } class B extends A { void print() { } void goB() { } } class C extends B { void print() { } void goC() { } } Which one of the following are correct? A. A a1 = new B(); B. A a2 = new C(); C. B b1 = new C(); D. a1.print(); // what will this print? E. ((B) a1).goB();
All options are correct.
Inheritance provides which of the following?
Allows developers to place general code in a class that more specific classes can gain through inheritance. Also promotes code reuse.
Casting
Allows you to convert a data type into another one; you can change a double to an int by typing (int) 3.25.
client code
An application that uses one or more classes.
Logical Invariant
An assertion that expresses a relationship between variables that remains constant throughout all iterations of the loop. ex: for(int j=0;j<=10;j++ ) { J++ } J in this case would change and check a counter which will add 1 to J and check if J is less than or equal to 10.
bug
An error in the code
Peripherals
An input device, output device, or secondary storage device that is not part of the central processing unit (CPU)
array
An object that is a simple but powerful way to group and organize data.
What is the error in this array code fragment? double[] data; data[0] = 15.25; A) The array referenced by data has not been initialized. B) A two-dimensional array is required. C) An out-of-bounds error occurs. D) A cast is required.
Ans: A Section Ref: Section 7.1 Arrays
Wrapper objects can be used anywhere that objects are required instead of ____. A) primitive data types B) clone methods C) array lists D) generic classes
Ans: A Section Ref: Section 7.3 Wrappers and Auto-boxing
Rewrite the following traditional for loop header as an enhanced for loop, assuming that ArrayList<String> names has been initialized. for (int i = 0; i < names.size(); i++) { // process name } A) for (String s : names) B) for (int i = 0; i < names.size(); i++) C) for (s : names) D) for (names : String s)
Ans: A Section Ref: Section 7.4 The Enhanced for Loop
When designing a hierarchy of classes, features and behaviors that are common to all classes are placed in ____. A) every class in the hierarchy B) the superclass C) a single subclass D) all subclasses
Ans: B Section Ref: 10.1
Which of the following is a good indicator that a class is overreaching and trying to accomplish too much? A) The class has more constants than methods B) The public interface refers to multiple concepts C) The public interface exposes private features D) The class is both cohesive and dependent.
Ans: B Section Ref: 8.2
Which of the following statements about a Java interface is NOT true? A) A Java interface defines a set of methods that are required. B) A Java interface must contain more than one method. C) A Java interface specifies behavior that a class will implement. D) All methods in a Java interface must be abstract.
Ans: B Section Ref: 9.1
You have a class which extends the JComponent class. In this class you have created a painted graphical object. Your code will change the data in the graphical object. What additional code is needed to ensure that the graphical object will be updated with the changed data? A) You must call the component object's paintComponent() method. B) You must call the component object's repaint() method. C) You do not have to do anything - the component object will be automatically repainted when its data changes. D) You must use a Timer object to cause the component object to be updated.
Ans: B Section Ref: Common Error 9.6
The wrapper class for the primitive type double is ____________________. A) There is no wrapper class. B) Double C) doubleObject D) Doub
Ans: B Section Ref: Section 7.3 Wrappers and Auto-boxing
Which of the following represents the hierarchy of GUI text components in the hierarchy of Swing components? A) JTextField and JTextComponent are subclasses of JTextArea. B) JTextArea and JTextComponent are subclasses of JTextField. C) JTextField and JTextArea are subclasses of JTextComponent. D) JTextField, JTextArea, and JTextComponent are subclasses of JPanel.
Ans: C Section Ref: 10.1
Which of the following questions should you ask yourself in order to determine if you have named your class properly? A) Does the class name contain 8 or fewer characters? B) Is the class name a verb? C) Can I visualize an object of the class? D) Does the class name describe the tasks that this class will accomplish?
Ans: C Section Ref: 8.1
What is the purpose of this algorithm? for (int i = 0; i < data.size(); i++) { data.set(i, i ); } A) Filling in initial values for an array. B) Counting matches in an array. C) Filling in initial values for an array list. D) Counting matches in an array list.
Ans: C Section Ref: Section 7.6 Common Array Algorithms
Which of the following is true regarding inheritance? A) When creating a subclass, all methods of the superclass must be overridden. B) When creating a subclass, no methods of a superclass can be overridden. C) A superclass can force a programmer to override a method in any subclass it creates. D) A superclass cannot force a programmer to override a method in any subclass it creates.
Ans: C Section Ref: Special Topic 10.1
Consider the following code snippet: final RectangleComponent component = new RectangleComponent(); MouseListener listener = new MousePressListener(); component.addMouseListener(listener); ______________ frame.add(component); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); Which of the following statements completes this code? A) private static final int FRAME_WIDTH = 300; B) private static final int FRAME_HEIGHT = 400; C) Frame frame = new Frame(); D) JFrame frame = new JFrame();
Ans: D
To create a subclass, use the ____ keyword. A) inherits B) implements C) interface D) extends
Ans: D Section Ref: 10.2
The ____reserved word is used to deactivate polymorphism and invoke a method of the superclass. A) this B) my C) parent D) super
Ans: D Section Ref: 10.3
Which of the following is true regarding subclasses? A) A subclass may call the superclass constructor by using the this reserved word. B) A subclass cannot call the superclass constructor. C) If a subclass does not call the superclass constructor, it must have a constructor with parameters. D) If a subclass does not call the superclass constructor, it must have a constructor without parameters.
Ans: D Section Ref: 10.4
Which of the following is not a reason to place classes into a package? A) to avoid name clashes (most important) B) to organize related classes C) to show authorship of source code for classes D) to make it easier to include a set of frequently used but unrelated classes
Ans: D Section Ref: 8.9
A method that has no implementation is called a/an ____ method. A) interface B) implementation C) overloaded D) abstract
Ans: D Section Ref: 9.1
When an array is created, all elements are initialized with ___. A) zero B) array elements are not initialized when an array is created C) null D) a fixed value that depends on the element type
Ans: D Section Ref: Section 7.1 Arrays
Which class manages a sequence of objects whose size can change? A) Array B) Object C) Sequence D) ArrayList
Ans: D Section Ref: Section 7.2 Array Lists
Which code fragment constructs an arrray list named players that is initialized to contain the strings "Player 1" and "Player 2"? A) ArrayList<String> players = new ArrayList<String>(); players.set(0, "Player 1"); players.set(1, "Player 2"); B) ArrayList<String> players = new ArrayList<String>(); players.set(1, "Player 1"); players.set(2, "Player 2"); C) ArrayList<String> players = { "Player 1", "Player 2" }; D) ArrayList<String> players = new ArrayList<String>(); players.add("Player 1"); players.add("Player 2");
Ans: D Section Ref: Section 7.2 Array Lists
Which of the following is considered by the text to be the most important consideration when designing a class? A) Each class should represent an appropriate mathematical concept. B) Each class should represent a single concept or object from the problem domain. C) Each class should represent no more than three specific concepts. D) Each class should represent multiple concepts only if they are closely related.
Ans:B Section Ref: 8.1
What would be the result of attempting to compile and run the following code? // Filename: TestClass.java public class TestClass{ public static void main(String args[]){ B c = new C(); System.out.println(c.max(10, 20)); } } class A{ int max(int x, int y) { if (x>y) return x; else return y; } } class B extends A{ int max(int x, int y) { return 2 * super.max(x, y) ; } } class C extends B{ int max(int x, int y) { return super.max( 2*x, 2*y); } } A. The code will fail to compile. B. Runtime error. C. The code will compile without errors and will print 80 when run. D. The code will compile without errors and will print 40 when run. E. The code will compile without errors and will print 20 when run.
Answer is C. When the program is run, the main() method will call the max() method in C with parameters 10 and 20 because the actual object referenced by 'c' is of class C. This method will call the max() method in B with the parameters 20 and 40. The max() method in B will in turn call the max() method in A with the parameters 20 and 40. The max() method in A will return 40 to the max() method in B. The max() method in B will return 80 to the max() method in C. And finally the max() of C will return 80 in main() which will be printed out.
Which of these statements concerning nested classes and interfaces are true? Select 3 options: A. An instance of a static nested class has an inherent outer instance. B. A static nested class can contain non-static member variables. C. A static nested interface can contain static member variables. D. A static nested interface has an inherent outer instance associated with it. E. For each instance of the outer class, there can exist many instances of a non-static inner class.
B, C and E are correct. Note the difference between an Inner class and a static nested class. Inner class means a NON STATIC class defined inside a class. Remember: A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class. An inner class is a nested class that is not explicitly or implicitly declared static. A class defined inside an interface is implicitly static. For example, public class A // outer class { static public class B //Static Nested class . It can be used in other places: A.B b = new A.B(); There is no outer instance. { } class C //Inner class. It can only be used like this: A.C c = new A().new C(); Outer instance is needed. { } } One can define a class as a static member of any top-level class. Now consider the following contents of a file named I1.java ... public interface I1 { public void mA(); public interface InnerI1 { int k = 10; public void innerA(); } } Here, interface InnerI1 is implicitly STATIC and so is called as static nested interface. 'k' is a static (& final) member of this interface.
Consider the following classes in one file named A.java... abstract class A{ protected int m1(){ return 0; } } class B extends A{ int m1(){ return 1; } } Which of the following statements are correct... A. The code will not compile as you cannot have more than 1 class in 1 file. B. The code will not compile because class B does not override the method m1() correctly. C. The code will not compile as A does not have any abstract method. D. The code will compile fine
B. is the correct answer. The overriding method should not decrease the access level The hierarchy is as follows: private->'no modifier'->protected->public
Composition
Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.
Difference between aggregation and composition
Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object. Example: A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don't go deeper into example and justify relationships!
What contains methods and instance variable and can be instantiated?
Concrete Class
Consider the following class and interface definitions (in separate files): public class Sample implements IInt{ public static void main(String[] args){ Sample s = new Sample(); //1 int j = s.thevalue; //2 int k = IInt.thevalue; //3 int l = thevalue; //4 } } public interface IInt{ int thevalue = 0; } What will happen when the above code is compiled and run? A. It will give an error at compile time at line //1. B. It will give an error at compile time at line //2 C. It will give an error at compile time at line //3 D. It will give an error at compile time at line //4 E. It will compile and run without any problem
E. is correct... As a rule, fields defined in an interface are public, static, and final. (The methods are public and abstract.) Here, the interface IInt defines 'thevalue' and thus any class that implements this interface inherits this field. Therefore, it can be accessed using s.thevalue or just 'thevalue' inside the class. Also, since it is static, it can also be accessed using IInt.thevalue or Sample.thevalue.
multiplicity
Each class involved in a relationship may specify a multiplicity. A multiplicity could be: • a number or an interval that specifies how many of the class's objects are involved in the relationship.
What is the order of execution of instance initializers and constructors-in base and subclasses? Constructors first or initializers?
Each class will have its initializers called first, before the constructor. The super class constructor will be called first, implicitly or excplicitly, before the subclass.
Logical Operator
Either of the logical connective operators && (and), || (or), or ! (negation) ex: (in use) (exsampleClassA >= 0 || > exsampleClassB), or (exsampleClassA >= 0 && > exsampleClassB) or (exsampleClassA >= 0! > exsampleClassB)
Floating Point Literals
Either written with a whole and fractional part separated by a dot '45.98' or with scientific notation which allows significant digits that are multiplied by a power of 10 specified after the character 'e'. 'double speedOfLight = 2.998e8'. It seems that both double and float use the same literals, unlike C++.
What does a scanner do for a program?
Enables the program to read data (ints, dbls, char etc.)
import
Enables the programmer to abbreviate the names of classes defined in a package.
native
Enables the programmer to use code that was written in another language (one of those awful languages other than Java).
What are the four basic development activities? How do they interact with one another? Which one is the most important?
Establishing the requirements -Software requirements specify what a program must accomplish. Creating a design -A software design indicates how a program will accomplish its requirements. Implementing the design -Implementation is the process of writing the source code that will solve the problem. Testing -Testing is the act of ensuring that a program will solve the intended problem given all of the constraints under which it must perform.
Literals
Have a fixed value, as opposed to a variable. Each primitive type has an associated set of literal values and a literal value can be assigned to a primitive variable of the same type.
Given this code: class A{ int i = 10; public static void m1(){ } public void m2() { } } class B extends A{ int i = 20; public static void m1() { } public void m2() { } } What will the following methods output or call? A a = new B(); A. System.out.println(a.i) B. a.m1(); C. a.m2();
Here, UNLIKE m2, m1() of B does not override m1() of A, it just shadows it, as proven by the following code: A a = new B(); System.out.println(a.i) //will print 10 instead of 20 a.m1(); //will call A's m1 a.m2(); //will call B's m2 as m2() is not static and so overrides A's m2()
Inheritance is a key concept that underlies ...
IS-A, polymorphism, overriding (not "overloading" but redefine a methodand from a superclass in a subclass) and casting.
-Must start with a letter -Can contain letters, numbers, and underscore character -Cannot contain spaces -Cannot contain reserved (key) words
Identifiers (name) Rules
Constants
Identifiers that always have the same value.
' '
Identifies a string of text to be presented to the user
Name the variable NOTE: starts with lower case, new word starts with capital letter (numDays)
Identity
Increment/Decrement Operators
Increase/decrease the value of a variable by a particular amount. Addition: x += 1 will accomplish x = x + 1. Subtraction: x -= 2 will accomplish x = x - 2. Multiplication: x *= 5 will accomplish x = x * 5. To increment or decrement by one, do: x++ x---
++
Increment operator - Increases the value of operand by 1 can be both prefix and postfix ++prefix is value after increment postfix++ is value before increment
float
Indicates that a value is a 32-bit number with one or more digits after the decimal point.
How many interfaces can a class implement?
Infinity
In a (for), (while), or, (do...while) statement what does the break statement do? and a continue statement?
It breaks out of the loop using an if statement ' Ex: if (count==5) break; 1 2 3 4 It skips the number defined Ex: if (count==5) continue; 1 2 3 4 6 7 8 9 10
What does a UML activity diagram do?
It models the workflow(also called the activity) of a portion of a software system.
A variable declared in a method is said to be a ____________________.
Local variable
-All must have one (except apps) -Follows the class, where execution begins -Must h ave { and }
Main method
Power or Exponent
Math.pow(x,y)
square root of a
Math.sqrt (a);
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.
All objects in a class have the same _______ and same types of _______.
Methods && Instance Variables
Methods with parameters
Methods that you can pass one or more values in to.
#129 Can a class be declared synchronized?
NO.
Methods
Name for functions that are defined in a class..
Class scope variables
Name for variables that are used in a class.
Extended "if" Statement
Nested selection in which additional "if-else" statements are used in the else option. ex: if(j<=0) { System.out.println("Example"); } else { System.out.println("Example"); if(m<10) System.out.println("Example"); else { System.out.println("Example"); } }
Can one child (subclass) have more than one parent (superclass)?
No
Can instance initializers be inherited by a derived class?
No. The instance initializers can't be defined with any explicit access. They can only be defined using the 'default' access. Also, instance initializers aren't inherited by derived class. They execute when a class is instantiated.
if you call the next() method from the iterator interface and there are no more elements next() throws what exception?
NoSuchElementException
When can a child class in another package access a protected member in the parent class?
Only when the children tries to access it own variable, not variable of other instance
Logical Operators
Operate on boolean values and can be unary or binary. Often used to combines logical expressions with relational operators.
Precedence and Parentheses
Operations in parentheses are carried out first and can therefore be used by the programmer to control the order in which an expression is evaluated. This is preferable so that anyone using the code doesn't have to remember orders of precedence and it helps avoid obfuscation.
what is the output of the following program? class Animal { public void eat() { System.out.println("I eat everything"); } } class Horse { public void eat() { System.out.println("I eat Hay"); } public void eat(String food) { System.out.printf("I eat %s \n", food); } } public class TestAnimals { public static void main(String[] args) { Animal a = new Animal(); Animal h = new Horse(); a.eat(); h.eat(); } }
Output should be: I eat everything I eat Hay To print Superclass' version of the method, do the following inside the Horse.eat() method: super.eat();
What is an overloaded method?
Overloaded methods accept different lists of arguments. The argument lists can differ by: - Changes in the number of parameters that are accepted - Changes in the types of parameters that are accepted - Changes in the positions of parameters that are accepted
#100 Class A inherits from B. B includes a method with the same name, return type, and arguments as a method in A. This is an example of overriding or overloading
Overriding. An overriding method must have the same name, returntype and arguments as the method in the superclass. It can't declare new or broader checked exceptions, and it also can't have more restrictive access.
What allows one object to act as either one of its superclasses or as an interface that it implements?
Polymorphism
What is the concept called in which the developer defines the requirement functionality instead of defining strict object data types?
Programming to an interface
What are the three types of class variables?
Public, Allows them to be used in your own classes Static, allows them to be accessed vie that class name and a dot (.) separator Final, indicates that they are constants--- their values cannot change after they are initiated.
<=
Relational operator: less than or equal to
Modulus
Represented by the character %, gives the remainder of a division between integral or fractional numbers (note that the result can also be fractional).
Index Operator
Represented by two bracket symbols ([]) and has the highest precedence of all Java operators. Used to indicate the index of an array.
Initialize scanner
Scanner keyboard= new Scanner (System.in);
;
Semicolon
Selection Sort
Sorts a list of values by successively putting particular values in their final, sorted positions.
draw circle at (x, y) radius = r
StdDraw.circle(x, y, r);
What are the conditions for a method to be polymorphic?
The *polymorphic methods* are also called *overridden methods*. Overridden methods should define methods with the same name, same argument list, same list of method parameters. The return type of the overriding method can be the same, or a subclass of the return type of the overridden method in the base class, which is also known as covariant return type. Access modifiers for an overriding method can be the same or less restrictive but can't be more restrictive than the method being overridden.
Chapter 12: ______ is a compound pattern consisting of the Observer, Strategy and Composite patterns.
The Model View Controller Pattern (MVC)
inheritance
The OOP property in which a class can define a specialized type of an already existing class
polymorphism
The OOP property in which objects have the ability to assume different types.
Hardware
The Physical pieces of a computer system
What is the purpose of declaring a field private and declaring a mutator method that allows the public to change it.
The advantage of forcing the public to use a mutator method to change a field is that you can control how the field is changed.
Space Efficiency
The amount of space an algorithm uses.
Precedence
The binding power of an operator, which determines how to group parts of an expression. -- Multiplicative operators (*, / , %) have higher precedence. -- Additive operators are evaluated from left to right.
Class
The data type of an object
CPU
The device that executes the individual commands of a program
restriction for abstract class variable
There are no any restriction for abstract class variable.
Why is the method "main" Declared static?
This allows the JVM to invoke "main" without creating an object of the class
Exception
This class indicates issues that an application may want to catch. A subclass of the class Throwable.
Blueprint
This is what it is liken to when a class describes how to make an object of that class type.
Superclass
This is where a class can inherit instance variables and methods from.
Object-oriented programming
This language paradigm lets you extend a program without having to touch previously-tested, working code.
Floating Point Types
Those that contain fractional parts using significand digits and an exponent which represents its magnitude. Includes floats and doubles (32 and 64 bits respectively).
Swapping
Three assignment statements that change elements to a different index using a temporary place holder.
override
To *redefine a method* from a superclass in a subclass.
object casting
To cast an object as the appropriate class.
java.awt.*;
To paint basic graphics and images.
Why must a variable be cast?
To tell the compiler that the data conversion is safe to make
True or False: The super keyword can be used to invoke super class methods in the subclass's overloaded methods?
True.
True or False: When an object is referred to by a reference variable of a base class, the reference variable can only access the variables and members that are defined in the base class.
True.
True or False: When an object is referred to by a reference variable of an interface implemented by a class, the reference variable can access only the variables and methods defined in the interface.
True.
True or False: When implementing polymorphism with classes, a method defined in the base class may or may not be abstract.
True.
True or False: When implementing polymorphism with interfaces, a method defined in the base interface is always abstract.
True.
#104 True or false? An inner class has free access to ALL member data of its enclosing (outer) class.
True. .....
True or False: The reference type determines which members of a variable object are accessible
True. Only those members allowing access according to their access modifiers will be available to be called. Furthermore, only those available methods are candidates for polymorphic calls.
#106 True or false? This is a legal way to create an instance of an inner class: *OuterClass.InnerClass x= * *new OuterClass.new InnerClass(); *
True. This may look strange, but that syntax is how do you can create an instance of the InnerClass when you don't yet have an instance of the OuterClass. An InnerClass must ALWAYS be tied to an instance of the OuterClass
True or false, BitSets automatically grow ti represent the number of bits required by a program?
True?
What is meant by method overloading?
Two or more methods have the same name, but specify a different order or data types for parameters.
Prefix Operator
Unary operator that appears before it's operand. E.g. the negation operator '-' which negates the value to it's right. e.g. 'int negative speed = -speed;'
Buffered Streams
Use a large block of memory to store batches of data that flow into or out of a program
When using primitive types with ArrayList
Use class Integer
String operator '+'
Used for concatenation. If either operand is a String type, both operands will be turned into strings, concatenated and then added to a newly created String object. E.g. String aString = "Jon" + 2; would output 'Jon2'.
//
Used to comment out a line.
A name and a type
What must variables must always be declared with?
it should describe what to do
What should prep code should do?
Can a subclass override a method and declare fewer thrown exceptions that the superclass method?
Yes, it is legal. The overriding method does not have to declare "throws" on checked exceptions declared by the super class.
Is this allowed: interface Bounceable { public void bounce(); } abstract class Ball implements Bounceable { } // i.e., can the implementation class be abstract?
Yes. As long as the first concrete class that implements Bounceable includes the implementation for bounce(), we are good.
#132 Class Y is a sublass of class X. Will this compile? X myX = new X(); Y myY = (Y) myX;
Yes. It will compile because the myX object might really have been a Y object all along (as far as the compiler knows), but in runtime it will fail
const
You can't use this word in a Java program. The word has no meaning. Because it's a keyword, you can't create a const variable.
goto
You can't use this word in a Java program. The word has no meaning. Because it's a keyword, you can't create a goto variable.
How to change a Boolean expression from printing "false" to " incorrect" The preceding program displays a message such as "6 + 2= 7 is false" .. if you want to print " 6 + 2 = 7 is incorrect" you what must you do ?
You must use a one- way if statement.
What escape sequence makes the backspace character?
\b
New line
\n
New line character
\n
What escape sequence makes the newline character?
\n
An interface is like ...
a 100-percent 'abstract' class, and is implicitly abstract whether you type the 'abstract' modifier in the declaration or not.
Hash code
a computed key that uniquely identifies each element in a hash table.
interpreter
a computer program that translates one computer statement at a time and executes each statement as it is trasnlated
Each superclass in an object's inheritance tree will have ...
a constructor called.
just-in-time compilation
a feature of some java virtual mahcines that first translates byte codes to the machine's code before executing them
method
a group of one or more programming statemetnts that collectively has a name
graphical user interface
a means of communication between human beings and computers, that uses a pointing device for input and bitmapped screen for output. The bitmap displays images of windows and window objects such as buttons, text fields, and pull-down menus. The user interacts with the interface by using the mouse to directly manipulate the window objects
A local variable disappears when...
a method invocation ends.
a method that prints characters to the screen and remains on the same line
architecturally neutral
a program that can run on any operating system ex. Java
java virtual machine
a program that interpretes java byte codes and executes them
A ________ is used to terminate all java
a semi colon ;
'abstract' methods end in ...
a semicolon - no curly braces.
debugging
freeing the program of all errors
class
fundamental building blocks of Java programs; contains declarations of methods in which each method contains a sequence of instructions
What is the general form of the if statement?
if (condition) statement1; else statement2; The condition is any statement that returns a Boolean value
String variables name1 & name2 Write a fragment of code assigning the larger of the 2 to the variable first (NOTE: "larger" here means alphabetically larger, not "longer". Thus, "mouse" is larger than "elephant" bc "Mouse" comes later in the dictionary than "elephant"!)
if (name1.compareTo(name2) > 0 ) { first = name1; } else { first = name2; }
if statement (many commands)
if (true) { }
'abstract' methods must be ...
implemented by a subclass, so they must be inheritable.
Interfaces can be ...
implemented by any class, from any inheritance tree.
Stack class
implements a last-in, first-out stack of elements. You can think of a stack literally as a vertical stack of objects; when you add a new element, it's stacked on top of the others. When you pull an element off the stack, it comes off the top. That element is removed from the stack completely, unlike a structure such as an array, where the elements are always available.
method, which finds the index of an element based on the element itself:
indexOf("Inkster"); (example: int i = v.indexOf("Inkster"); )
\n
indicates a newline character
\t
indicates a tab character
What does the keyword, Extends, do?
indicates that the class before the keyword is an enhanced type of the class following the keyword meaning that the methods and data from the class before the keyword are added on to the methods of the class after the keyword.
void
indicates that the main() value doesn't return any value when it's called.
What is the format for a, while, statement?
initialization; while (loopContinuationCondition) { Statement increment; } ex: pg 91
'final' reference variables must be ...
initialized before the constructor completes.
What are all of the methods for Scanner objects to read in input from a user.?
input.nextLine();
The 'transient' modifier applies only to ...
instance variables.
Which operator determines whether an object matches a reference type or one of its supertypes?
instanceof
An 'abstract' class cannot be ...
instantiated.
statement
instructions that each end in a semicolon and are executed one by one when a program runs
-32 bits Range: -2,147,483,648 to 2,147,483,647 No rules
int
Generate a random integer between lowerLimit (inclusive) and upperLimit (exclusive).
int num = (int)(Math.random() * (upperLimit - lowerLimit) + lowerLimit;
Generate a random index into array "arr."
int num = (int)(Math.random() * arr.length);
What is an interface? Where have we seen these before?
interface - a collection of constants and abstract methods. - a class can implement an interface We have used the Panel interface, and interfaces with our classes - getters/setters
What is a Class
is a collection of data fields that hold values and methods that operate on those values. A class defines a new reference type.
What could a object be compared to for similarity?
like base blocks that are interchangeable in how they can be used in other programs.
&&
logical AND operator returns true if both its operands are true. E.g. 'boolean isCup = hasHandle && holdsTea;'. Otherwise returns false.
!
logical NOT operator is unary and returns the opposite of its operand. Ie. if operand is true, returns false and vice-versa. E.g. 'boolean isWoman = !hasBeard;' where isWoman would equal false if hasBeard is true.
||
logical OR operator returns if any of its its operands are true (including both). E.g. 'boolean isCool = hasCar || hasBand'.
-64 bits Range: -big to big No rules
long
primary storage
made from memory chips
A single class can implement ...
many interfaces.
Helper methods should be
marked as private
static method
method invoked WITHOUT creating an instance of the class → use "STATIC" in method declaration
next()
method retrieves the next element in a structure. (if you've implemented the iterator interface)
Method call/actual and formal for method name; No return value, no parameters
methodName(); public static void methodName():
The 'synchronized' modifier applies only to ...
methods and code blocks.
The two main kinds of methods:
methods that return a value / void methods
The 'native' modifier applies only to ...
methods.
adding a throws clause to your method definition simply means that the method _______ throw an exception if something goes wrong,
might
when writting multiple catch clauses you should always start with ______
more specific subclass exceptions and end with more general superclass exception catches (because if you start with a superclass exception catch you wont know what the specific exception was.
Device connecting a computer to a local area network (LAN).
network interface card (NIC) • LAN is commonly used in business, universities, & gov't organizations. A typical type of NIC, called 10BaseT, can transfer data at 10 Mbps.
ad hoc polymorphism
overloading and coercion are two special kinds of ad-hoc polymorphism
'final' methods cannot be ...
overridden in a subclass.
Final methods cannot be ...
overridden.
You implement an interface by properly and concretely ...
overriding all of the methods defined by the interface.
*Polymorphism* applies to ...
overriding, not to overloading.
'protected' = ...
package + kids (kids meaning subclasses)
What is the difference between pass by reference and pass by value?
pass by value - the current value of the actual parameter is copied into the formal parameter - java only does pass by value pass by reference - references an object, just looks at the values, cant edit
type
primitive: int, double, char, boolean
Prints to the current line(single function)
Applets
programs imbedded in a web page
secondary storage
provides slower and less expensive storage that persists without electricity ex: hard disk
pass arguments into constructor
public Rectangle (double len, double wid) { }
no argument constructor
public Rectangle() { }
extends
The keyword used in a class declaration to inherit another class.
super
The keyword used to call a superclass constructor or method.
Operating System
The main software of a computer.
What is the output? import static System.*; class Init { Init() { out.println("no-arg constructor"); } static { out.println("static 1"); } { out.println("instance 1"); } { out.println("instance 2"); } static { out.println("static 2"); } public static void main (String[] args) { new Init(); } }
The output will be: static 1 static 2 instance 1 instance 2 no-arg constructor
What are the conditions for a method to be polymorphic?
The polymorphic methods are also called overridden methods. Overridden methods should define methods with the same name, same argument list, same list of method parameters. The return type of the overriding method can be the same, or a subclass of the return type of the overridden method in the base class, which is also known as covariant return type. Access modifiers for an overriding method can be the same or less restrictive but can't be more restrictive than the method being overridden.
Casting
The process of explicitly converting one primitive type to another. Involves writing the desired type of an expression in parentheses e.g. '(int)'. This can result in the *loss of information* and therefore is worth avoiding by choosing appropriate types.
else if
Specifies a new condition if the first condition is false
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.
Target
The item being searched for in a search
<
Relational operator: less than
Mutators
set() methods
Naming standard for mutator method?
setXYZ();
What are the characteristics of default constructor?
* Default Constructor has the same access modifier as the class * Default Constructor has no arguments * Default Constructor includes a no-arg call to to Super Constructor ( super() )
How do you assign data to a variable?
"=". ex. int number = 100
"What is the difference between the == operator and the equals() method?"
"== compares two operands and in the case of primitives, returns true if the values are equal. In the case of Objects, it checks to see if the references are the same. The default implementation of the equals() method does the same thing but the equals method is override-able and many pre-defined classes have such overrides."
LAN
(adj.) drooping; without energy, sluggish
Network
(broadcasting) a communication system consisting of a group of broadcasting stations that all transmit the same programs
Overloading Rules: How do they differ from overriding rules?
* Overloaded methods MUST change the arguments list * Overloaded methods CAN change the return type * Overloaded methods CAN change the access modifier * " CAN declare new or broader checked exceptions
cast operator
(double),(int), third highest precedence, right to left association
Formal parameter
(i.e. Parameter) • variables defined in method signature
pass-by-value
(i.e., call-by-value) • copy of the value of the argument is passed to the method. For a parameter of a: • primitive type → actual value is passed; • reference type → reference for the object is passed
Syntax Error
- Compile error - Mistake detected by the compiler - Generally a type - ^ will indicate where the mistake is (always go up)
Source Code
- Instructions for a program Ex: public class HelloWorld{ public static void main(String [] args){ System.out.println("Hello World");} }
Double
- Name for a floating-point integer (decimals) Ex: 10.1, 9.0
- Name of message will be sent - Cursor placed right after the last character typed in the code
Println
- Name of the message will be printed out and the cursor will be placed at the beginning of the next line
Interpreter
- Program behaving like a computer Ex: JVM
Import Statement
- Program reads keyboard input using a scanner object Ex: import java.util.Scanner;
Parameter
- Sends a message to object - Between (parentheses) Ex: System.out.println("Hello World");
Statement
- Sentence in the program Ex: System.out.println("Hello World");
Program
- Sequence of instructions for the computer
Applet
- Small Java programs already translated into byte code Ex: animations on a webpage
Variable
- Storage for one value - Refers to data, value, or objects Ex: double fahrenheit
Readability
- The ability for other programmers to read and understand your program - Easier to read = easier to understand and learn
Terminal I/O User Interface
- View as seen from Java compiler - Less pleasing to the eye and harder for users to understand
What is the Iterator interface?
- defined as part of java standard class library - hasNext(), returns a boolean result and - next() returns object
What is the Comparable interface?
- defined in java.lang package - contains only one method, compare to -takes an object as a parameter and returns an integer - mechanism to compare one object to another - integer returned is negative if first object is less than 2nd - 0 if they are equal - positive if greater
Life Cycle - Blocked
-The thread is waiting for some resource...-Common reasons for blocking: waiting for input over a network or from a file, or waiting for the user
Life Cycle - Dead
-Thread execution is complete...-Cannot restart this thread...-There is a stop() method that can be used to kill a thread, but it is depreciated
Life Cycle - Active
-The state of the thread that has control of the CPU...-Only time a thread can progress...-Can go to any of the following states from here: dead, blocked, suspended, sleeping, wait, runnable
A legal non-abstract implementing class has the following properties:
1) It provides concrete implementations for the interface's methods. 2) It must follow all legal override rules for the methods it implements. 3) It must not declare any new checked exceptions for an implementation method. 4) It must not declare any checked exceptions that are broader than the exceptions declared in the interface method. 5) It may declare runtime exceptions on any interface method implementation regardless of the interface method. 6) It must maintain the exact signature (allowing for covariant returns) and return type of the methods it implement (but does not have declare the exceptions of the interface).
What two characteristics separate different overloaded methods
1) Number of parameters and 2) type of parameters
What are the rules for forming a structured program?
1. Begin with the simplest activity diagram { @->(action state)->(@)} 2. Any action state can be replaced by two action states in sequence. (A.K.A stacking rule) 3. Any action state can be replaced by any control statement. (A.K.A the nesting rule) 4. Rules 2 and 3 can be applied as often as you like and in any order.
Given the following code, which of these constructors can be added to class B without causing a compile time error? class A{ int i; public A(int x) { this.i = x; } } class B extends A{ int j; public B(int x, int y) { super(x); this.j = y; } } A. B(int y ) { j = y; } B. B(int y ) { super(y*2 ); j = y; } C. B(int y ) { i = y; j = y*2; } D. B(int z ) { this(z, z); }
1. To construct an instance of a sub class, its super class needs need to be constructed first. Since an instance can only be created via a constructor, some constructor of the super class has to be invoked. Either you explicitly call it or the compiler will add super() (i.e. no args constructor) as the first line of the sub class constructor. Now, if the super class ( here, A ) does not have a no args constructor, the call super() will fail. Hence, choices B( ) { }, B(int y ) { j = y; } and B(int y ) { i = y; j = y*2; } are not valid and choice B(int y ) { super(y*2 ); j = y; } is valid because it explicitly calls super( int ) which is available in A. 2. Instead of calling super(...) you can also call another constructor of the base class in the first line (as given in choice B(int z ) { this(z, z); } ). Here, this(int, int) is called in the first line which in turn calls super(int). So the super class A is correctly instantiated.
What can contain a mixture of implemented and unimplemented methods and must be extended to use?
Abstract class
Association
Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation. Example: A Student and a Faculty are having an association.
What is association navigation?
Association navigation is a term used to describe the direction in which a relationship can be traveled.
What, if anything, is wrong with the following code? interface T1{ } interface T2{ int VALUE = 10; void m1(); } interface T3 extends T1, T2{ public void m1(); public void m1(int x); } A. T3 cannot implement both T1 and T2 because it leads to ambiguity. B. There is nothing wrong with the code. C. The code will work fine only if VALUE is removed from T2 interface. D. The code will work fine only if m1() is removed from either T2 and T3.
B is correct. Having ambiguous fields or methods does not cause any problems by themselves but referring to such fields/methods in an ambiguous way will cause a compile time error. T3.m1() is also fine because even though m1() is declared in T2 as well as T3 , the definition to both resolves unambiguously to only one m1(). Explicit cast is not required for calling the method m1() : ( ( T2) t).m1(); m1(int x) is valid because it is a totally independent method declared by T3.
'abstract' methods are declared, with a signature, a return type, and an optional throws but are not ...
implemented.
Consider the following interface definition: interface Bozo{ int type = 0; public void jump(); } Now consider the following class: public class Type1Bozo implements Bozo{ public Type1Bozo(){ type = 1; } public void jump(){ System.out.println("jumping..."+type); } public static void main(String[] args) { Bozo b = new Type1Bozo(); b.jump(); } } What will the program print? A. jumping...0 B. jumping...1 C. this program will not compile D. it will throw a runtime exception
C. is correct. Member variables in the Interface ARE ALWAYS public, static and final. So, even though the variable is declared as follows in the Interface: int type = 0; it is actually interpreted as: public static final int type = 0; Methods in the Interface are ALWAYS public and abstract, even if you don't explicitly define them as such. In fact, you CANNOT even declare a private or protected method in the Interface block.
What will be the result of compiling and running the following code? class Base{ public short getValue(){ return 1; } //1 } class Base2 extends Base{ public byte getValue(){ return 2; } //2 } public class TestClass{ public static void main(String[] args){ Base b = new Base2(); System.out.println(b.getValue()); //3 } } A. It will print 1 B. It will print 2 C. Compile error at Line 2 D. Compile error at Line 3
C. is correct... In case of overriding, the return type of the overriding method MUST EXACTLY match the return type of the overridden method, IF IT IS A Primitive Data type. If the return type is Object, SubClasses can be returned. There is a different Flash Card for that.
Objects need to be cast when they more up or down the inheritance chain? i.e. sub to super etc.
Cast them when moving down. i.e. super to sub class.
give an example of a constructor
Circle() (( this is a member of a class that has the same name as the class and has a body))
-All programs start with a ? -Must have { and } -Identifier (name) begins with a CAPITAL letter EX: public class Westlake
Class
Chapter 2: Observable is a ____ not a interface.
Class
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.
RuntimeException
Class is the superclass of those exceptions that can be thrown during normal runtime of the Java virtual machine.
What will be printed when the following code is compiled and run? class A { public int getCode(){ return 2;} } class AA extends A { public long getCode(){ return 3;} } public class TestClass { public static void main(String[] args) throws Exception { A a = new A(); A aa = new AA(); System.out.println(a.getCode()+" "+aa.getCode()); } public int getCode() { return 1; } } A. 2 3 B. 2 2 C. It will throw Exception at runtime D. It will not compile
D is correct. Class AA is trying to override getCode() method of class A but its return type is incompatible with the A's getCode. When the return type of the overridden method (i.e. the method in the base/super class) is a primitive, the return type of the overriding method (i.e. the method in the sub class) must match the return type of the overridden method. In case of Objects, the base class method can have a covariant return type, which means, it can return either return the same class or a sub class object. For example, if base class method is: public A getA(){ ... } a subclass can override it with: public AA getA(){ ... } because AA is a subclass of A.
Cable modem = as fast as?
DSL
--
Decrement operator - Decreases the value of operand by 1 --prefix is value after decrement postfix-- is value before decrement
Code Block
Delimited by curly-brackets, enables a set of statements to be treated as a single statement.
Primitive Data Types
Eight commonly used data types.
Portable, Secure, Robust
Java is _____ (p), _______ (s), and ______ (r). - Makes Java a good language to learn/program to use
Modifier
Java keyword • Specifies the properties of data, methods, & classes + how they can be used. EX: public, private, & static.
Non-Access Modifiers
Java provides a number of non-access modifiers to achieve many other functionality. - The abstract modifier for creating abstract classes and methods. - The static modifier for creating class methods and variables - The final modifier for finalizing the implementations of classes, methods, and variables. - The synchronized and volatile modifiers, which are used for threads.
Read an int from the Scanner object and store it in an int
Java: Int varx= input.nextint();
Create a Scanner object that reads from System.in
Java: Scanner input= new Scanner(System.in)
Create a Method called methodX
Java: public static void methodX(){
break
Jumps out of a loop or switch.
Capable of compiling each byte code once, & then reinvoking the compiled code repeatedly when the byte code is executed.
Just-in-Time compiler
synchronized
Keeps two threads from interfering with one another.
What type of structure are stacks usually known as?
LIFO structures (Last-in, First-out) which means that the last item pushed onto the stack is the first to be taken off.
syntax
Language rules that govern how words can be combined to form meaningful phrases and sentences
Pi
Math.PI
When implementing a method declared in an interface or abstract class, which three techniques are available for specified exceptions?
Not throw an exception, throw the same class of the specified exception, or throw a subclass of the specified exception.
A literal of a reference variable that does not reference any concrete object.
Null
exceptions happen when you try to use a variable that doesn't refer to an object yet.
NullPointerException
||
OR Operator. If any of the boolean operands is true, the condition becomes true
Define the Java related "object" and what is it interchangeable with?
Object and class define state (data_ and behavior (operations). Classes define an object's behavior.
next()
One word String
Private variable declaration?
Only applies to that class. ex. private String first;
create object with constructor
Rectangle r = new Rectangle();
What are common errors # 3 with selection statements ?
Redundant testing
!=
Relational operator: not equals
Will this code compile and execute? class Animal { } class Dog extends Animal { } class DogTest { public static void main(String[] args) { Animal a = new Animal(); Dog d = (Dog) a; } }
This code will compile but throw a runtime error with ClassCastException. Compiler is forced to trust us when we do the downcast even though we can mess things up... As long as the class is in the same inheritance tree, it will allow during compilation. But, the following will not work: String s = (String) a; // because String s is not in the same inheritance tree
prepcode, test code and real (Java) code)
Three things to write when designing a new class
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.
Which keyword is used declare a class that provides interface implementation?
implements
An interface can have only ...
abstract methods, no concrete methods allowed.
Graphical user interfaces (GUIs)
allow users to interact with a program in a graphical environment
concatenation operator
allows strings to be combined in Java
high-level programming language
allows you to use a vocabulary of reasonable terms instead of sequences of 1s and 0s
compile-time error
an error in which the compiler detects a violation of language syntax rues and is unable to translate the source code to the machine
The assert keyword must be followed by one of three things:
an expression that is true or false, a boolean variable, or a method that returns a boolean.
object-oriented programming
an extension of procedural programming in which you create classes, creating objects for those classes, and creating applications for the object
statement
an individual instruction in a program
HAS-A means ...
an instance of one class "has a" reference to an instance of another class or another instance of the same class.
out
an object that provides a way to send output to the screen
Members accessed without a dot operator (.) must ...
belong to the same class.
Binary Seach
binarySearch(array, lowerboundIndex, upperboundIndex, key) public static void binarySearch(int[ ] array, int lowerbound, int upperbound, int key) { int position; position = ( lowerbound + upperbound) / 2; while((array[position] != key) && (lowerbound <= upperbound)) { comparisonCount++; if (array[position] > key) // If the number is > key, .. { // decrease position by one. upperbound = position - 1; } else { lowerbound = position + 1; // Else, increase position by one. } position = (lowerbound + upperbound) / 2;
Bubble Sort
boolean flag = true; int n []; for (int i = 0; i < n.length; i++) { if(!flag) break; flag = false; for(int j = 0; j < n.length - i; j++) { if(numLis[n] > numList[i+1] { int temp = numList[i]; numList[i] = numList[i++]; flag = true; } }
Example of how to get the value of a individual bit in a set:
boolean isWriteable = connex.get(ChannelAttributes.WRITABLE);
Example using conditional operator
boolean someCondition = true; result = someCondition ? value1 : value2;
Logical Type
boolean, with literals 'true' and 'false'. A logical variable can hold the result of a *logical expression*.
*HAS-A* relationship is demonstrated
by a *class that contains another class*.
*IS-A* relationship is demonstrated
by a class derived from an existing class.
Use an Addition assignment operator to make c=5 when c=2
c += 3
Make c not equal to b
c!=b
Use a remainder assignment operator to make c=3 when c=12
c%=9
Use a multiplication assignment operator to make c=8 when c=2
c*=4
Use a subtraction assignment operator to make c=5 when c=7
c-=2
semantics
define the rules for interpreting the meaning of statements
Abstract classes have constructors that are ...
called when a concrete subclass instantiated.
Local variables don't get ...
default values, so they must be initialized before use.
What is the format for a, for, statement?
for (initialization;loopContinuationCondition;increment) statement (Initialization=declared variable and value) (loopContinuationCondition=i<5) (Statement=(println)
Loop count to 10
for(count = 0; count<11: count++);
import Scanner class
import java.util.Scanner;
All instances shares ...
only one copy of a 'static' variable/class.
( )
opening/closing parentheses; used in a method header
+
operator to concatenate strings
With *three interfaces A, B, and C* what is the proper signature for interface A *inherits* interfaces B and C?
public interface A extends B, C {}
Members can use all four access levels:
public, protected, default, private.
Which three modifiers are implicit for fields declared in an interface?
public, static, and final
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.
" "
quotation marks; encloses a string of characters, such as a message that is to be printed on the screen
What keyword is used to jump out of a try block and into a finally block?
return
What are hard disks made of?
rotating platters which are coated with a magnetic material and read/write heads, which can detect and change the magnetic flux on the platters
objects
second category of Java variables such as scanners and strings
A class with public access can be ...
seen by all classes from all packages.
A class with default access can be ...
seen only by classes within the same package.
;
semicolon; marks the end of a complete programming statement
string
sequence of characters enclosed in quotation marks
program
sequence of instructions and decisions
algorithm
sequence of steps that is unambiguous, executable, and terminating
Calling a thread's _____ method causes its _____ method to be called
start() & run()
Polymorphism could be
static and dynamic both. Overloading is "static polymorphism" while, overriding is "dynamic polymorphism". Static Binding/Early binding/Method overloading. (in same class) Dynamic binding/Runtime binding/Method overriding. (in different classes.)
Thread creation example
static public void main(String [] args) { // Not necessary to use an array Thread [] thAry = new Thread[3]; for(int i = 0; i < 3; i++) { Thread th = new MyThread(i); // create the thread thAry[i] = th; th.start(); // start the thread running } ... }
Runnable creation example
static public void main(String [] args) { for(int i = 0; i < 3; i++) { Runnable r = new MyRunnable(i); // create the Runnable object Thread th = new Thread(r); // create the thread for the object th.start(); // start the thread running }
assignment statement
stores a new value in a variable, replacing the previously stored value; doesn't start off with indication of a type
transistors
structural elements that make up a processor
What is the class before the keyword, extends called? the one after?
subclass Superclass
A 'final' class cannot be ...
subclassed.
Default and 'protected' members differ only when ...
subclasses are involved.
All classes (except class Object), are ...
subclasses of type Object, and therefore they inherit Object's methods.
programming
the act of designing and implementing computer programs
passing arguments
the act of sending an argument to a method
The capacity of a vector is:
the amount of memory allocated to hold elements, and it is always greater than or equal to the size.
'private' methods can be accessed only by ...
the code in the same class.
expression
the combination of variables, literals, operators, and/or method calls
'this .' always refers to ...
the currently executing object.
Cohesion refers to ...
the degree in which a class has a single, well-defined role or responsibility.
Coupling refers to ...
the degree to which one class knows about or uses members of another class.
Loose coupling is ...
the desirable state of having classes that are well encapsulated, minimize references to each other, and limit the breadth of API usage.
How does the substring() method of the String class work ?
the first argument specifies the index of the first character to include, the second argument indicates the index of the last character plus 1. A call to substring(2, 5) for a string would return the characters from index position 2 to index position 4.
argument
values the method needs to carry out its task; enclosed in parenthesis; multiple of these are separated by commas
variable = variable *X
variable *=X
Method call/actual and formal for method name; Return value, no parameters
variableName = methodName(); public static int methodName():
Local Variables
variables declared within a method or, more accurately, within a code block. These variables can only be used within the code block scope. They aren't initialised by default, so should be initialised by hand !.
What are static variables?
variables local in a static method
Reference type determines ...
which overloaded method will be used at compile time.
Object type (not the reference variable's type), determines ...
which overridden method is used at runtime.
Postdecrement
x-- "Give me x, then decrement"
short type
represents an integer in the range from -215 (-32768) to 215-1 (32767) • Primitive
Chapter 1: Good OO designs are
reusable, extensible and maintainable
Overloading means ...
reusing a method name, but with different arguments.
How do we test things?
review - many people meet and examine/evaluate a code defect testing - test suite, a variety of user inputs and actions We should know the desired output first
inheritance
the ability to create classes that share the same attributes and methods of existing classes but with more specific features
byte code
the kind of object code generated by a java compiler and interpreted by a java virtual machine. Its platform is independent
source code
the program text as viewed by the human who creates or reads it, prior to compilation
syntax
the rules for combining words into sentences
It is legal to declare a local variable with ...
the same name as an instance variable; this is called shadowing.
vocabulary
the set of all of the words and symbols in a given language
Java Virtual Machine (JVM)
the software that Java runs on allowing to to be architecturally neutral
Pascal Casing or upper camel casing
the style that joints words in which each begins with an uppercase letter
Instance members are accessible only after ...
the super constructor runs.
What are switch statements?
the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types ex. switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break;
assignment operator
the symbol =, which is used to store a value in a variable
Low cohesion is ...
the undesirable state of a class whose members support multiple, unfocused roles or responsibilities.
state
the values and properties of an object
method
the verbs of a program
No classes instances are needed in order to ...
use 'static' members of the class.
What is method overloading? How do we accomplish this?
using the same method name with different parameter lists for multiple methods example, these two methods with same name can be used. public int sum(int numb1, int numb2){ } public int sum(int numb1, int numb2, int numb3){ }
How would you wipe out all of a the elements inside of a vector named "v"
v.clear();
Example of how to remove items from a vector:
v.remove(3);
example of how to change a specific element :
v.set(1, "Kung");
What must be used in an if statement of more than 1 line of code must be used ?
{}, code must be put inside curly brace block
Reading from Text Files
~Uses Reader class ~BufferedReader: Provides buffered text stream reading ~FileReader: Connects an input stream to file
Writing to Text Files
~Uses Writer class ~BufferedWriter: Writes text to text output streams and provides buffering ~PrintWriter: Uses methods to write formatted data to output streams ~FileWriter: connects an output stream to a file
ArrayList Methods
~add(object): adds to end of list ~add(index, object) ~set(index, object) - replaces ~get(index) ~remove(index) size() isEmpty() - boolean clear() - removes all elements
String Class Methods
~length() ~substring(starting pos(, ending pos)) ~toUpperCase(), toLowerCase() ~charAt() ~equals()
The amount of space bw pixels. If higher/lower = better resolution
• Dot pitch • Smaller the dot pitch → better the display.
contains the class of exception to be caught and a variable name.
catch clause
Methods that use instance variables
causes objects of the same type to behave differently
/b
causes the cursor to back up, or move left, one position
CPU
central processing unit; performs program control and data processing; fetches data from external memory or devices and places processed data into storage
null reference example
class NameIsEx { String name; void printName( ) { System.out.println (name.length ( ) ); } }
What cases do class names and variable names start with?
class: start with uppercase variable: start with lowercase (think camel), cannot start with a number, have spaces, or use symbols /
The 'strictfp' modifier applies only to ...
classes and methods.
package
collection of classes with a related purpose
Interfaces can have ...
constants, which are always implicitly 'public', 'static', and 'final'.
no argument constructor defined
constructor passed with no parameters; boolean = false; strings = null, numerical values = 0
default constructor defined
constructor that is created if none already has been
method
contains a collection of programming instructions that describe how to carry out a particular task
class files
contains instructions for the Java virtual machine
method, which simply checks whether an element is in the vector:
contains() (example:boolean isThere = v.contains("Webb");] )
Interfaces are ...
contracts for what a class can do, but they say nothing about the way in which the class must do it.
//
double slash; marks the beginning of a comment (a statement ignored by the computer)
There are two types of reference variable casting: ...
downcasting and upcasting.
During runtime, only overridden instance methods are ...
dynamically invoked based on the real object's type.
keywords
each languages limited vocabulary
what is the path from editor to a running program?
editor > source code/source file > compiler > class files > virtual machine > running program?
memory chips
electronic circuits that can store data, provided they are supplied with electric power; make up primary storage
Method returning true if this string is = to string 2
equals(s1)
run-time error
error in which the program is syntactically correct and does something, but it doesn't do what it is supposed to do; caused by logical flaws in the program; also known as logic errors
exception
error message from the Java virtual machine
eval
eval() evaluates expressions
What is a conditional expression ?
evaluates a condition based on an expression
Which keyword is required when declaring a concrete class of an abstract class?
extends
Which keyword is used to specify that a class cannot be extended, a field is a constant value, or a method cannot be overridden?
final
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.
a Boolean value that represents one of a group of on/off type states in a program.
flag
-32 bits Range: -big to big -Must put an f at the end of the value EX: 98.6f; <--- f won't print
float
Consider: o1 and o2 denote two object references to two different objects of the same class. Which of the following statements are true? Select two: A. o1.equals(o2) will always be false. B. o1.hashCode() == o2.hashCode() will always be false. C. o1 == o2 will always be false. D. Nothing can be said about o1.equals(o2) regarding what it will return based on the given information. E. Nothing can be said about o1 == o2.
C and D are correct Note that both equals() and hashCode() methods can be overridden by the programmer so you can't say anything about what they will return without looking at the code. The == operator compares whether the two references are pointing to the same object or not. Here, they are not, so it returns false. equals could have been overridden, so nothing can be said about choice D.
Instance Variables
A variable declared at the class level (such as size) is called an instance variable Each time a Dog object is created, a new memory space is reserved for variable size in this particular object The objects of a class share the same method definitions, but each object maintains its own (different) values for its instance variables, and thus its own state
The for Statement
The increment section can perform any calculation: for (int num = 100; num > 0; num -= 5) System.out.println (num); A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance
Difference between & and &&
& is bitwise. && is logical. & evaluates both sides of the operation. && evaluates the left side of the operation, if it's true, it continues and evaluates the right side.
Constructor vs Method
A Constructor is a member function of a class that is used to create instances of that class. It has the same name of the class itself, has no return type and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, return type (which may be void), and is invoked using the dot operator.
abstract data type vs abstract class
A java abstract class is a class with at least one abstract method and no body. An abstract data type is a specification of a type's operations that could be implemented in any object oriented programming.
Method Declaration
A method declaration specifies the code that will be executed when the method is invoked (called) When a method is invoked, the flow of control jumps to the method and executes its code When complete, the flow returns to the place where the method was called and continues The invocation may or may not return a value, depending on how the method is defined
The Return Statement
The return type of a method indicates the type of value that the method sends back to the caller; void type means it does not return a value A return statement specifies the value that will be returned return result; The expression must be compatible with the return type in the method header You must use an explicit cast when the return type is smaller than what you are trying to return Even if the method has a non-void return type, the return value can be ignored
Create a math program that generates to random numbers to be added together .
This shows how the use of boolean or true/false is used in the answer
Let's write a program to read a series of integer values from the user, sums them up, and computes their average
What variables do we need to maintain? -Current value from the user input -The sum of values entered so far -The number of values entered so far A sentinel value is a special input value that represents the end of input
What is the format of System.out.printf("%3d#%2s#%3.2f\n", 1234, "Java", 51.6653);
displays 1234#Java#51.67
An example of a for loop:
for (int count=1; count <= 5; count++) System.out.println (count); The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times
Switch Example 2
int i=2; switch (option) { case 1: Statement; case 2: Statement; case 3: Statement; }
What is the code to generate a random number between 0-9?
int math=(int)(Math.random() *10); System.out.print(math)
An example of a switch statement:
switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; default: misc++; }
The while Statement
A while statement has the following syntax: while ( condition ) statement; If the condition is true, the statement is executed then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false An example of a while statement: int count = 1; while (count <= 5) { System.out.println (count); count++; } If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times
Quick Check: Data Conversion
An int type can not store a float value Can fix it with casting to perform the narrowing conversion: int i = (int) 10.0/5 Output: 2
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 int dollars = 20; double money = dollars;// OK long y = 32; int x = y; // won't compile
Autoboxing
Autoboxing is the automatic conversion of a primitive value to a corresponding wrapper object: Integer obj; int num = 42; obj = num; The assignment creates the appropriate Integer object The reverse conversion (called unboxing) also occurs automatically as needed Integer obj = new Integer(45); int num; num = obj; The assignment extracts the int value from obj
Casting
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 Example of widening conversion: int total = 50; float result = (float) total / 6; (reads float, then division, then equals) Without the cast, the fractional part of the answer would be lost
What is the difference between composition vs aggregation.
Composition, is when a type is composed of another type, the complete existence of that component type's objects is controlled by the composing type's object; The components are uniquely bound to it and cannot be changed by any outside object. Aggregation, the component elements exists outside the collection, can be changed by other classes, and may even be components of other aggregates.
Lexicographic Ordering
If all characters are in the same case (upper or lower), the lexicographic ordering is the same as alphabetic ordering, therefore "book" comes before "bookcase" Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode Also, short strings come before longer strings with the same prefix (lexicographically)
What is a package?
It is a namespace, a name for a group of classes, interfaces and enum types that can be used to distinguish those from other classes, interfaces and enum types of the same name.
Enumerated Types
Java allows you to define an enumerated type, which can then be used as the type of a variable An enumerated type declaration lists all possible values for a variable of that type The values are identifiers of your own choosing The following declaration creates an enumerated type called Season enum Season {winter, spring, summer, fall}; Any number of values can be listed Once a type is defined, a variable of that type can be declared: Season time; And it can be assigned a value: time = Season.fall; The values are referenced through the name of the type Enumerated types are type-safe - you cannot assign any value other than those listed An enumerated type is a special type of class, and each variable of that type is an object The ordinal method returns the ordinal value of the object The first value in an enumerated type has an ordinal value of 0, the second 1, and so on time.ordinal(); // 3 The name method returns the name of the identifier corresponding to the object's value time.name(); // "fall"
The break Statement
Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case
Difference between public, protected and private?
Public: are globally accessible. Protected: are accessible by classes and subclasses. Private: are accessible only from its own class.
Repetition Statements
Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: while, do, and for loops
What is the result of the conditional expression above?
Result is the conditional expression is EXPRESSION1 if BOOLEAN-EXPRESSION is true; otherwise the result is EXPRESSION2
Data Conversion
Sometimes it is convenient to convert 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 generate a value as part of a computation
The Conditional Operator
The conditional operator evaluates to one of two expressions based on a boolean condition Its syntax is: condition ? expression1 : expression2; If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression The conditional operator is similar to an if-else statement, except that it is an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger May serve as a shortcut for if-else statement
Formatting Parameters
The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number DecimalFormat fmt = new DecimalFormat("0.###"); -0 means at least one digit should be printed to the left of the decimal point (.), and should be a zero if the integer portion of the value is zero -### means the fractional part of the value should be rounded to three digits (trailing zeros are not printed) format method in the DecimalFormat class can then be used to format a particular value fmt.format(2.0/3); // "0.667" fmt.format(3.3/6); // "0.55"
Wrapper Classes
The java.lang package contains wrapper classes that correspond to each primitive type: The following declaration creates an Integer object which represents the integer 40 as an object int age = 40; Integer ageWrap = new Integer(age); An object of a wrapper class can be used in any situation where a primitive value will not suffice Unwrap a wrapper value int age = ageWrap.intValue(); Other wrapper classes have similar methods Wrapper classes also contain static methods that help manage the associated type The Integer class contains a method to convert an integer stored in a String to an int value: String str = "234"; int num = Integer.parseInt(str); The Double class contains a method to convert a double value stored in a String to an double value: double d = Double.parseDouble("30.24");
A loop can also be used for input validation, making a program more robust
The number of games won must be greater than or equal to zero and less than or equal to the total number of games played