JAVA FINAL 4

Ace your homework & exams now with Quizwiz!

Hash Table

An array used for hashing.

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.

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.

JRE

An environment used to run Java Applications. Contains basic client and server JVM, core classes and supporting files.

bug

An error in the code

Off-by-one Error

An error that occurs because indexes begin at zero and not one.

Run-time error

An error that occurs when a program asks the computer to do something that it considers illegal, such as dividing by 0

Mixed expression:

An expression that has operands of different data types.

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.

Peripherals

An input device, output device, or secondary storage device that is not part of the central processing unit (CPU)

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.

Object

An instance of a class.

Statement

An instruction you give a computer.

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

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.

Element

An item in an Array.

Attributes and Behaviors

An object contains these two things.

Exception

An object defining a problem that can usually be fixed

array

An object that is a simple but powerful way to group and organize data.

New operator

An operator that constructs new objects

Unary operator:

An operator that has only one operand.

Binary operator:

An operator that has two operands.

&&

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

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

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 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 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

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

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

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

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

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

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

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

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

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

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

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

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 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 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

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

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

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

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: 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

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 must every line of code not followed by curly braces end in?

";"

How do you assign data to a variable?

"=". ex. int number = 100

&&

"And" operator

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.

||

"Or" operator

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."

Methods and instance (non-local) variables are known as ...

"members".

When defining a method, the _____ parameter is a name used for the calling object.

"this."

remainder

%

System.out.Printf("%3d", i*j)

% /number of spaces taken up/ Integer, variable

remainder or modulus operator

%, fourth highest precedence, left to right association

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.

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))

Logical Operators

&& ||

Integer value: 48

'0'

Integer value: 65

'A'

Integer value: 97

'a'

An 'abstract' class can have both ...

'abstract' and non-abstract methods.

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'.

Classes can also be modified with ...

'final', 'abstract' and 'strictfp'.

'abstract' methods cannot be ...

'private' or 'final'.

Interface methods are by default ...

'public' and 'abstract' - explicit declaration of these modifiers is optional.

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.

grouping operator

( ), highest precedence

Method Selector

(.) - Selects the method

Assignment Operator

(=) - Assigns right side to left side Ex: celsius = (fahrenheit + 32)

How do you create variables?

(A kind of variable) (name of the variable) = (value of variable); For example, String var = "Hello, World";

{ }

(Curly braces). Marks the beginning and end of a unit, including a class or method description.

Mutator method

(Setter) - changes the value of a private field of an obj.

LAN

(adj.) drooping; without energy, sluggish

str.equals("test")

(boolean) returns true if the string "test" matches string str, false otherwise

Network

(broadcasting) a communication system consisting of a group of broadcasting stations that all transmit the same programs

cast operator

(double),(int), third highest precedence, right to left association

Actual parameter

(i.e. Argument) • the variables or data to substitute formal parameters when invoking a method

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

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 )

Cast

(typeName) expression

What operator multiplies two numbers?

*

Software Layers and responsibilities

* Presentation Layer - rendering the user interface, responding to user event, creating and populating domain objects, and invoking the business layer. * The Business Layer - managing workflow by coordinating the execution of services located in the service layer. * The Service Layer - service interfaces and implementations, the movement of objects in and out of the application, and the hiding of technology choices. * The Domain Layer - abstracting domain objects (i.e., the nouns) as they appear in the problem space. Data types for: user interface ->> Presentation Layer; manage use case workflow ->>Business Layer; move objects in and out of application ->>Service Layer; abstract the "nouns" of problem space ->> Domain Layer

multiplication operator

*, fourth highest precedence, left to right association

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

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

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

Syntax Error

- Compile error - Mistake detected by the compiler - Generally a type - ^ will indicate where the mistake is (always go up)

System.out

- Computer sends message out to screen

;

- Ends a statement - Acts like a period

Source Code

- Instructions for a program Ex: public class HelloWorld{ public static void main(String [] args){ System.out.println("Hello World");} }

Byte Code

- Java compiles code into ____ first - Unique to Java

.Java

- Java file created by user

Double

- Name for a floating-point integer (decimals) Ex: 10.1, 9.0

Integer

- Name for a whole number Ex: 4, 10

Print

- 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

Thread

- Process that can run at the same time with another process

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

To create a subclass, use the ____ keyword. A) inherits B) implements C) interface D) extends

Ans: D Section Ref: 10.2

Applet

- Small Java programs already translated into byte code Ex: animations on a webpage

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

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

.Java~

- This file cannot be used for anything

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

subtraction operator

-, fifth highest precedence, left to right association

unary minus operator

-, third highest precedence

Predecrement

--x "Decrement, then give me x"

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

Runnable vs Thread

-Extend Thread...-Implement Runnable. Implementing Runnable allows you to extend another thread

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

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 - 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

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 - 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

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

LinkedList: add item to beginning of list

-addFirst(item);

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

method selector operator

., second highest precedence, left to right association

Anatomy of a Java Statement

...

Defining Parameters

...

How to use sub-string function?

...

Java Environment

...

Java reserved keywords

...

Method call/actual and formal for method name; Return value, no parameters

...

The Parts of a typical class

...

UML Notation

...

Work with ArrayList Objects and Their Methods

...

This method is present in all exceptions, and it displays a detailed error message describing what happened.

.getMessage() method

What operator divides two numbers?

/

division operator

/, fourth highest precedence, left to right association

What symbols are used to make comments in Java? (Both single and block comments)

// and /* */

How do you make a comment?

//Comment /*Multi-Line Comment*/ /**JavaDoc Comment *Describes Program or *Method **/

Test extends Base ( gọi hàm tạo )

0 tham số và 2 tham số

random number between 1 and n

1 + Math.random() * n;

byte

1 byte, stores an integer

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);

Test extends Base ( gọi hàm )

1 tham số và 2 tham số

There are three access modifiers:

1) 'public' 2) 'protected' 3) 'private'

What are checked & unchecked exceptions.

1) Checked Exception is required to be handled by compile time while Unchecked Exception doesn't. 2) Checked Exception is direct sub-Class of Exception while Unchecked Exception are of RuntimeException.

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

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

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).

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

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

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.

Name 3 reasons why favor composition over inheritance

1. Almost all inheritance can be rewritten 2. Less about modeling the real world and more about modeling interactions in a system and roles and responsibilities 3. Inheritance is difficult to maintain V52

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.

Describe 2 classes can have.

1. Is a - inheritance 2. Has a - composition / aggregation V47

Create an array called 'colors' and add to it :"red","blue", "Green" 2. 1. Create a foreach loop the writes out the contents of the arra

1. String[] colors = new String[] {"red","blue", "Green"}; 2. for (String c : colors){ System.out.println(c); } v42

Name to things about strings in Java.

1. Treated like a primitive type (can be assigned w/o the New keyword) but it's an object 2. They're immutable (can't be changed). If you give a string a different value, it create an new string in memory. Java Fundamentals - v22

class Q6 ( Holder )

101 ( tăng 1 so vs held gốc )

Reasons to use "double"

1023 digits after the decimal point

Reasons to use "float"

127 digits after the decimal point

short

16 bit integer

short

2 bytes, stores integer values

JDBC supports

2-tier and 3-tier

2000

20 + '0' + 0=

The RGB values of Color.RED

255, 0, 0

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

int

32 bit integer

float

32 bit real number

int

4 bytes, stores integer values

float

4 bytes, stores less precise floating-point numbers

long

4 bytes, stores long integer values

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 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

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 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

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

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

Moden can transfer speed up to ______

56,000 bps (bits per second).

long

64 bit integer

double

64 bit real number

What is the ASCII value of 'A'?

65

byte

8 bit integer

double

8 bytes, stores floating-point numbers

What is the ASCII value of 'a'?

97

In Java, every program statement ends with what?

; (a semicolon)

What is the end of file indicator for windows? and for UNIX/Linux/Mac OS X?

<Ctrl> z <Ctrl> d

Assignment/Declaration

<type> <name> = <expression> Declares a variable (names it), and assigns it a value.

What are 6 assignment operators?

= += -= *= /= %= ----------------- v20

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

== != > >= < <=

Make g conditional upon some statement

?:g

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.

Identifier:

A Java identifier consists of letters, digits, the underscore character ( _), and the dollar sign ($), and must begin with a letter, underscore, or the dollar sign.

Bit

A binary digit 0 & 1. • binary numbers = #'s consists of 0's & 1's.

true or false

A boolean value can be ____ __ _____

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.

Programs

A class that can be used as a template for the creation of new objects.

Subclass

A class that inherits from another class.

Superclass

A class that is inherited from.

Nested Classes

A class written inside another class Enclosing Classes The class that the nested class is nested in

String

A collection of characters. Surrounded by double quotation marks.

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.

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

Screen coordinate system

A coordinate system used by most programming languages in which the origin is in the upper-left corner of the screen, window, or panel, and the y values increase toward the bottom of the drawing area

int

A data type of integers (whole numbers).

boolean

A data type of logical values (true, false).

double

A data type of real numbers (1/2, 99.9, -0.1).

char

A data type of single characters ('a', 'b', '?').

boolean

A data type that represents a true or false value.

double

A data type that represents decimals.

int

A data type that represents whole numbers.

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

Source file:

A file containing the source code, having the file extension .java.

Method

A group of Attributes and Behaviors.

OOP Program

A group of objects that work together to get something done.

Method

A group of programming statements given a name.

Array

A group of related variables that share the same type and are being arranged.

What is a 'set' in Java?

A grouping like a LIST but all the items are unique. There are no duplicates.

What's a list in Java?

A grouping that is ordered, sequential & can have duplicates.

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.

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.

String

A line of text that can include letters, numbers, punctuation, and other characters.

Anonymous inner class

A local class whose definition and use are combined into a single expression

Variable

A location in memory used to hold a data value.

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) }

Class

A master copy of the object that determines the attributes and behavior an object should have.

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:

Named constant:

A memory location whose content is not allowed to change during program execution.

Variable:

A memory location whose content may change during program execution.

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.

b()

A method called b

return

A method can have only one of these.

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);

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

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

Abstract Method

A method that does not have an implementation (no body of code defined)

What's a method?

A mini-program that is referred to by the program and others.

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.

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}}

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.

Java bytecode

A platform independent instruction set that's produced when Java source code is compiled.

Java Virtual Machine (JVM)

A platform-targeted runtime environment that knows how to execute Java bytecode.

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

What is a requirements document?

A precise specification of what the software should do.

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

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

Programming:

A process of planning and creating a program.

Browser

A program that allows the user to find and view pages on the world wide web.

Platform Independent

A program that does not have to be written for a specific operating system.

Application

A program that runs locally, on your own computer.

Applet

A program that runs on a web page.

Assembly Language

A programming language that uses letters and numbers to represent machine language instructions

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.

An object is this type of variable

A reference variable

this Reference

A reference variable that lets an object refer to itself

Fourth-generation language

A report generator is a type of:

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.

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"); }

String

A sequence of characters

Computer program:

A sequence of statements whose objective is to accomplish a task.

Escape Sequence

A sequence used to represent special characters.

The Java Software Development Kit (JDK)

A set of command line tools (e.g., compilers, de-compilers, debuggers) used to develop Java programs. The JDK also contains the JRE, which contains the JVM.

The Java Runtime Environment (JRE)

A set of libraries that define the application programming interface (API) of the Java language. The JRE also contains the JVM application.

Programming language:

A set of rules, symbols, and special words.

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

Data type:

A set of values together with a set of operations.

Expression

A simple value or a set of operations that produces a value.

char

A single character

Iteration

A single trip through a loop.

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

Empty String

A special string literal, denoted by "".

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.

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.

Assignment Statement

A statement assigning a value to a variable.

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.

Variable

A storage place that can hold information, which may change.

Pseudocode

A stylized half-English, half-code language written in English but suggestion Java code

Control structure

A syntatic structure that controls other statements. Ex. A for loop.

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.

.....How would a three dimensional array be declared as? (How would it look like?)

A three dimensional array would be declared as int[ ][ ][ ] threeDArray.

appletviewer

A tool included in the JDK that's supported in NetBeans, which will test applets.

Statement

A unit of executable code, terminated by a semi-colon.

Attribute

A value an object stores internally.

Boundary Condition

A value at which two equivalence classes meet. ex: (exsampleClassA >= 0 || > exsampleClassB)

null

A value of no value

Literal

A value represented as an integer, floating point, or character value that can be stored in a variable.

Array Element

A value stored in an array.

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

Local variable

A variable declared inside a method that is accessible only in that method.

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]

Multi-thread

A way for the computer to do more than one thing at the same time.

Method

A way of doing something

Object

A way of organizing a program so that it has everything it needs to accomplish a task.

Method

A way to accomplish a task in a Java program.

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.

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

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.

name [row] [col]

Access an element

Private instance variables can be accessed from outside their class through ______ methods and changed with _________ methods

Accessor methods && Mutator methods

J2EE

Acronym for Java 2 Platform, Enterprise Edition.

J2ME

Acronym for Java 2 Platform, Micro Edition.

J2SE

Acronym for Java 2 Platform, Standard Edition.

Expliciete cast

Actie van een programmeur om een variabele te converteren naar een beperktere type.

+=

Add and assign operator

Concatenation

Adding one string to another.

+

Addition

Scanner input = new Scanner(System.in);

Adds scanner to program

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

.java

All Java file names have to have this extension.

Capital Letter

All java file names must have this at the beginning.

8 primitive data types

All of Java's numeric primitive data types are signed. Boolean (1 bit): true, false char (2 bytes): Unicode characters, ranging from 0 TO 65,535 byte (1 byte): -128 to 127 short (2 bytes): -32,768 TO 32,767 int (4 bytes): -2,147,483,648 TO 2,147,483,647 long (8 bytes): -9,223,372,036,854,775,808 TO +9,223,372,036,854,775,807 float (4 bytes): 1.40129846432481707e-45 TO 3.40282346638528860e+38 (+ or -) double (8 bytes): 4.94065645841246544e-324d TO 1.79769313486231570e+308d (+ or -)

Equivalence Class

All the sets of test data that exercise a program in the same manner ex: all data types listed.

Protected

Alleen toegankelijk binnen de class zelf en binnen de kinderen of kleine kleinkinderen van die class.

flow control structures

Allow different segments of code to be executed under different circumstances. Keywords : if...else, switch..case (all selection statements).

Casting

Allows you to convert a data type into another one; you can change a double to an int by typing (int) 3.25.

What are bounded types in Java?

Allows you to restrict the types that can be used in generics based on a class or interface. v60

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.

Argument Storage

An Array.

...

An ArrayList object can have any element in it removed and will automatically move the other elements.

...

An ArrayList object can have its internal capacity adjusted manually to improve efficiency.

modular application

An application that uses components that are separately written and maintained.

client code

An application that uses one or more classes.

Constructors are special methods defined in a class that are used to initialize ___ ___.

Answer: object instances Constructors must have the same name as the class name; the class Book will have constructors named Book (must be identical). Constructs are not allowed to explicitly declare that they return a type; rather, the implicit type they return is the enclosing class type in which they're defined.

char

Any character. Surrounded by single quotation marks.

String Literal

Anything within double quotation marks.

API

Application Program Interface (API) • Set of classes & interfaces that can be used to develop Java programs.

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

ArrayList<String>: Instantiation

ArrayList <String> myArr = new ArrayList<String>();

ArrayList<String> friends = new ArrayList<String>();

ArrayList<typeParameter> variableName = new ArrayList<typeParameter>(); typeParameter cannot be a primitive type

One-Dimensional Array

Arrays that store a simple list of values.

prompt

Asks the user a question

=

Assignment

=

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.

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

a thread's run() method

At line 2, ..stop running. It will resume running SOME TIME...

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

SomeException

B fail A suceed

A ext Objectl B ext A; C ext B, java.io.Serializable

B must have no-args constructor

Name 9 primitive types

BSILF DB CS byte short int long float double boolean char String

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()

UML Diagrams - list the behavior diagrams

Behavior Diagrams - STIACUS Sequence Timing Interactive Activity Communication Use Case State

Final

Behoudt gedurende het hele programma dezelfde waarde

Thread safe

Beveiligd tegen ongewenste effecten van asynchrone bewerkingen.

&

Bitwise And operator

~

Bitwise Not operator

|

Bitwise Or operator

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

Scope

Block of code in which a variable is in existence and may be used.

main()

Block statement statement in which all of the program's work gets done.

==

Boolean equals

!

Boolean not

!=

Boolean not equal to

&&

Boolean operator meaning both sides have to be true. A Short circuiting logical operator.

||

Boolean operator meaning only one side has 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

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

Engaging in OOP

Breaking down computer programs in the same way a pie chart is broken down.

static fields and methods

By default, data members and methods are "instance" members and are said to be "non static." Non static instance data members are copied to each object instance of the class, so each object has its own copy. Non static methods can reference these copied data members through an implicit object reference (but you can access it via "this" when necessary). The concept of non static instance members is illustrated below. public class Book { private String title = ""; public void setTitle(String title) { this.title = title; } } When there's a need to not copy data members to each object instance, such as constants. They can remain in the class definition. Data members and methods that are not associated with object instances are call "class" members; they are local to the class and are not affiliated with the objects. Annotated with the keyword "static": public static final int CHECKOUT_DURATION = 21; Because the above data member is a class variable, it can be accessed through the class name as follows: int duration = Book.CHECKOUT_DURATION; Methods can also be designated as static: private static int nextId = 1; public static int getNextId() { return nextId++; } Above, method getNextId() provides access to the static data member and manages its next value. IMPORTANT: "static only sees static" but "non-static sees everything" static members can only access other static members; in particular, static members cannot access non-static members. Non-static members have access to all members (both static and non-static).

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.

A ext Objectl B ext A; C ext B, java.io.Externalizable

C must have no-args constructor

Objects example illustrated

CLASS Book title: String author: String isCheckedOut: boolean checkOut(): void checkIn(): void If a user checks out 2 books, each of them are assigned the class properties: Book Book title: Call of the Wild title: Gone with the Wind author: J. London author: M. Mitchell isCheckedOut: true isCheckedOut: true class is a type, and objects are instances of those types

Hash Function

Calculates the hash code from properties of the data itself.

string.length

Calculates the length of a string.

What does the 'new' key word do here when creating an instance? Printer myPrinter = new Printer();

Calls the default constructor on the Printer class.

Public modifier

Can be applied to a class and/or individual data members and methods within a class; indicates that the given item is accessible across package boundaries, the following class and method are both accessible outside the package in which they're defined. package domain; public class Book { public void checkOut() { } }

Default (no modifier)

Can be applied to a class and/or individual data members and methods within a class; indicates that the given item is not accessible across package boundaries (i.e., it limits access to members of the same package) e.g., the following class and method are NOT accessible outside the package in which they're defined. package domain; class Book { void checkout() { } }

Protected modifier

Can be applied to individual data members and methods (but cannot be applied to a class); when applied, it restricts access to members of the same class and any derived class; e.g., the following method, setHashCode, is only accessible to members of the LibraryItem class and any derived classes (e.g., Book). package domain; public class LibraryItem { protected void setHashCode() { } } package domain; public class Book extends LibraryItem { public LibraryItem () { setHashCode(); } }

Private

Can be applied to individual data members and methods (but cannot be applied to a class); when applied, it restricts access to members of the same class; e.g., the following data member, isbn, is only accessible to members of the Book class, and nowhere else. package domain; public class Book { private String isbn; public void getIsbn() { return isbn } }

Arithmetic Operators

Can be applied to integral or floating point types, includes multiplication(*), division(/), remainder(%), addition(+), subtraction(-).

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.

String

Can use +, ., and +=

Reference Variables

Can't store data values, but *refer to objects* that do.

Case SenSitive

Capital letters must be capitalized to reference a variable correctly

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

Autoboxing

Casts a simple variable value to the corresponding class.

Unboxing

Casts an object to the corresponding simple value.

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.

Conversion

Changing one type of primitive data to another.

Work with Java Arrays

Chapter 6 Objective 1

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.

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)

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.

UML Class diagram w/ general syntax

ClassName Properties Here Behaviors Here Book title: String author: String isCheckedOut: boolean checkOut(): void checkIn(): void Each property name is followed by its data type (e.g., String, boolean). Each method name is followed by its return type (e.g., void).

Object Construction

ClassName objectName = new ClassName(parameters);

How do you call a method from a class?

ClassName.methodName(arguments)

Static method call

ClassName.methodName(parameters);

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

In OOP, describe is-a or has-relationships?

Classes in OOP, are related to each other & they're going to be related through an "IS-A" relationship or "HAS-A" relationship. > IS-A relationship result from inheritance > HAS-A relationship result from composition This comes from the need to reuse code. v47

Checked collecties

Collecties waarvan at runtime gecontroleerd wordt of je er elementen van het juiste type in stopt.

Generic collections

Collection waarbij de compiler controleert of de objecten die je in de collectie stopt van het juiste type zijn.

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");

//

Comment (??) ignore the elephant

// marks the single line ? /* block ? */

Comments

.... objects in a List to be sorted,..

Comparable interface and ít compareTo method

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.

A software program that translates source code (e.g., Java source code) into a machine language program.

Compiler

public static iterator

Complication fails

Chapter 12: The view uses the ____________ to implement the user interface, which usually consists of nested components like panels, frames and buttons.

Composite Pattern

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.

Interface ___ help manage the connection

Connection

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.

Chapter 12: The ______ is the strategy for the view.

Controller

Casting

Converting information from one form to another.

new type [nRows] [nCols]

Create a 2D array

var

Creates a variable and optionally gives it an initial value. Cannot start with a number.

Declaration

Creating a variable of the type that you want to use, reserves a memory location for that variable.

Instantiation

Creating an object.

Overloading the method?

Creating multiple definitions for the same method name, using different parameter types

Cable modem = as fast as?

DSL

What kind of value and how much will be stored?

Data Type

Encapsulation?

Data and actions combined into a class whose implementation details are hidden

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.

Encapsulation

De buitenwereld heeft geen rechtstreekse controle over de inhoud.

Inheritance

De class laten afleiden van een andere class.

Synchronisatie

De handeling is ondeelbaar, het kan niet onderbroken worden door een andere thread.

Enumeration constants

De individuele waarden die een variabele van het datatype enumeration kan aannemen.

Natural ordening

De logische volgorde waarin objecten van een bepaalde class worden gesorteerd.

Autoboxing

De primitieve waarde wordt automatisch omgezet naar de wrapper class.

Specialisatie

De subclasses bevatten gedetailleerder data members en methods dan de superclass.

Throwable

De superclass van de subclasses Exception en Error

Generalisatie

De superclass verzameld alle gemeenschappelijke data members en methodes van de verschillende subclasses.

Collection views

De terugkeer waarde van deze methods zijn een Set of een Collection, waarop een Iterator kan toegepast worden.

JDBC

De verzameling classes die een eenvoudige toegang tot databases mogelijk maakt.

Interface

De verzameling van alle niet-private data members en methods

type[] [] name

Declare a 2D array

[]

Declares arrays

Localizing variables

Declaring variables in the innermost scope possible.

--

Decrement by one

Null means nothing. It's a place holder.

Define "Null"

Abstract is assigned when you want to prevent an instance of a class from being created.

Define the keyword "abstract"

Used to catch exceptions and tell the application to do something else.

Define the keyword "catch"

used to create a subclass for an existing class.

Define the keyword "extends"

used to implement an interface.

Define the keyword "implements"

Only able to be modified inside the class.

Define the keyword "private"

Able to be modified by the class, package, and subclass. But not the world.

Define the keyword "protected"

Able to be modified by the class, package, subclass, and world.

Define the keyword "public"

Method that returns.

Define the keyword "return"

Does not change. Cannot make an instance of.

Define the keyword "static"

Method that does not return.

Define the keyword "void"

{}

Defines a block of code

Code Block

Delimited by curly-brackets, enables a set of statements to be treated as a single statement.

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.

Definition of class

Describes the properties and behavior of a prototypical object. During runtime, the application creates individual instances of classes where the instances are called objects. For example: class - Book properties - title, author behaviors - checkOut(), checkIn() Then at runtime, the application creates a separate object for each book as they are requested by users.

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.

Operator precedence rules:

Determine the order in which operations are performed to evaluate an expression.

confirm

Displays a message and returns true if OK was clicked and false for cancel

alert

Displays a message with an ok button

/

Division

/

Division operator

do{ code here } while ( argument here);

Do loop

Surround all String text with?

Double Quotes

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.

obtain a Connection to a Database

DriverManager

Exception that occurs when you're reading from a file and the file ends before you expected it to end.

EOFException

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

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.

Thread

Each part of a program which takes care of a different task.

What is camel casing?

Each time a new word begins start it with a capital letter

Comparator class als inner class

Een Comparator class integreren in een andere class.

TreeMap

Een Map waarbij de entry's gesorteerd worden opgeslagen volgens de natural ordening van de sleutel.

NullPointerException

Een RuntimeException: het betreffende object kan geen null-waarde bevatten

Class

Een abstract beschrijving van een ding.

Interface

Een abstracte class waarin alleen abstracte methods en eventueel publieke constanten opgenomen zijn.

Inheritance Polymorphism

Een array maken met references naar objecten met eenzelfde base class.

Interface polymorphism

Een array maken van referance variabelen met als type een interface.

Exception

Een class Dat je gebruikt bij het opvangen van onvoorziene omstandigheden.

ListIterator

Een class dat dient om een List te kunnen doorlopen van voren naar achteren en omgekeerd of vanaf een bepaalde positie.

Iterator

Een class dat dient om een collectie te kunnen doorlopen van voor naar achter.

Collections

Een class dat enkele constanten en wat algoritmen bevat voor uiteenlopende handelingen die met collecties te maken hebben.

DigitalFormat

Een class dat gebruikt wordt om decimale getallen in een specifieke formaat weer te geven.

Comparator

Een class dat geïmplementeerd kan worden om het het aantal sorteer wijzen te verhogen van een TreeSet of een TreeMap.

Anonieme inner class

Een class dat volledig in de method wordt beschreven en waarvan de beschrijving van de class onmiddellijk volgt na new.

StringTokenizer

Een class dat wordt gebruikt om een string op te splitsen in verschillende delen, gebaseerd op een scheidingsteken.

BigDecimal

Een class die decimale getallen exact kam weergeven doordat het werkt met meer dan 16 beduidende cijfers.

Singleton

Een class die speciaal geconstrueerd is om maar één object toe te laten.

Subclass

Een class gebaseerd op een bestaande class.

Generic class

Een class met een of meerdere parameters.

StringBuffer

Een class voor tekst dat wel concatenations toelaat.

Abstract class

Een class waarvan geen objecten geïnstantieerd kunnen worden.

Final class

Een class waarvan niet meer overgeërfd kan worden.

Superclass

Een class waarvan overgeërfd wordt.

Hashtable

Een datastructuur waarbij sleutels worden geassocieerd met waardes die dan vervolgens worden gebruikt om het element in de tabel te plaatsen of op te zoeken.

Enumeration

Een datatype dat beschreven wordt adhv een geordende opsomming van waarden.

Collection framework

Een framework dat bestaat uit interfaces en bijhorende implementaties zodat er gewerkt kan worden met een reeks van objecten.

LinkedHashMap

Een gelinkte HashMap waarbij de entry's onderling ook verbonden zijn door 2 referenties.

Comparable<T>

Een generieke interface voor de method compareTo().

JPS

Een html-pagina waarin Java wordt aangeroepen.

HashSet

Een implementatie van Set dat intern gebruik maakt van een Hashtable om de elementen op te slaan.

LinkedHashSet

Een implementatie van de Set dat intern gebruik maakt van een combinatie van een Hashtable en een LinkedList.

TreeSet

Een implementatie van de SortedSet, waarbij de sortering bepaald wordt door de method compare() van de objecten.

Comparator-functieobject

Een instantie van een class dat de Comparator interface implementeert en doorgegeven wordt aan een TreeSet of TreeMap via één van zijn constructors

Set

Een interface afgeleid van de Collection interface dat geen dubbele waarden kan bevatten.

List

Een interface afgeleid van de Collection interface waarbij de volgorde van toevoegen blijft behouden, dat geen dubbele elementen kan bevatten, waarbij elk element een integer positie in de verzameling heeft.

SortedMap

Een interface afgeleid van de Map interface. De key-value paren zijn gesorteerd volgens de key. Het kan geen dubbels bevatten.

SortedSet

Een interface afgeleid van de Set interface dat geen dubbele waarden kan bevatten en altijd gesorteerd is in stijgende volgorde.

Collection

Een interface dat een reeks andere objecten groepeert.

Map

Een interface dat een reeks van objecten groepeert als key-value paren. Het kan geen dubbels bevatten.

Cloneable

Een interface met de method clone()

SERVLET

Een klein programmaatje dat op de server draait. Wordt vooral gebruikt om html-pagina's te genereren.

APPLET

Een kleine applicatie die samen met een HTML pagina geladen wordt vanaf een internet server en die op de cliënt computer wordt uitgevoerd.

LinkedList

Een lijst die bestaat uit objecten die aan elkaar gekoppeld zijn door middel van referenties.

HashMap

Een map waarbij de plaats van de entry-objecten bepaald wordt door de hashcode van de key.

Final method

Een method dat niet meer overriden kan worden.

Abstract method

Een method dat niet uitgevoerd kan worden.

Entry

Een object in een LinkedList

Instantiëren

Een object van een bepaalde class creëren.

Generics

Een oplossing voor het probleem van typecasting bij Collections enMaps.

Key-value paar

Een paar dat bestaat uit twee gegevens: een sleutel en een waarde.

Type parameter

Een parameter dat staat voor een nog niet bekende type en als parameter gebruikt wordt in een generic class.

ArrayList

Een resizable array implementatie van de List interface.

Method overriding

Een subclass een eigen variant geven van een bestaande method uit de superclass.

Package

Een verzameling logisch bij elkaar horende classes, die in een eigen directory, subdirectory worden opgeslagen.

Hashcode

Een waarde dat berekend wordt adhv de waarde(n) van een object.

Bounded wildcard

Een wildcard waarop beperkingen opgelegd zijn: afgeleid van een bepaald type.

Synchrinized wrapper

Een wrapper class die een object thread safe maakt

Unmodifiable wrapper

Een wrapper class die er voor zorgt dat een object niet meer te wijzigen is.

Data member

Eigenschap van een class

Primitive Data Types

Eight commonly used data types.

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++.

Linear/Sequencial Search

Elements are searched one at a time in the order which they are numbered.

Wrapper class

Elke primitive data type heeft een bijhorende class

Inheritance

Enables one object to inherit behavior and attributes from another object.

What does a scanner do for a program?

Enables the program to read data (ints, dbls, char etc.)

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.

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";'.

Representing a character using a binary code.

Encoding

;

End of a statement

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

ClassCastException

Error dat ontstaat bij verkeerde downcasting

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

-Begins with a \ -Always comes in pairs

Escape sequences

Double var = input.nextDouble();

Establishes value inputed into scanner as a variable

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.

Logical Expression

Evaluates to either 'true' or 'false' (boolean literals). Can be used for conditional processing in flow control structures.

Class definition

Every Java program is a ___________________________.

Predefined Java classes

Example of 2: Object class & String class

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

int value = matrix [3] [2]; Pixel pixel = pixels[r] [c];

Example: Accessing two elements

matrix[0].length pixels[0].length

Example: get the number of columns

int [] [] matrix Pixel [] [] pixels

Examples of 2D array declarations

new int [5] [8] new Pixel [numRows] [numCols]

Examples of creation of 2D arrays

What class should be the superclass of any exceptions you create in Java?

Exception

Throwing & Catching Exceptions

Exceptions can be thrown either by the Java API or by your code. To throw an exception examples: throw new Exception(); throw new Exception("Some message goes here"); throw new LoginFailedException("User not authenticated"); Once an exception is thrown, the JVM starts looking for a handler in the call stack to transfer execution of the program. Exception handlers are declared in the context of a try/catch block. Catching Exceptions Java supports the catching of exceptions in what's known as a try/catch block or also known as a try/catch/finally block. Syntax for a try/catch block: try { ... } catch (SomeException e) { ... } The interpretation of the try/catch block is the following: the statements between the try and catch are executed sequentially, and if no exception occurs, then execution continues with the first statement that follows the try/catch block. On the other hand, if an exception occurs while executing the statements between the try/catch, execution transfers to the catch block, and then once the catch block finishes executing, execution continues with the first statement after the try/catch block.

IOExceptions

Exceptions die te maken hebben met in- en uitvoer.

RuntimeExceptions

Exceptions die zich voordoen tijdens het uitvoeren van een applicatie

a.b()

Execute a method b which belongs to object a

Exercise: 1. Create a printer class w/ a modelNumber property & a method to print that model #. 2. From you main method, assign a value to the modelNumber & invoke the Print() method.

Exercise. v(32)

Argument

Extra information sent to a program.

Accessor

Extracts information from an object without changing it. Usually prefixed with 'get'.

read back data from file

FileInputStream, RandomAccessFile

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).

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'.

What is a main method for?

For letting your program run.

for( insert argument here) { insert code here }

For loop

Three types of Loops

For, While, and Do-While.

- Left alignment 0 show leading zeroes + show a plus sign for positive numbers ( enclose negative numbers in parentheses , show decimal separators ^ convert letters to uppercase

Format flags (printf)

d decimal integer f fixed floating-point e exponential floating-point (very large or very small values) g general floating-point s string

Format types (printf)

reference variables

Four types of things can be tested with the equality operators: numbers, characters, booleans, and _________ __________

Graphical User Interface

GUI - PC users view of the "out" screen

Property

Gedrag van een class

Classpath

Geeft aan waar je andere zelfgeschreven classes vindt

name[0].length

Get the number of columns

name.length

Get the number of rows

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.

Applet

Graphical Java program that runs in a web browser or viewer. To run one must have an HTML file with an applet tag.

>

Greater than

>=

Greater than or equal to

Arrays

Group (or collection) of items that are the same type. declares an array object, daysOfWeek, as an array of seven String objects: String [ ] daysOfWeek = new String[7]; assign the seven elements as follows: daysOfWeek[0] = "Sunday"; daysOfWeek[1] = "Monday"; daysOfWeek[2] = "Tuesday"; daysOfWeek[3] = "Wednesday"; daysOfWeek[4] = "Thursday"; daysOfWeek[5] = "Friday"; daysOfWeek[6] = "Saturday"; values could be initialized at the point of declaration: private String [ ] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday" , "Thursday", "Friday", "Saturday"}; The size of the array is available via the length property (e.g., daysOfWeek.length), allowing you to iterate through its values in a "for loop": for (int i = 0; i<daysOfWeek.length; i++) { System.out.println(daysOfWeek[i]); } Array downside, once declared, their size is fixed. Can create a new, larger array and move the contents of the first array into the second, but that is clumsy. Typically used only for grouping items whose size is fixed.

Java Collection Framework

Group of interfaces, classes, and algorithms that together provide a rich set of abstractions for grouping objects. Maps - A collection whose entries are accessed by some unique identifier. Lists - A collection whose entries can be accessed with an index. Sets - A collection whose entries are guaranteed to be unique. Queues - A collection whose entries are ordered, based on some scheme.

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 '=='.

switch argument

Has to be an expression of type int, char, short or byte. Notably not float, double and long (too imprecise or large).

HashMap<String, String>: Instantiation

HashMap<String, String> myMap = new HashMap<String,String>();

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.

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).

Dynamic binding

Het bepalen van de juiste versie gebeurd pas bij de uitvoering.

Upcasting

Het proces om een object van een subclass te beschouwen als een object van zijn superclass.

Type casting

Het type van een variabele omzetten in een andere type.

Wildcard

Het type wordt helemaal niet vastgelegd; het wordt beschouwd als een joker.

Numbers with radix 16

Hexadecimal

Use the dot operator (.)

How do you access a method or instance variable?

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"); }

Quick Check: Nested Loops

How many times will the string "Here" be printed?

Inheritance

How one class can be created from another.

What is an abstract data type?

I a specification of the type's operations: what an instance of that type can do.

Bit

I binary digit, either 0 or 1

encapsulation

I prefer my instance variables private.

-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

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.

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 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 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

What are the 3 selection statements? And the 3 Repetition Statements?

If, If...else, and Switch While, do...while, and for

List Interface

Implemented by classes that represent an ordered collection of element such as numbers or strings.

import java.util.Scanner;

Import the ability to use a scanner from database

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.

:

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.

What is a primitive type in Java?

In java, we have primitive types & objects. Primitive types hold the actual value in memory. Object hold references in memory.

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.

Where is the Scanner Class stored ?

In the java.util package. import java.util.Scanner;

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 by one

Software

Incudes programs and the data those programs use

Annotation

Informatie voor de compiler zodat die de nodige controles kan uitvoeren.

Access Modifiers

Information hiding is achieved through the use of access modifiers, which are keywords that are used to augment the visibility of various constructs. Public Default (no modifier) Protected Private

Source

Information in it's original form.

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.

Inner & Anonymous Classes

Inner classes are defined within the context of another class. package domain; public class Book extends LibraryItem implements AuthorableItem, PrintedMaterial { BookReader reader = new BookReader(); // .rest of Book definition public String nextLine() { return reader.readNextLine(); } // Note that this is not a "public" class- //only an instance of Book can access the BookReader class BookReader { public BookReader() { } public String readNextLine() { // Implementation of this method. } } // BookReader } // Book Anonymous classes are also inner classes that are defined within the context of another class, but these classes do not have a name, hence the name anonymous. Anonymous inner classes are often used as event handlers in the implementation of graphical user interfaces.

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

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".

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.

Command invoking the INTERPRETER to run a Java program from the command line. - vs. invoking the COMPILER

Interpreter → java command Compiler → JAVAC command

Java Program

Is a sequence of statements(smallest executable unit) that have to be formed in accordance with a predefined syntax.

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 is the scope of a variable?

It defines where the variable can be used in a program.

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.

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."

What does a UML activity diagram do?

It models the workflow(also called the activity) of a portion of a software system.

pass by value

It really means 'make a copy'.

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

What's the purpose of the Finally Block

It's useful to force code to execute whether or not an exception is thrown. It's useful for IO operations to close files.

Package

Items of related functionality, each item in the package has a unique name. Thus, a package is a namespace, where a namespace is a collection of uniquely named items. One of main packages is "java", does not contain any data types, it's used to aggregate other packages that are nested within it. java.applet java.awt java.beans java.io java.util nested package example: java.util.concurrent.locks other nested packages do contain type definitions: - java.util contains the Date class (and other classes) - java.util.concurrent contains the Semaphore class (and other classes) - java.util.concurrent.locks contains the LockSupport (and other classes)

LinkedList: iterate through list of strings and print each one

Iterator<String> iter = list.iterator(); while(iter.hasNext()){ System.out.println(iter.next()); } don't forget: iterators have a remove() function!

___ a set of java API

JDBC

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

Java Virtual Machine

JVM - Program needed to run Java byte code - Comes with Mac - Acts like a computer

JSE JEE JME Java Card

Java Standard Edition - Contains the core functionality of the Java language; used to develop desktop applications. Java Enterprise Edition - Provides additional functionality required of enterprise applications, including web applications. Java Micro Edition - A scaled-down version used for mobile phones and other handheld devices. Java Card - The smallest Java footprint used for integrated circuits (e.g., memory and microprocessor cards).

What does JVM stand for?

Java Virtual Machine

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"

Package

Java classes grouped together in order to be imported by other programs

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.

Impliciete cast

Java neemt de waarde van een variabele van het beperktere type en stopt deze waarde in een ander variabele met een type met meer opslag mogelijkheden.

String class

Java's String class is used to represent a sequence (i.e., string) of characters. A simplified class diagram of String is shown below: STRING count : int value : char[] String() String(orig:String) length : int charAt(index:int) : char concat(st : String) : String equals(obj : String) : boolean indexOf(str : String) : int isEmpty() : boolean lastIndexOf(str : String) : int length() : int replace(oldChar : char , newChar : char) : String substring(beginIndex : int, endIndex : int) : String toLowerCase() : String toUpperCase() : String toString : String * Extends class Object and thus inherits Object's properties and behavior, including method equals(Object); * Encapsulates private fields (e.g., count and value), prevents direct access to these fields by other objects; indirect access is provided through public methods; e.g., the method length() provides access to the count field; * Has two overloaded constructors, String() and String(String s). The first constructor takes no parameters, and the second takes a String object that is copied into the new String object; * Overrides methods toString() and equals() inherited from class Object by providing its own implementations; * Exhibits polymorphism (one interface, multiple behaviors) with methods toString() and equals();

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)

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

Create a Method called methodX

Java: public static void methodX(){

Concatenating

Joining one string to another string. Also known as pasting.

Capable of compiling each byte code once, & then reinvoking the compiled code repeatedly when the byte code is executed.

Just-in-Time compiler

Public

Kan door de buitenwereld worden aangeroepen.

Private

Kan niet door de buitenwereld worden aangeroepen

TreeSet

Keeps the elements sorted and prevents duplicates.

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

<

Less than

<=

Less than or equal to

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

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

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

;

Like a period in English. Marks the end of a statement or command

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.

public static void main(String[] args){

Line 2 of program, opens programming block

TestException

Line 46 ... enclosing method throws... Line 46... try block

LinkedList<String>: Instantiation

LinkedList<String> myList = new LinkedList<String>();

A constant value that appears directly in the program

Literal • may be numeric, character, boolean, or **null** for object type.

A variable declared in a method is said to be a ____________________.

Local variable

Define how java classes are connected.

Loosely connected objects that interact with each other.

public static void main(String args[])

Main Method

-All must have one (except apps) -Follows the class, where execution begins -Must h ave { and }

Main method

LinkedList

Makes it easy to create structures like stacks or queues.

Public int

Makes it possible to modify the variable from another program that is using the object.

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.

Exception that occurs when a URL isn't in the right format (perhaps a user typed it incorrectly)

MalformedURLException

What's the equivalent of a dictionary in Java? Please create an example.

Map - Look in module about collections.

Pi

Math.PI

π

Math.PI;

absolute value?

Math.abs(#)

absolute value of x - y

Math.abs(x - y);

arc cos x

Math.acos(x);

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(#)

Natural logarithm of a number?

Math.log()

find the max

Math.max (x, y);

larger value of x and y?

Math.max(x,y)

find the min

Math.min (x, y);

Smaller value of x and y?

Math.min(x,y)

x^y

Math.pow (x, y);

Power or Exponent

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

square root of a

Math.sqrt (a);

Tangent?

Math.tan(x)

radians to degrees

Math.toDegrees();

degrees to radians

Math.toRadians();

void

Means that the method does something but does not return any value at the end

Finalize

Method dat door de garbage collector wordt aangeroepen net voor het object wordt opgeruimd.

Copy constructor

Method die alle properties van een nieuw object initialiseert adhv waarden van de proporties van het parameter object.

Constructor

Method met identieke naam als de class, wordt uitgevoerd als een object geïnstantieerd wordt.

Setter

Method om de waarde van een data-member in te stellen.

Getter

Method om de waarde van een datamember op te halen.

polymorphism

Method overloading is an example of polymorphism. polymorphism can be defined as "one interface with multiple behaviors." Another form of polymorphism is method overriding, which is an example of dynamic binding. Method overriding is discussed later in this topic.

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.

Mutator

Method that alters the attributes of an object.

toUpperCase

Method which converts any String to uppercase equivalent by creating a new String object

-Segments of code that perform some action -Always followed by parenthesis EX: System.out.println("abc") <--- print is the ?

Methods

All objects in a class have the same _______ and same types of _______.

Methods && Instance Variables

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

Methods with parameters

Methods that you can pass one or more values in to.

-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

%

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.

MVC

Model -View -Controller

Binary Search

More efficient than a linear search, but only works if the indexes are in order/ are sorted.

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 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}}}

...

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][ ][ ]

...

Multi-dimensional arrays do not have to have the same size sub arrays. Example: int[ ][ ] oddSizes = {{1,2,3,4},{3 },{6,7}}

*

Multiplication

*

Multiplication operator

*=

Multiply and assign operator

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"); } }

\n

New line

Static

Niet specifiek per object, maar gedeeld door alle instanties van de class.

Immutable

Niet te wijzigen

A no-argument constructor has....

No parameters.

Are primitive data types considered objects in Java?

No, primitive types are the only elements of the Java language that are not modeled as objects.

!=

Not equal to

Ways to handle an exception

Not handle it at all - program will crash and and produce a message describing the exception

Reason Brackets are missing

Not required for single statement IF statements or Loops.

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

Reasons to use "int"

Numbers -2 billion to, 2 billion

Reasons to use "long"

Numbers greater then ±2 billion

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)

4 Java Data Types?

Numeric, String, Character, Boolean.

*** 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

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.

Object class

Object is base class of all Java classes. All Java classes extend (inherit) class Object either directly or indirectly. these 2 definitions are exactly the same: public class Book {...} public class Book extends Object {...}

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

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(); }

'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.

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

Jar

Om de hoeveelheid code die bevat zit in duizenden classes manipuleerbaar te houden, slaat men ze op in gecomprimeerde archieven.

static

One copy and everyone can see it

Inheritance

One of the 3 main pinnacles of object-oriented programming (the others being encapsulation and polymorphism). Inheritance is a means by which a class extends another class, it acquires the properties and behavior of the class that's being extended. Sometimes called generalization/specialization, also called an "is a" relationship. For example, the class declarations of Book, Audio, and Periodical are shown below: package domain; public class Book extends LibraryItem { // properties and behavior of Book go here } package domain; public class Audio extends LibraryItem { // properties and behavior of Audio go here } package domain; public class Periodical extends LibraryItem { // properties and behavior of Periodical go here } class can only extend one other class -- cannot extend multiple classes

next()

One word String

Private variable declaration?

Only applies to that class. ex. private String first;

public class{

Opens and names your program

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.

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.

||

Or

During runtime, value assigned that exceeds positive bounds of a variable

Overflow error

A _____________ is like a blank in a method definition...

Parameter

Methods

Part of an Object's behavior.

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

Declare the data type of a variable.

Primitive types are used to declare the data types of variables where a variable is a named memory location. datatype variableName = initialvalue; The following statements illustrate the use of Java's eight primitive data types in variable declarations: char c = 'a'; Boolean succeeded = false; byte age = 0; short index = 0; int ssn = 0; long length = 0; float pi = 3.14159f; double d = 0.0; floating point literals are defaulted to a "double" data type. To compile certain types, such as float, add a suffix to the literal: float pi = 3.14159f;

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*.

System.out.print(" ");

Prints a string of text

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

Objects

Programs that you create. These can be thought of as physical items that exist in the real world.

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

Initializer List

Provides the initial values for the elements within an array.

Access Control

Public or Private; Determines how other objects made from other classes can use the variable, or if at all.

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.

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.

Single '

Quotation type used for character values.

Double "

Quotation type used for string values.

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

Use of the word "this"

Refers to the object itself

==

Relational operator: equals

>

Relational operator: greater than

>=

Relational operator: greater than or equal to

<

Relational operator: less than

<=

Relational operator: less than or equal to

!=

Relational operator: not equals

boolean

Relational operators always result in a ________ value.

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

For Loop

Repeats a section of a program a fixed amount of times.

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

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.

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

Java1

Result? "Java" + 1

3

Result? 2 + 1

return SQL query result

ResultSet

Iteration

Returning an object that can be used to cycle through all of the elements in a list

return function?

Returns and expression. ex. return first + " " + middle + " " + last;

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.

Two-Dimensional Array

Rows and columns.

Syntax

Rules for combining words into sentences

Semantics

Rules for interpreting the meaning of statements

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

Differences in String

S is Capitalized. Type of Object.

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);

Initialize scanner

Scanner keyboard= new Scanner (System.in);

;

Semicolon

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)

Data Type 'String'

Sequence of characters, a reference data type.

Java vocabulary

Set of all words and symbols in the language

name [row] [col] = value

Set the value of an element

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.

long totalMilliseconds = System.currentTimeMillis();

Sets total number of milliseconds since midnight, January 1, 1970, as a variable

What is a Vector?

Similar to ArrayList, but synchronized

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

Design patterns

Slimme oplossingen voor complexe problemen, die ons onder de vorm van abstract beschrijvingen worden gegeven.

Why is there a semicolon (;) at the end of each statement?

So Java knows that it is the end of a statement.

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

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

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

Insertion Sort

Sorts a list of values by repeatedly inserting a particular value into a subset of the list that has already been sorted.

Selection Sort

Sorts a list of values by successively putting particular values in their final, sorted positions.

if

Specifies a block of code to be executed if a certain condition is true

else if

Specifies a new condition if the first condition is false

What is program control?

Specifying the order in which statements(actions) execute in a program.

What are the local variables/parameters of a method stack known as?

Stack frames/activation records

What are standard Java arrays and when must they be initialized?

Standard Java arrays are objects and must be initialized after they are declared.

....

Standard Java arrays can be declared with square brackets after the type or variable name. Example: int[] myArray or int my Array[]

...

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]

How many dimensions can standard Java arrays have?

Standard Java arrays can have one or many dimensions.

What can standard Java arrays store?

Standard Java arrays can store both objects and primitives.

println

Starts a new line after displaying the text.

submit a query to a database

Statement object

-Must end with a ; (semicolon)

Statements

Expressions

Statements that involve a mathematical equation and produce a result.

play 2001.mid

StdAudio.play("2001.mid");

draw circle at (x, y) radius = r

StdDraw.circle(x, y, r);

draw filled circle at (x, y) radius = r

StdDraw.filledCircle(x, y, r);

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);

draw an image, starfield.jpg at (0, 0)

StdDraw.picture(0, 0, "starfield.jpg");

draw point at (x, y)

StdDraw.point(x, y);

set pen color

StdDraw.setPenColor();

pen size to 0.05

StdDraw.setPenRadius(0.05);

set x and y window scale to -R , R

StdDraw.setXscale(-R , R); StdDraw.setYscale(-R, R);

draw "text" at (x, y)

StdDraw.text(x, y, "text");

boolean for empty

StdIn.isEmpty()

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'.

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 word is always capitalized in java syntax?

String

0 or more characters surrounded by double quotes?

String (always capital "S")

Example of variable declaration and explanation.

String firstName; Start with data type then variable name. Must end with the ";".

String declaration

String name = "";

nextLine()

String of words

Syntax to create a String

String s1 = new String("Hello World"); Can be created and initialized without using new: String s2 = "Hello World"; Can be concatenated with the + operator: String s3 = "Hello " + "World"; Operator == compares object references (and not the object's state), and since s1, s2 and s3 reference different String objects, == returns false: (s1 == s2); // returns false (s2 == s3); // returns false (s1 == s3); // returns false String's implementation of equals(Object) examines the values of the strings, this is true: s1.equals(s2); s2.equals(s3); s1.equals(s3); Strings objects created with the "new" operator that have the same value (the same string of characters) are always "equals()" to each other, but since they are different objects, they are never "==" to each other. One last subtle point: strings created using the double quote syntax with the same value without the new operator are always = = to each other. String s4 = "Hello World"; String s5 = "Hello World"; (s4 == s5); // returns true

How could you define a String variable named wrd and initialize it to the word cats?

String wrd = "cats";

Array: convert from Collection strs to Array

String[] arr = new String[strs.size()]; strs.toArray(arr);

string Array: Instantiation

String[] myArr = new String[numberOfItems]; String[] myArr = {"a","b","c"};

declare and initial string array, names, with length N

String[] names = new String [N];

Variable names

Strings of any length of letters, digits, underscores, and dollar signs that begin with a a letter, underscore, or dollar sign.

UML Diagrams - list the structure diagrams

Structure Diagrams - CCCODPP Composite Structure Class Component Object Deployment Profile Package

__________ method cannot throw more exceptions (either exceptions of different types or more general exception classes) than its superclass method.

Subclass

-

Subtraction

-

Subtraction operator

Argumenten van het wildcard type

Superclasses en interfaces als method parameter gebruiken zodat de method voor de verschillende implementaties en subclasses gebruikt kan worden.

When you type something wrong and java doesn't compile (LANGUAGE)

Syntax error

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"

How do you print something in the output?

System.out.print("Something to print"); or System.out.println("Something to print with a line (LiNe)");

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]);

Print statement

System.out.println("");

Command to print to the console? (what letter is capitalized)

System.out.println("Hello");

What System.out method moves the cursor to the next line?

System.out.println()

print (return)

System.out.println();

Given: String firstName = "reynald"; Writhe the line of code to out the index of letter 'a'

System.out.println(firstName.indexOf('e')); v23

Emergency exit

Sytem.exit(value);

Create a generic class as in v58

TODO

Create a generic method as in v59 and use bounded types (v60)

TODO

Create an example of Polymorphism that reflect v51

TODO

Create an example of changing inheritance to composition by using interfaces. See exampled in v54.

TODO

Create an example of composition. Create a car class that HAS a gas tank. After the car runs 200miles, make it request to add gas.

TODO inspired by v49 (paper tray example)

Create an example of inheritance and using a constructor by writing a method that print the name passed into the constructor. In the super class, use the keyword 'protected'

TODO v48

Create an example using 'wild cards'

TODO v61

What is erasure?

TODO v62

Create an IllegalAurgumentException (with some error message) in a method & on the calling method, add a try / catch block to display your error.

TODO - video on Excepions -->Try / Catch

What is a 'Queue' in Java?

TODO: Create a queue

%=

Take remainder and assign operator

%

Take remainder operator

Hash Code

Tells where in the array the data item should be stored.

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).

While Loop

Tests the condition at the beginning of each repetition of a section of a program.

Do While Loop

Tests the condition at the end of each repetition of a section of a program.

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

Assignment operator:

The = (the equals sign). Assigns a value to an identifier.

What is the ArrayList class a representation of?

The ArrayList class is an object-orientated representation of a standard Java array.

Chapter 12: ______ is a compound pattern consisting of the Observer, Strategy and Composite patterns.

The Model View Controller Pattern (MVC)

Hardware

The Physical pieces of a computer system

!

The ___ operator, called the "inversion" operator, returns the opposite value of the boolean value it precedes.

^

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.

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.

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

Arrays.copyOf(values, n)

The call Arrays.copyOf(values, n) allocates an array of length n, copies the frst n elements of values (or the entire values array if n > values.length) into it, and returns the new array.

Enclosing Classes

The class that the nested class is nested in

Suppose interface Inty defines 5 methods

The class will not compile if it's declared abstract The class may not be instantiated

Source code:

The combination of the import statements and the program statements

string1.compareTo (string2) < 0

The compareTo method compares strings in lexicographic order.

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"

Destination

The converted version of the source in a new form.

Iterator

The counter variable used to control a loop.

Class

The data type of an object

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

CPU

The device that executes the individual commands of a program

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.

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.

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

Polymorphism

The idea that we can refer to objects of different but related types in the same way.

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(); }'.

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

Attribute

The information that describe the object and show how it is different than other objects.

class hierarchy

The instanceof operator can be used only to test objects (or null) against class types that are in the same _____ ___________

Target

The item being searched for in a search

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");

Operating System

The main software of a computer.

Index/Subscript

The number for each position of a stored array value. Always starts from zero.

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

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.

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.

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.

Sorting

The process of arranging a list of items in order.

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.

Evaluation

The process of obtaining the value of an expression.

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

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

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.

Token:

The smallest individual unit of a program written in any programming language.

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.

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.

Edit, Compile, Run

The three steps to creating a program are ___ (e), ____ (c), and ____ (r).

countryName = countryName.trim();

The trim method returns the string with all white space at the beginning and end removed.

Element Type

The type of values stored in an array.

Class Statement

The way you give your computer program a name.

Boolean Literal

The words true and false.

true

The || and | operators return ____ if either or both operands are true.

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

What are single array variables capable of doing?

They can reference a large collection of data

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.

What are variables?

Things that store information.

Error

This Class indicates issues that an application should not try to catch. Subclass of the class Throwable.

Why is the method "main" Declared static?

This allows the JVM to invoke "main" without creating an object of the class

return, argument

This can be implicitly promoted.

Loop

This causes a computer program to return to the same place more than once.

Exception

This class indicates issues that an application may want to catch. A 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.

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.

Do While Execution

This loop will always execute at least once, even if the conditions are not met.

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

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).

parts of a program set up to run on their own while the rest of the program does something else.

Threads

Swapping

Three assignment statements that change elements to a different index using a temporary place holder.

prepcode, test code and real (Java) code)

Three things to write when designing a new class

javax.swing.*;

To create lightwieght components for a GUI.

java.net.*;

To develop a networking application.

java.awt.*;

To paint basic graphics and images.

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 (==)

java.io.*;

To utilize data streams.

java.lang.*;

To utilize the core java classes and interfaces.

java.util.*;

To work with collections framework, event model, and date/time facilities.

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.

Set implementation... value-ordered

TreeSet

T or F: The name of a local variable can be reused outside of the method in which it is declared ?

True

True or False, by catching a exception superclass you can also catch any subclass exceptions that are thrown?

True

code fragmanet, sbuf references.. sbuf.append

True

False

True or False? + and - have higher precendence than *,/, and %

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.

False

True or False? If the left-operand is false, the && will go ahead and evaluate the right operand.

True

True or False? The || won't evaluate the right operand if the left operand is true.

Method overloading

Twee methods schrijven binnen een class met dezelfde naam, maar met een verschillend aantal parameters.

Parallel Arrays

Two arrays with corresponding elements.

Collision

Two or more data values that hash to the same cell.

...implement the JDBC API

Type 1

Boolean Values

Type of variable that cannot be used in any Casting.

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;'

subclasses of the RuntimeException and Error classes and are usually thrown by the Java runtime itself.

Unchecked exceptions

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

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'.

Cast operator:

Used for explicit type conversion

else

Used in conjunction with if. Checks if the condition is false

Ternary Operator

Used to assign a value or display a value based on a condition.

//

Used to comment out a line.

/* */

Used to comment out a paragraph or longer

double

Used to declare and initialize a fraction interager. Ex: double canVolume = 0.335;

int

Used to declare and initialize a non fraction interager Ex: int canVolume = 5;

byte

Used to define a primitive variable as an integer with 1 byte of storage. Also a corresponding wrapper class.

==

Used to equal a value

Integer.ParseInt()

Used to get a value of a String, usually with a digit.

break

Used to leave a loop early

Semicolon

Used to separate sections.

Comma

Used to separate things within a section.

Variables

Used to store values that can be used repeatedly in a class

The comparing method: equals(Object)

Using equals(Object): boolean areEqual = book1.equals(book2); It compares object references, compares to see if book1 and book2 reference the same Book object in memory. In the example above, book1 and book2 reference different Book objects, so the boolean variable areEqual is set to false. This one would be true: Book book1 = new Book(); Book book2 = book1; boolean areEqual = book1.equals(book2);

How do you declare a CONSTANT in Java?

Using the keyword "final": final float pi = 3.14159f;

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

blank.

Value

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]

Long

Variable type of 64 bits and with a range of [-9223372036854775808, 9223372036854775807]

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

Short

Variable type with a size of 16 bits and a range [-32768,32767 ]

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)

Primitive and Reference

Variables come in two flavors.

final

Variables marked ______ cannot be incremented or decremented.

Constants

Variables that do not change in value; typed in all-caps.

Downcasting

Via expliciete typecasting een object van een superclass typecasted naar een object van een subclass.

SQL keyword

WHERE

How did we read in files? What is required?

We used a scanner, while loop, and iterator

Behavior

What an object does.

%

What arithmetic operator returns the remainder of a division?

design test code

What do you use prep code for?

Null

What does a reference variable have for its value when it is not referencing any object?

A remote control

What does a reference variable liken to?

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?

i

What is the standard convention for un-named variables?

The number and type of values

What must match the order and type of the parameters declared by the method?

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?

literal values or values of declared type.

What type of values you can pass as an argument to a method?

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

A void return type does not return anything

What void return type mean?

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)?

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 counter controlled repetition?

When a loop is controlled by a counter such as x>3

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.

What is control statement stacking?

When a number of control statements are placed one after another in a sequence within a program.

Implicit type coercion:

When a value of one data type is automatically changed to another data type.

INCORRECT.. serialization

When an Object Output Stream

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.

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.

Unicode

When comparing characters, Java uses the ________ value of the character as the numerical value

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

object

When comparing reference variables, == returns true only if both references refer to the same ______

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?

Encapsulation

When each object protects its own information.

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

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.

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.

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.

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.

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.

while(insert argument here) { insert code here }

While loop

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

Reserved words

Words that have predefined meanings that cannot be changed

Main class

Wordt uitgevoerd bij het opstarten van de applicatie.

int i = 10; do{ i = i + 5; System.out.print(i); } while (i > 5);

Write an endless do loop where i=10

for(i=10; i > 5; i++){ System.out.println(i); }

Write an endless for loop where i=10

int i = 10; while(i > 5){ i = i + 5; System.out.print(i); }

Write an endless while loop where i=10

if (i=10) { //do something } else { //do something else }

Write an if then else statement where i=10

if(i=10){ //do stuff }

Write an if then statement where i=10

Are there standard Java arrays built into the Java language?

Yeah, hell Yeah lol there standard Java arrays are built into the Java language.

write code... execute onlu.. curren thread owns multiple locks

Yes

Can standard Java arrays be multi-dimensional?

Yes, standard Java arrays can be multi-dimensional; each set of square brackets represents a dimension.

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.

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.

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

EJB

Ze draaien op de server, zijn niet grafisch georiënteerd, maar zullen eerder taken verrichten in database manipulatie, netwerkbeheer, ...

"

\"

'

\'

What escape sequence makes one backslash character in a print or println statement?

\\

\

\\

Backspace

\b

What escape sequence makes the backspace character?

\b

New line

\n

New line character

\n

What escape sequence makes the newline character?

\n

New tab character

\t

Tab

\t

What escape sequence makes the tab character?

\t

short hand a = a * n

a *= n;

short hand a = a + n;

a += n;

short hand a = a - n;

a -= 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.

bytecode

a binary program

overloaded

a class having more than one method with the same name

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.

INCORRECT..RMI server

a client acceeses remote object... only server name

What does /* suggest

a comment

interpreter

a computer program that translates one computer statement at a time and executes each statement as it is trasnlated

compiler

a computer program that translates the WHOLE code into machine language and then carries out the statement

'final' reference variables cannot refer to ...

a different object once the object has been assigned to the 'final' variable.

Coordinate system

a grid that allows a programmer to specify positions of points in a plane or of pixels on a computer screen

method

a group of one or more programming statemetnts that collectively has a name

Package

a group of related classes in a named directory

low-level programming language

a language that corresponds closely to a computer processors's circuitry

semantic error

a logical error, for example if you use the correct word in the wrong location

A local variable disappears when...

a method invocation ends.

println

a method that prints characters to the screen and moves to the next line

print

a method that prints characters to the screen and remains on the same line

identifier

a name

int

a primitive data type, integer

Virus

a program that can enter a computer and perhaps destroy information

architecturally neutral

a program that can run on any operating system ex. Java

system software

a program that manages the computer itself -ex.Windows

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.

null Reference

a reference that does not refer to any object

A ________ is used to terminate all java

a semi colon ;

'abstract' methods end in ...

a semicolon - no curly braces.

Method

a sequence of instructions that accesses the data of an object

Arithmetic expressions

a sequence of operands and operators that computes a value

literal string

a series of characters that will appear in the output exactly as entered, must be in quotation marks

program statements

a series of sentences that tell a program what to do

developmental environment

a set of tools that help you write programs by providing features such as displaying a languages keywords in color

jGRASP

a source code editor

object

a specific concrete instance of a class

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

JDBC 2-tierprocessing model

a user's command are delivered to the database

Object reference

a value that denotes the location of the object in memory

What is the sentinel value?

a value to be typed in to stop a loop

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");

System.out.println("ab\"\\c"); prints out

ab"\c

System.out.println("ab\\c"); prints out

ab\c

System.out.println("abc"); prints out

abc

public class Outer

abce

Abstract Classes & Interfaces

abstract class - class that is never intended to be instantiated as an object. Its purpose is to serve as a base class that provides a set of methods that together form an API. classes that inherit the abstract class can override its base behavior as necessary. Because the derived classes can be instantiated, they are referred to as concrete classes. This combination of an abstract base class and one or more concrete derived classes is widely used in industry and is known as the "Template" design pattern. class is identified as being abstract by pre-pending the keyword "abstract" to the class definition. package domain; public abstract class LibraryItem { } abstract keyword prohibits a LibraryItem from being instantiated with the "new" keyword. When a class is denoted as abstract, it typically means that one or more of its methods are also abstract, which implies they have no implementation. method is declared to be abstract by using the "abstract" keyword: public abstract boolean validate(); there's no {...} following the signature; rather, a semicolon is present. method must not have an implementation following its signature, the enclosing class must be declared to be abstract. implementation of validate() in one of the concrete derived classes: Book. package domain; public class Book extends LibrarayItem { public boolean validate() { if (id <= 0) return false; if (title == null || title.equals("")) return false; if (author == null || author.equals("")) return false; if (pages <= 0) return false; return true; } } another technique for declaring "abstract" interfaces by way of the "interface" keyword: package domain; public interface IValidator { public boolean validate(); } interface construct is used to capture zero or more method signatures without specifying their implementation details. methods enclosed within an interface definition must be "abstract" in the sense that they must not provide an implementation (i.e., {...}), but the abstract keyword is not necessary. interfaces are implemented in classes with the "implements" keyword. User and Login are not defined as abstract since implementations are provided for the validate() method. package domain; public abstract class LibraryItem implements IValidator { public abstract boolean validate(); } uniform interface for validating objects. package domain; public class User implements IValidator { public boolean validate() { } } package domain; public class Login implements IValidator { public boolean validate() { } } while Java does not support multiple class inheritance , it does support the implementation of multiple interfaces in a single class. To serialize Login objects across a secure network Login class needs to implement the Serializable interface. package domain; public class Login implements IValidator, Serializable {...} Serializable does not contain any methods, known as a Marker Interface. Marker interfaces, used to "mark" classes (and hence their objects) as "one of those," but without any additional methods. In summary, interface constructs are used to separate interface abstractions from implementation details.

An interface can have only ...

abstract methods, no concrete methods allowed.

Instance variables can't be ...

abstract, synchronized, native, or strictfp.

A class implementing an interface can itself be ...

abstract.

__ method is used to wait for a client...

accept()

values[i] = 0;

access element of array at position i (count starts from 0)

Local (method, automatic, or stack) variable declarations cannot have ...

access modifiers.

'static' methods do not have direct ...

access to non-static members.

Constructor Definition

accessSpecifier ClassName(parameterType paramterName, ...) { constuctor body }

Instance Field Declaration

accessSpecifier class ClassName { accessSpecifer fieldType fieldName; }

Class Definition

accessSpecifier class ClassName { constructors methods fields }

Method Definition

accessSpecifier returnType methodName(parameterType parameterName, . . .) { method body }

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.

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.

+

add operator

Write an expression that returns the position of the 1st occurrence of the String "Avenue" in address (a String).

address.indexOf("Avenue")

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

friends.add (i, "Cindy"); String name = friends.get(i); friends.set(i, "Harry"); friends.remove(0);

adds element to arrayList at pos i (w/out i will add element to end); obtains element at i; redefines element at i as "Harry"; removes element

StringBuffer sbuf

after line 2, .... eligible

correct statement about RMI

all

correct statement about remote class

all

correct statement about remote interface

all

'public' members can be accessed by ...

all other classes, even in other packages.

Associations

allow classes (and their objects) to form relationships with one another. These relationships facilitate object collaboration. two types of associations: "Has a" relationships: Abstracts/models the concept of containment (e.g., a Customer has an Account; or in other words, the Customer contains an Account). "Uses a" relationships: Abstracts/models the concept of using (e.g., a Workflow manager uses various services to accomplish a task [to get some work done]). "has a" relationship with another class if it has a data member of that particular type. package domain; public class User { private Account account = new Account(); } abstracting a Login class that contains the user's credentials (username, password) and associating it with the User by declaring Login data member: package domain; public class User { private Login login = new Login(); private Account account = new Account(); } Once you declare a data member as an object type, you have essentially created a "has a" relationship between the two objects. "uses a" relationship, only difference between a "has a" and "uses a" relationship is where the declaration is made. "uses a" relationships are defined within method declarations (and not as data members of the enclosing class). So for instance, suppose a particular method needs to use a Date object to timestamp a message: package domain; public class Logger { public generateLogMessage(String message) { Date date = new Date(); } } The above method instantiates a Date object locally within the scope of the method, not as a data member (at the class/object level). "uses a" relationship. So we can summarize "has a" and "uses a" relationships as follows: "Has a" relationships are realized as object declarations located at the class level (i.e., as data members). "Uses a" relationships are realized as object declarations located within the scope of a method.

Graphical user interfaces (GUIs)

allow users to interact with a program in a graphical environment

Type casting

allows one data type to be explicitly converted to another

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

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);

Exception

an abnormal state or error that occurs during runtime and is signaled by the operating system

public

an access specifier

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

Logic error

an error such that a program runs, but unexpected results are produced. Also referred to as a design error

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

instance

an object of a class.

out

an object that provides a way to send output to the screen

Assignment operator

an operator (=) that changes the value of the variable to the left of the operator

numeric data types

another name for primitive data types; most commonly int and double

'synchronized' methods can have ...

any access control and can also be marked 'final'.

Static variables are not tied to ...

any particular instance of a class.

String concatenation

append a string or value to another string

How do you test a diagram as to whether it is structured?

apply the rules backwards to reduce it to the simplest activity diagram.

Objects...

are instances (instantiations) of classes, as objects are created, the properties that are defined in the class template are copied to each object instance and assigned values. Thus, each object has its own copy of the class properties

A method can have many of these.

argument

double[] values = new double[10]; double[] moreValues = {32, 54, 67.5};

array declaration and initialization

Array Element Access

arrayReference[index]

How can you specify a string to make a assert statement more meaningful

assert price > 0 : "Price less than 0.";

expressions that represent a condition that a programmer believes to be true at a specific place in a program.

assertions

Arithemetic overflow

assigning a value to a variable that is outside of the ranges of values that the data type can represent

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

b

b

\\

backslash; causes a backslash to be printed

What is the syntax of a sequence control flow example?

base = rate * hours; taxes = base * taxRate; net = base - taxes; count++; count--;

Iterable Interface

base interface for all interfaces of the Java collection framework (excluding Map). Iterable defines exactly one method, namely: Iterator iterator(); This allows you to get an Iterator for iterating over the elements of a collection. Since all other collection interfaces extend Iterable (either directly or indirectly), they all inherit the above method; that is, they all provide an iterator for iterating over their elements. For example, the Collection interface directly extends Iterable, and hence, if you have a Collection, you can get an iterator to iterate over its elements: Collection<Book> coll = getOverdueBooks(); Iterator<Book> iter = coll.iterator(); while (iter.hasNext()) { Book book = iter.next(); } Because the need to iterate over all items in a collection is a common practice, the method iterator() is placed in the base interface Iterable, and then through inheritance, it's made available to all collections that extend Collection (because Collection extends Iterable). The extension of Iterable by Collection (and then List, Set, and Queue) is known as interface inheritance.

b

bb

Objects

belong to classes

Members accessed without a dot operator (.) must ...

belong to the same class.

{ double volume = sideLength * sideLength * sideLength; return volume; }

body of method

True False data type

boolean

Value: true/false

boolean

declare a boolean variable, isAscending

boolean isAscending;

&&, ||, !

boolean operators; and, or, not

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*.

An open brace is always followed by a close

brace }

Never put a semi-colon before an open

brace{

A thread can be created in two ways:

by subclassing the Thread class or implementing the Runnable interface in another class.

-8 bits Range: -128 to 127 No rules

byte

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

Use a division assignment operator to make c=4 when c=8

c/=2

What is a local variable?

can be used only in the method that declares it from point of declaration to end of method

If a class cannot be accessed, its members ...

cannot be accessed.

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

Chapter 1: Most patterns and principles address issues of

change in software

-16 bits unsigned Range: 0 to 65535 -Holds one letter -Value enclosed in ' ' -Outputs letter unless addition is in parenthesis

char

Alphabetic characters that can be stored as a numeric value?

char

\

char that comes after is exempted from compiler (ie printing "")

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'.

in.hasNextDouble()

checks for numerical input; false if the next input is not a floating-point number

Java interpreter

checks the bytecode and communicates with the operating system, executing bytecode instructions line by line within the JVM

How do you start a program?

class (name of program) { //Your program goes here!! }

null reference example

class NameIsEx { String name; void printName( ) { System.out.println (name.length ( ) ); } }

public class _____

class header; indicates a publicly accessible class named "_____"

How do you make a Hello World program?

class helloWorld { public static main (String[] args) { String hw = "Hello, World!"; System.out.println(hw); } }

Declaring a class to a package

class is declared to belong to a package by including a package statement at the beginning of the source file, it must be the first statement in the file: package mypackage; public class MyClass { ... } If package is not declared, the class will belong to the "default package". Not recommended for larger programs.

source file contains a large number of import statements ( class loading )

class loading takes no additional time

Instantiating an object

class name object name = classname();

The 'strictfp' modifier applies only to ...

classes and methods.

Default members can be accessed only by ...

classes in the same package.

Application defined classes

classes that you create for your specific application Login -username : String -password : String +setUsername : (username : String) +getUsername () : String +setPassword : (password : String) +getPassword () : String +validate() : boolean +equals(Login Login) : boolean two private data members: username and password; the minus sign means the properties are hidden in the class, cannot access them outside of class. When a class does not explicitly provide a constructor, Java implicitly provides a default constructor (one that takes no arguments). The default constructor is available for use even though it's not shown.

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

//

comment

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

if (string1.equals(string2))...

compares equality of 2 strings

source file contains a large number of import statements ( compilation )

compilation takes slightly more time

Dog, Animal

compile and run

hardware

computer equipment such as a keyboard

variables

computer memory locations that hold values

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

A variable declared "Final"

constant

Interfaces can have ...

constants, which are always implicitly 'public', 'static', and 'final'.

Interfaces are ...

contracts for what a class can do, but they say nothing about the way in which the class must do it.

Math.toRadians(x)

convert x degrees to radians (ie, returns x* p/180)

Math.toDegrees(x)

convert x radians to degrees (ie, returns x*180/p)

Boxing

converting a primitive value to a wrapper obj.

Math.cos(x)

cosine of x

primitive

data such as numbers and characters, NOT objects

Scanner in = new Scanner(System.in);

declares Scanner "in"

String s = in.nextLine();

declares and inputs a line (a string of characters)

double d = in.nextDouble();

declares and inputs a real value (floating point #)

int i = in.nextInt();

declares and inputs integer value

Variable declaration statement

declares the identifier and data type for a variable

Chapter 12: These patterns work together to ______ the three players in the MVC model, which keeps designs clear and flexible.

decouple

method toString()

default behavior is to return the object's fully qualified name followed by the object's hash code. book1.toString(); //returns: Book@1ea2df3 book2.toString(); //returns: Book@1ea2df3 this information is typically not useful, it's common to override toString().

Local variables don't get ...

default values, so they must be initialized before use.

semantics

define the rules for interpreting the meaning of statements

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 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

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

What should methods do?

determine how the class will define its behaviors solve a problem

Semantic rules:

determine the meaning of instructions in a programming language.

Syntax rules:

determine the validity of instructions in a programming language.

logic

determines the exact order of instructions needed to produce the desired results

Chapter 1: Patterns aren't invented, they are

discovered

What is the format of System.out.printf("%3d#%2s#%3.2f\n", 1234, "Java", 51.6653);

displays 1234#Java#51.67

/=

divide and assign operator

do { i++; //more code }while (i<max)

do/while loop

What are static methods?

don't need to instantiate an object of the class to invoke the method.

-64 bits Range: -big to big

double

For numeric data types what declaration will always be used?

double

declare and define a double, a, from command line argument

double a = Double.parseDouble(args[0]);

double b = a / b, but a is an int. Cast int to double

double b = (double) a / b;

How could you define a real number named numero and initialize it to 867.5?

double numero = 867.5

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)

//

double slash; marks the beginning of a comment (a statement ignored by the computer)

declare and initial double array, points, with length N

double[] points = new double [N];

Math.exp(x)

e^x

keywords

each languages limited vocabulary

Arrays.toString(values) = [4,7,9...]

elements separated by commas with brackets

Chapter 1: We often try to take what varies in a system and

encapsulate it

for (typeName variable: array/collection) { sum = sum + variable; }

enhanced for loop for arrays; adds each element of array to sum (declared before loop)

Your classes should generally have both an _______ method and a _____ method.

equals && toString

Method returning true if this string is = to string 2

equals(s1)

\\

escape character for backslash

What is a conditional expression ?

evaluates a condition based on an expression

Exception Handling

events (e.g., errors) that disrupt the normal flow of execution. Examples of software exceptions: - Dividing by zero. - Using an unassigned object reference (that points to null) to invoke a method. - Failure to open/read/write/close a file. - Failure to open/read/write/close a socket connection. - Database errors. when a program executes, described as a call stack, ordered list of the active methods called up to the current point in time. stack starts with the main entry point and documents the active methods that are currently under call. once an exception occurs, it must be handled, or the program aborts. the JVM marches through the call stack looking for the nearest handler for the exception. If one is found, control is transferred. Otherwise, the program terminates.

In Java, the strange events that might cause a program to fail are called

exceptions

Defining Exceptions

exceptions are classes that extend the class Exception either directly or indirectly. For example, just a few of the many exceptions defined by the Java API. public class ClassNotFoundException extends Exception {...} public class IOException extends Exception {...} public class NullPointerException extends Exception {...} public class NumberFormatException extends Exception {...} The Exception class, most of its behavior is inherited from a base class named Throwable, which defines a message (String) property and a corresponding accessor, getMessage(). defining a custom exception that denotes a failed login: public class LoginFailedException extends Exception { public LoginFailedException() { super(); } public LoginFailedException(String msg) { super(msg); } } when defining your own exceptions, provide at least two constructors, default constructor and a constructor that takes a message string as a parameter. In both cases, the base constructor of Exception is invoked using the keyword super.

Comments

explanatory sentences inserted in a program in such a manner that the compiler ignores them

Mixed-mode arithmetic

expressions imvolving integers and floating-point values

A java monitor must either extend Thread....

false

a signed data type

false

a thread wants to make a second thread ineligible

false

If 1 of the operands of an && is false then the expression is _____?

false--- this is also known as the short-circuit AND operator

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.

how do you define a constant?

final double NUMBER1=4.5; or final double PI=3.14;

Constant definition

final typeName variableName = expression;

suppose a method called finallyTest()

finally block will always exe

optional 3rd block of code in a try/catch that executes NO MATTER WHAT:

finally{ }

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

-32 bits Range: -big to big -Must put an f at the end of the value EX: 98.6f; <--- f won't print

float

which line is not compiled

floater = ob

For loop structure

for ( <initialization>; <continuation test>; <update>) { <statement>; ... <statement>; }

HashMap<String,String>: iterate and print keys/values

for (String key : loans.keySet()) { System.out.println("key: " + key + " value: " + loans.get(key)); }

The "for each" loop

for (Type variable: collection) statement;

The for Statement

for (initialization; condition; update) statement;

What is the format for a, for, statement?

for (initialization;loopContinuationCondition;increment) statement (Initialization=declared variable and value) (loopContinuationCondition=i<5) (Statement=(println)

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

for loop (use i and N)

for (int i = 0; i < N; i++) { }

How do you make loops?

for (int i; i < 10; i++) { //Program }

What is the syntax of a looping control flow example?

for (int i=1; i<10; i++) { ... } while (x < y) { ... } do { ... } while (x<y)

Loop count to 10

for(count = 0; count<11: count++);

debugging

freeing the program of all errors

System.out.println("fun\tny"); prints out

fun ny

System.out.println("funny"); prints out

funny

Collection Interface

general abstraction for a collection of objects. It provides a handful of methods that operate over all interfaces that extend Collection. <<interface>> Collection +add(E) : boolean +addAll(Collection) : boolean +clear() : void +contains(Object) : boolean +containAll(Collection) : boolean +isEmpty() : boolean +remove(Object) : boolean +size() : int Java API does not provide any direct class implementations of interface Collection. Instead, implementations are provided for interfaces that extend Collection, namely, List, Set, and Queue. Nevertheless, the Collection interface is often used to pass collections around since it represents the base behavior of all collections. We'll now take a look at List, Set, and Queue and see how they might be used in our Library application.

Naming standard for accessor method?

getABC();

I return something by definition.

getter

These help create encapsulation.

getter, setter, public, private

array.length

gives the length of the array (no parentheses!)

public static double cubeVolume (double sideLength)

header for method

/t

horizontal tab; causes the curson to skip over to the next tab stop

outer:for...

i=1; j=0;

class Xyz

iAmPublic iAmPrivate iAmVolatile

How do you make if...else statements?

if (arg) { } else { } if (arg) { } if (arg) { } else if (arg) { } else { } For example if (e < 10) { //What happens if e < 10 } else { //What happens otherwise } Switch statements are better for if...else if...else.

The if Statement

if (condition) statement; else statement;

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) { }

if / else

if (true) { } else { }

What is the syntax of a decision control flow example?

if (x == y) { ... } else { ... } switch (index) { case 0: {...} case 1: {...} default: {...} }

if (condition) { statements1 } else { statements2 }

if statement (else not required in all cases)

The first concrete class to extend an 'abstract' class must ...

implement all of its 'abstract' methods.

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).

'abstract' methods must be ...

implemented by a subclass, so they must be inheritable.

Interfaces can be ...

implemented by any class, from any inheritance tree.

'abstract' methods are declared, with a signature, a return type, and an optional throws but are not ...

implemented.

Importing a Class from a Package

import packageName.ClassName;

import java.util.Scanner

imports Scanner library

Wildcard import

imports all the classes in a package. EX: • import javax.swing.* imports all classes from package javax.swing. import javax.swing.*;

Graphics context

in java, an object associated with a component where the images for that component are drawn

what are the members of a class?

include fields and methods and may also include constructors and initializers

++/--

increment/decrement; add 1 to/subtract 1 from the variable

\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.

procedures

individual operations grouped together for connivence -in Java also called methods

If a superclass member is public, the subclass ...

inherits it - regardless of package.

A for loop is functionally equivalent to the following while loop structure:

initialization; while ( condition ) { statement; increment; }

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();

Only setters should update these.

instance variables

The 'transient' modifier applies only to ...

instance variables.

The 'volatile' modifier applies only to ...

instance variables.

An 'abstract' class cannot be ...

instantiated.

-32 bits Range: -2,147,483,648 to 2,147,483,647 No rules

int

Declare and define integer a from double, b.

int a = (int) b;

declare and define command line integer argument, a

int a = Integer.parseInt (args[0]);

declare a as an int

int a;

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)

Declare & Initialize a variable

int n = 5;

Declare a variable

int n;

How could you define an integer named num and initialize it to 394?

int num = 394;

1. Define a variable that = to ten. 2. Create a while loop that prints you name tens time.

int ten = 10; while(copies > ten) { System.out.println("Reynald"); copies --; }

Name the 6 numeric data types

int, double, short, long, byte, and float

Numeric Data Sub-Types

int, long, float, double

declare and initial int array, number, with length N

int[] number = new int [N];

1. Create an Array called 'number' w/ 3 slots 2. Write out the 2nd number

int[] numbers = new int[3];

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 is the body of a class

is a set of members enclosed in curly braces

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

Literals

items whose values do not change, like the number 5.0 or the string "Java"

'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

Identifiers may contain ...

letters, digits and the underscore character

What could a object be compared to for similarity?

like base blocks that are interchangeable in how they can be used in other programs.

class SuperDuper

line 3: private; line 8: protected;

Racoon,SwampThing,Washer

line 7 will not compile ( phải ép kiểu )

statements

lines of code in java

LinkedList: peek methods

list.peek(); //peeks head list.peekLast(); // peeks last element

API documentation

lists the classes and methods of the Java library

&&

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'.

^

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;'.

-64 bits Range: -big to big No rules

long

/* */

long comments

INCORRECT..ServerSocket class

make new object avaiable... call its accept()

Helper methods should be

marked as private

static

means the method is accessible and useable even though no methods of the class exist

I can have many arguments.

method

How should we create methods?

method decomposition parameters

public static void main(String [ ] args)

method header;

static method

method invoked WITHOUT creating an instance of the class → use "STATIC" in method declaration

length() method

method which counts the number of characters in a String

trim() method

method which removes leading and trailing spaces from a String

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

syntax error

misuse of the language

prevent user input to other windows

modal dialog

'final' is the only ...

modifier available to local variables.

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.

ArrayList: add "hi"

myArr.add("hi");

ArrayList: add "hi" to ArrayList at index i

myArr.add(i,"hi");

ArrayList: check if list contains item

myArr.contains(item);

ArrayList: grab item at index i

myArr.get(i);

ArrayList: get first index of item

myArr.indexOf(item);

ArrayList: get last index of item

myArr.lastIndexOf(item);

ArrayList: delete item at index i

myArr.remove(i);

ArrayList: replace item at index i with new item

myArr.set(i, newItem);

ArrayList: get size

myArr.size();

HashMap: see if map contains a key

myMap.contains("key");

HashMap: get value string from key string

myMap.get("key");

HashMap: get a Set of the keys

myMap.keySet();

HashMap: insert a key string and a value string

myMap.put("key","value");

HashMap: get a Collection of the values

myMap.values();

Initialize a variable

n = 5;

Identifier

name of a variable, method or class

Length method

name.length()

final int VOLUME = 8

names constant integer

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.

Keyword: new

new - creates Class objects and a constructor as shown below: Book book1 = new Book(); Book book2 = new Book("SomeTitle", "SomeAuthor", false); Constructors are invoked with the "new" keyword as shown below: Book book1 = new Book(); Book book2 = new Book(1); Book book3 = new Book(1, "Gone with the Wind", "Margaret Mitchell"); Using a constructor that allows you to initialize the object with passed-in parameters. Using the default constructor, followed by the invocation of set(...) methods.

______\n______ is the escape sequence for

new line

Array Construction

new tymeName[length];

instantiation operator

new, third highest precedence, right to left association

/n

newline; advances the curson to the next line for subsequent printing

String input

next() nextLine()

String input = in.next();

next() reads the next string; returns any charas that are not white space

byte input

nextByte()

double input

nextDouble()

float input

nextFloat()

int input

nextInt()

short input

nextShort()

Is the break statement on a switch needed for the last statement/default?

no

Primitive data types

numbers, characters, and Booleans. combined in expression with operators

Method call

object.methodName(parameters);

Chapter 1: Patterns are proven

objectoriented experience

Integer.parseInt or Double.parseDouble

obtains the integer value of a string containing the digits

Method overloading

occurs when a class contains more than one method with the same name. Within a class, methods can have the same name if there's difference: The number of parameters. And/or the type parameters. And/or order of parameters. The determination of which overloaded method to invoke is a compile-time decision; hence, it is sometimes referred to as static binding. Library library = new Library(); Book book = new Book(); library.add(book); User user = new User(); library.add(user); Notice that the statement library.add (book) is clearly targeting the add (Book) method because of the parameter data type, Book. Similarly, the statement library.add(user) is clearly targeting the add(User) method because of the parameter data type, User. Since these decisions can be determined at compile time, the binding is said to be static.

A class can extend only ...

one class (no multiple inheritance), but it can implement many interfaces.

Interfaces can extend ...

one or more other interfaces.

All instances shares ...

only one copy of a 'static' variable/class.

/** */

opening comments

{ }

opening/closing braces; encloses a group of statements, such as the contents of a class or a method

( )

opening/closing parentheses; used in a method header

*

operator for multiplication

-

operator for subtraction

+

operator to concatenate strings

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

ad hoc polymorphism

overloading and coercion are two special kinds of ad-hoc polymorphism

'final' methods cannot be ...

overridden in a subclass.

'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

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

to swap values of integers you need a...

place holder

Prints to the current line(single function)

print

Prints x on the same line

print(x)

displays the sequence of method calls that led to the statement that generated the exception.

printStackTrace()

Prints a formatted string

printf

Prints to a new line and flushes the buffer.

println

Prints x on the same line, then moves the cursor to the next line

println(x)

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.print

prints statement

System.out.println

prints statement and creates new line

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

commands

program statements

source code

programming statements written in a high level programming language

Applets

programs imbedded in a web page

URL referring to databases

protocol:subprotocol:datasourcename

I shouldn't be used with instance variables

public

How to define a class?

public class "class name" (no extension)

Constructor syntax

public class Book { // properties private String title = null; private String author = null; private boolean isCheckedout = false; // constructors public Book() { } public Book(String title, String author, boolean isCheckedout) { this.title = title; this.author = author; this.isCheckedout = isCheckedout; } } Two constructors: Book(), which is known as the default constructor Book(String title, String author, boolean isCheckedout) Default constructor - typically used to initialize properties to their "null" values, unless it is done when they are declared, then there is no need to have the first constructor. The 2nd constructor above, takes the passed parameters and assigns them to the class's properties (i.e., data members) using the keyword "this".

Basic definition of class for Book (library program)

public class Book { // properties private String title = null; private String author = null; private boolean isCheckedOut = false; // behavior public void checkOut () { isCheckedOut = true; } public void checkIn () { isCheckedOut = false; } }

first line of program, HelloWorld

public class HelloWorld

Syntax to define a class

public class SomeClassName { // class properties and behaviors (methods) go here } keyword "public" is an access modifier, keyword "class" identifies the construct (i.e., the item) as a class definition, class name may contain alpha numeric characters, underscore, and $ (last two are rarely used). By convention, class names always start with an upper case letter, using CamelCase if there are more than one word.

write and instance field

public double r;

instance field

public double r; ( any field declared without the static modifier is an instance field)

Enum: Instantiate Enum for days of the week

public enum Day{ Monday(0),Tuesday(1), Wednesday(2), Thursday(3),Friday(4),Saturday(5),Sunday(6); private int value; private Day(int v){value = v;} public int getValue(){return this.value;} } //values() returns array of all constants defined in enum // valueOf() returns Enum with name matching to String passed to valueOf // Day.name() returns string name of enum

Classes can have only ...

public or default access.

Build a return method

public return

Write a class method

public static double radiansToDegrees (double radians) { return radians * 180 / PI; }

Constants declaration

public static final NAME = value;

Write a class field

public static final double PI=3.14159

How do you make a main method?

public static main(String[] args) { //Your program goes here! }

main loop

public static void main (String[] args)

Standard Starting, to start code block?

public static void main(String[] args) { //code goes here }

How do you create a method?

public void (method name)((arguments)) { } For example, public void greetYou(String greeting) { //Your program here! }

a programmer needs to create a logging method

public void logIt(String...msgs)

Build a void method

public void main

Given this method below, implements 'continue' or 'break' statement if color is 'green' public void printColors() { String[] colors = new String[] {"red","blue", "green","yellow"}; for (String c : colors) { System.out.println(c); } }

public void printColors() { String[] colors = new String[] {"red","blue", "green","yellow"}; for (String c : colors) { if("green".equals(c)) continue; System.out.println(c); } }

Members can use all four access levels:

public, protected, default, private.

access modifier

public, protected,private

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

'final' variables cannot be ...

re-initialized once assigned a value.

Scanner in = new Scanner(new File("input.txt");

reads input from a file (also declared in same line)

java SentinelDemo < numbers.txt

redirects input

==,!=,>,<,>=,<=

relational operators; equal, not equal, greater than, less than, greater than/equal to, less than/equal to

Set Interface

represents a collection of objects with no duplicates. By default, duplicates are identified by their equals(Object) method whose default behavior is defined in the root class Object. In other words, if equals(Object) is not overridden, object references will be used to determine if list entries are equal. If this behavior is not desired, equals(Object) needs to be overridden in the class for which objects are added to the set. A portion of the Set API is shown below. <<interface>> set +add(E) : boolean +addAll(Collection) : boolean +clear() : void +contains(Object) : boolean +containAll(Collection) : boolean +isEmpty() : boolean +remove(Object) : boolean +size() : int suppose the Library system has a business rule that prevents users from checking out more than one copy of a given book. During the checkout process, the user's books could be added to a Set collection where duplicate books are not added to the set. private Set booksCheckedOut = new HashSet(); public boolean checkout(Book book) { return booksCheckedOut.add(book); } The above method returns true if the book is not already in the set; otherwise, it returns false. If false is returned, the user would be notified that the duplicate book could not be checked out. Implementations of the Set interface include HashSet and TreeSet. The order of elements in a Set depends on the underlying implementation, and thus, will vary across implementations. If order is important, the interface SortedList should be used.

short type

represents an integer in the range from -215 (-32768) to 215-1 (32767) • Primitive

Queue Interface

represents an ordered collection based on some known order: e.g., first in first out (FIFO), last in first out (LIFO, a.k.a. a stack), priority. A subset of the Queue API is shown below (not including the methods inherited from interface Collection). <<interface>> Queue +element() : E +offer(E) : boolean +peek() : E +poll() : E +remove() : E order of the queue is determined by the implementing class. Classes that implement the Queue interface include LinkedList and PriorityQueue. As an example, suppose the Library system solicits user suggestions, and these suggestions need to be processed in a FIFO basis. private Queue suggestions = new LinkedList(); public void addSuggestion(Suggestion suggestion) { suggestions.add(suggestion); } The above method adds the new Suggestion to the Queue. Because the implementing class is a LinkedList, each suggestion is added to the end of the queue.

List Interface

represents an ordered sequence of objects. That is, elements are added to the list in a particular order, and the list maintains that order. suppose we have a List, booksCheckedIn, which contains all the books that are checked-in on a given day. Then, if we add books to the list as they are checked-in, the list will maintain the order in which they were checked-in. private List booksCheckedIn = new ArrayList(); public void checkin(Book book) { booksCheckedIn.add(book); } Implementations of the List interface include ArrayList, LinkedList, Stack, and Vector. List collections do not check for duplicate entries, so if an object is added multiple times, it will appear in the list multiple times (i.e., have multiple entries). Therefore, if it's important for a given object to appear only once in the collection, the Set interface should be used as explained below.

Declaring Exceptions

required that if a method throws an exception without catching it, the exception must be declared in the method signature to notify users. method that authenticates logins, throws an exception named LoginFailedException without catching it: public bool authenticate(Login login) throws LoginFailedException {...} Any exception that occurs in a method must either be handled (caught) by that method or be declared in its signature as "throws" (see above). method throws (and does not handle) multiple exception types, instead of listing all the exceptions in the method signature, the base exception class Exception can be listed: public bool authenticate(Login login) throws Exception {...} declaration covers all possible exception types, and thus prevents you from having to list the individual exceptions when multiple exceptions can be thrown.

in.useDelimiter("[^A-Za-z]+");

restricts input to only letters, removes punctuation and numbers

console.nextDouble():

retrieves that floating-point number, if the value of this expression is that floating-point number.

I always fly solo.

return

What keyword is used to jump out of a try block and into a finally block?

return

The return Statement

return expression;

return volume;

return statement that returns the result of a method and terminates the method call

/r

return; causes the cursor to go to the beginning of the current line, not the next line

str.charAt(pos)

returns the character (char) at position pos (int) in the given string

str.length()

returns the number of characters in the given string (int)

str.indexOf(text)

returns the position (int) of the first occurrence of string (text) in string str (output -1 if not found)

str.substring(start, end)

returns the string starting at position (start) and ending at position (end-1) in the given string

Syntax to define a method (behavior (function in C++))

returntype methodName(optional_list_of_arguments) { ...} Names of properties (variables) and methods should start with a lower case letter, using camelCase if multiple words.

Chapter 1: Good OO designs are

reusable, extensible and maintainable

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

syntax

rules of a computer language

If a class implements the Runnable interface, what methods must the class contain?

run()

This method is the engine of a threaded class.

run()

LinkedList: remove methods

same as arraylist remove methods, but also: remove(); // removes first item from list removeLast(); //removes last item from list

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

Objects

sent messages

.

separates package names / adds folders

What is the method signature of public void setDate(int month, int day);?

setDate(int, int);

Naming standard for mutator method?

setXYZ();

By definition, I take one argument.

setter

char newChar = (char)(mychr + x)

shift character by x numbers (use ASCII table values)

-16 bits Range: -32,768 to 32,767 No rules

short

//comment

short comments

Math.sin(x)

sine of x (x in radians)

programming vs natural languages

size, rigidity, literalness

Statements

smallest executable unit in Java, each one ends in a semicolon.

aggregation

special form of association representing ownership of a relationship bw obj's

Sentinel value

special input value signifying → end of input

Class Constructors

special methods that are called when a class is created. Must have the same name as the enclosing class, and are declared with no return value (the implied return type of the constructor is the enclosing class type). public Book() {...} public Book(int id) {...} public Book(int id, String title) {...} public Book(int id, String title, String author) {...} public Book(int id, String title, String author, int pages) {...} Constructors can be overloaded. Once you define at least one constructor (whether default or not), the implicit, hidden default constructor is not provided for you. used to initialize the data members of the newly created object either by assigning default values or by using the passed-in parameters. Constructors can also invoke other constructors either in the same class or in a base class. public Book(int id) { super(id); } Above uses "super" keyword to invoke a constructor in the base class LibraryItem. Constructors are invoked with the "new" keyword

Public Interface

specifies what you can do with its objects

Math.sqrt(x)

square root of x

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

Calling a thread's _____ method causes its _____ method to be called

start() & run()

To run a thread what method must be callled?

start() method

Character.isDigit(ch)

statement (boolean), ch (char); allows you to check if ch is a digit or not

Character.isLetter(ch); Character.isUpperCase(ch); Character.isLowerCase(ch); Character.isWhiteSpace(ch);

statement (boolean), ch (char); allows you to check if ch is a letter/uppercase/lowercase/whitespace

while (condition) { statements }

statements = body of while loop; braces not needed for a single statement

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 }

Object references

stored in Object variables and denotes the memory location of an Object

String: get char at index i

str.charAt(i);

String: get first index of substring

str.indexOf(char); // returns -1 if doesn't exist

String: get last index of substring

str.lastIndexOf(char); // returns -1 if doesn't exist

String: get substring "He" from "Hello"

str.subString(0,2); // begin index is inclusive, end index is exclusive

String: remove whitespace

str.trim();

String: concatenate two strings

str1.concat(str2); str1 + str2;

String: compare two strings

str1.equals(str2)

/** Computes the volume of a cube. @param sideLength the side length of the cube @return the volume */

structure for commenting before methods (javadoc)

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.

'private' members are not visible to ...

subclasses, so private members cannot be inherited.

-=

subtract and assign operator

Maps

supports the ability to add and retrieve items from a collection using a key value pair. The key (K) is the lookup identifier and the value (V) is the item being looked up. The methods for inserting/retrieving items in/out of the Map are put(...) and get(...). General accounts - For general public use. Business accounts - For commercial organizations. Nonprofit accounts - For nonprofit organizations. The above account types can be abstracted as a Java enum (enumerator): enum AccountType {general, business, nonprofit}; Each user is allowed to have one account of each type. Accounts for a given user could be contained in a Map data structure where the key for each account is one of the above enum values (general, business, or nonprofit) as shown below: Account generalAccount = new Account(); Account businessAccount = new Account(); Account nonprofitAccount = new Account(); //... Map<AccountType, Account> accountsMap = new HashMap<AccountType, Account>(); accountMap.put(AccountType.general, generalAccount); accountMap.put(AccountType.business , businessAccount); accountMap.put(AccountType.nonprofit , nonprofitAccount); Retrieval of the accounts from the map is then achieved with the key: Account generalAccount = accountMap.get(AccountType.general); Account businessAccount = accountMap.get(AccountType.business); Account nonprofitAccount = accountMap.get(AccountType.nonprofit); In summary, the key is used to place values in the map and also to retrieve values from the same map. advantage, code readily accommodates additional account types. simply add to the enum type: enum AccountType {general, business, nonprofit, government, education};

How do you set up a switch method?

switch () Case #: (statement)(++acount) (break;) Case #: (statement) (break;) Case #: (statement)

An example of a switch statement:

switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; default: misc++; }

How do you make a Switch statement?

switch (var) { case 1://if var = 1 //What happens break; case 2 ://if var = 2 //What happens break; default://Otherwise //What happens break; }

Switch statement

switch (variable you're check against) { case label: code; break; default:

_______\t________ is the escape sequence

tab

Math.tan(x)

tangent of x

throws FileNotFoundException

terminates main if FileNotFoundException occurs

for (initialization; condition; update) { statements }

terminating loop

inheritance

the ability to create classes that share the same attributes and methods of existing classes but with more specific features

passing arguments

the act of sending an argument to a method

condtion must be true....throw AssertionError

the application must be run... the args must have one or more...

'private' methods can be accessed only by ...

the code in the same class.

'this .' always refers to ...

the currently executing object.

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.

INCORRECT..Socket

the java.net.Socket... contain code... know how.. communicate server .. UDP

An object reference marked 'final' does not mean ...

the object itself immutable.

Origin

the point (0,0) in a coordinate system

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

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;

A parameter is a local variable initialized to....

the value of the corresponding argument. (Known as Call-by-value)

state

the values and properties of an object

method

the verbs of a program

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)

Chapter 1: Patterns don't give you code

they give you general solutions to design problems. You apply them to your specific application.

Keyword: this

this - used to disambiguate the overloaded use of variable names; in particular, "this" can be used to reference a data member (defined in the class) when that name is identical to a passed parameter. assigns the input parameter, title, to the data member, title: private String title = ""; public void setTitle(String title) { this.title = title; } inside the method setTitle(String title), the passed parameter, title, hides the data member, title, defined in the class. To access to the title data member, the keyword "this" is used to indicate a data member of the object is being referenced (and not a local variable inside the method).

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.

Why do we use interfaces?

to formally define the way we can edit a class

code fragmanet, sbuf references.. sbuf.insert

true

If 1 of the operands of an || is false then the expression is _____?

true -- this is also known as the short-circuit OR operator

boolean

true or false

to "catch" a exception you must surround it with a ____ & _______

try & catch

.... native client library....

type 2

...pure java...communicate with middleware server....

type 3

... pure java... implement the network protocol

type 4

Variable definition

typeName variableName = value;

double blah = (int) (blah + 3)

typecast; change variable type

valid identifiers

tất

WAN

undisciplined; unrestrained; reckless

No classes instances are needed in order to ...

use 'static' members of the class.

Escape character (\)

used in codes to represent characters that cannot be directly typed into a program

JFrame

used to show a frame(window)

()

used to surround perimeters

escape character

used when including 'special characters' in string literals

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){ }

string Var = "Hello"

variable Var = Hello (*double quotes!)

char answer = 'y'

variable answer = y (*single quotes!)

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();

Method call/actual and formal for method name; Return value, no parameters

variableName = methodName(); public static int methodName():

Assignment

variableName = value;

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

Constants

variables whose values cannot change

Chapter 1: Most patterns allow some part of a system to

vary independently of all other parts

Chapter 1: Patterns give us a shared _______

vocabulary

public static void boxString(String contents)

void methods return no value, but can produce output

INCORRECT..deserialization

we use readObject()... to deserialize

run-time errors

when a computer is asked to do something that is considered illegal

Method Overriding

when a method in a base class is repeated (redefined) in a derived class signature of both methods must match identically override its behavior in the LibraryItem to output the item's id and title as shown below: public class LibraryItem { ... public String toString() { return "LibraryItem, id=" + id + ", title: " + title; } } can invoke toString() to get a meaningful description of the object. Also true if the object is a Book, Audio, or Periodical because they inherit LibraryItem. Object obj = new Book(1, "Catch-22", "Joseph Heller", 485); String s = obj.toString(); actual instance is a Book and Book "is a" LibraryItem which overrides toString(), the LibraryItem's toString() method is called. Example of polymorphic dynamic binding; dynamic because it's not known until runtime which toString() method is invoked; it depends on whether the method is overridden, and if so, where. Can override toString in each of the more specialized classes: Book, Audio, and Periodical: public class Book extends LibraryItem { public String toString() { return super.toString() + ", Author, =" + author; } } super.toString() in the above return statement; its purpose is to invoke the toString() method in the base class LibraryItem. So the Book's overridden toString() method calls the LibraryItem's toString() method and then appends to it the author information that's contained in the Book. This time, since Book has overridden toString(), which overrides LibraryItem.toString(), which overrides Object.toString(), it's Book.toString() that gets called, and not the ones declared in Object or LibraryItem: Object obj = new Book(1, "Catch-22", "Joseph Heller"); String s = obj.toString(); another example of method overriding, consider the method equals(Object obj) defined by the Object class. to compare the state of two objects, overriding equals(Object obj) as shown below for LibraryItem: public class LibraryItem { public boolean equals(Object obj) { if (this == obj) return true; if ( ! (obj instanceof LibraryItem)) return false; LibraryItem item = (LibraryItem)obj; if ( this.id != item.id ) return false; if ( ! this.title.equals(item.title)) return false; return true; } } @override annotation - applied to methods that are intended to override behavior defined in a base class. annotation forces the compiler to check that the annotated method truly overrides a base class method. package domain; public class LibraryItem { @Override public String equals(Object obj) { ... } @Override public String toString() { ... } }

variable declaration statement

when a program declares the type of a variable

syntax errors

when a syntax rule is violated

Importing packages

when classes are in defined in different packages. In order for ClassA, in packageA, to have visibility to ClassB, in packageB, one of three things must happen; either: - the fully qualified name of ClassB must be used, - fully qualified name of ClassB be must be imported with an import statement, - entire contents of packageB must be imported with an import statement. first technique is to use the FQN of the class. The FQN of ClassB is packageb.ClassB. to declare: package packagea; public class ClassA { packageb.ClassB b = new packageb.ClassB(); } better technique is to use an "import" statement: package packagea; import packageb.ClassB; public class A { ClassB b = new ClassB(); } import statements must appear after the package statement, and before the data type (class, interface) definition more efficient technique is to import all the data types from a given package using the * notation: import packageb.*; if multiple packages have classes with the same name, use long way (FQN) of importing package: package1.ClassXYZ xyz = new package1.ClassXYZ()

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

The while Statement

while (condition) statement;

while

while (true) { }

Cat, Washer,SwampThing

will compile... exception line 7...cannot be converted

keywords

words in java that cannot be used as user-defined symbols

PrintWriter out = new PrintWriter("output.txt");

writes output to a file "output.txt"

import x.y.z

x - overall name of package, y - name of package subsection, z - name of particular class in subsection

What is this "x+=3" the equivalent of?

x = x + 3;

x = a++ + b++

x tổng cũ, a,b tăng 1

Postincrement

x++ "Give me x, then increment"

An increment operator

x+++

Example using compound assignment

x+=1 • which is the same as → x = x + 1

A decrement operator

x--

Postdecrement

x-- "Give me x, then decrement"

int[]x

x[24] = 0; x.length = 25;

Math.pow(x,y)

x^y (x>0, or x=0 and y>0, or x<0 and y is an integer)

Can you have 2 action listeners?

yes, but not ideal

Method overloading

you can define methods w.the SAME NAME in a class IF: • Enough difference in their parameter profiles.

monitor called mon ... 10 threads... waiting pool

you cannot

Block statement

{ statement; statement; }

What must every method and class have an open and closed of?

{ } (braces, or curly brackets)

Uses a phone line & can transfer data in a speed 20 x faster vs. regular modem.

• DSL (digital subscriber line)

The amount of space bw pixels. If higher/lower = better resolution

• Dot pitch • Smaller the dot pitch → better the display.

long type

• represents an INTEGER ranging from -263 to 263-1 • Primitive variable vs. integer - ranges → -231 (-2147483648) to 231-1 (2147483647).


Related study sets

Chapter 8, Legal Environment of Business

View Set

Chapter 10: Government Health Insurance Programs: Medicaid, CHIP, and Medicare

View Set

Chapter 8 Political Participation & Voting

View Set

MOP Chapter 16 Medical Insurance

View Set