0% found this document useful (0 votes)
65 views38 pages

Intro Java

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 38

Basics in CS

- What is computer science?


- What are algorithms?
- Representing algorithms in pseudo-code
- Basic algorithm analysis
- Binary and linear search,
- Insertion and selection sort.
- Efficiency (time complexity)
- Representing information using bits
Jaba Programming Skills
- Variable assignment
- Primitive data types
- Byte - 1
- Boolean - 1
- Char - 2
- Short - 2
- Int - 4
- Long - 8
- Float - 4
- Double - 8
- Control structures.
- Loops
- for
- for (int i = 0; i<5; i++)
- Enhanced for
- for(element: array)
- While
- while(x<2)
- Conditionals
- if/else and boolean operator (==, !=, >, <, &&, ||)
- Writing Classes
- Class header: public class ClassName{
- Instance variables
- Unique for every instance of the class
- Declared in the beginning of the program
- private variableName;
- public variableName;
- Methods
- Method signature is just the main(string[] args) part
- Method header is the method signature + the visibility/accessibility
modifier (public/private) + the return type (void or primitive)
- Accessor method: does not change the data, just returns the value
- Mutator method: changes the data, does not return anything (void)
- Static methods
- Methods that belong to a class
- The implicit parameter is a class
- Static variables
- Variables that belong to the class, NOT unique for every instance of the class
- Declared like any other variable: public static variableName;
- Parameter passing
- Passing actual parameters (given during method invocation) into formal
parameters (given in the method header)
- Passing primitives
- Passing object references
- Designing better classes
- File I/O
- Can use scanners to get input from a text file instead of just the user keyboard
- import java.util.Scanner;
- Scanner name = new Scanner(System.in) → reads inputs from keyboard
- Scanner name = new Scanner(“input.txt”) → reads inputs from a text file
called input.txt
- Creating input streams
- Create a new file object
- File inFile = new File (“name.txt”);
- The scanner can read input from the file
- Scanner scanner= new Scanner(inFile);
- PrintWriting (output writing to a new text file)
PrintWriter output= new
PrintWriter(“newFile.txt”);
while(scanner.hasNext())
{
String text = scanner.next();
output.println(text);
}
output.close();

- Exceptions
- Not fatal (unlike an error)
- Allow the program to run, but the exception will stop the program
- Ex: string index out of bound, array index out of bound
- Exception handling
- Try/catch block
- Put the code that may result in an error in the try block
- Catch (Exception e) → if the code does result in an error, call the
catch block
- Throws
- public void methodName () throws Exception {} → in method
header
- Tells java that you recognize the method may result in an
exception, but you will handle it later (exception suppressing)
- Throw
- throw new Exception e; → within method body
- Calls java to throw the exception
- Handles it immediately
- Interfaces
- An abstract class that is implemented by other classes
- Different classes (dog, pig, chicken) can implement the Animal interface, but their
actual execution of these methods is different.
- Comparable interface
- Any class that contains a compareTo() method
- Can compare instance variables of your choice
public static compareTo(type other)
{
if(this.variable > other.variable)
return 1;
else if(this.variable < other.variable)
return -1;
else if(this.variable == other.variable)
return 0;
}

- Generics
- ArrayList
- ArrayLists that can hold any type of object, defined by whatever is
provided as the actual parameter
- Keeps the method generic, easily applicable to any case
- ArrayList <T> = new ArrayList<T>
- T is whatever is provided
- Can be ArrayList<Integer> or ArrayList<String> or whatever T
ends up being during compile time!
- Generic method
- Method with a type parameter
- public static <T> void methodName()
- Don’t need to specify type to use for the type parameter when you call the
generic method
- Just call the method with appropriate arguments, and the compiler will
match up the type parameters with the argument types
- Can have type parameters restrictions
- public static <T extends Comparable> void methodName();
- Arrays and ArrayLists
Array ArrayList

- Immutable length - Flexible/adaptive length


- Can only hold one type - Can only hold one type
- Can hold primitives - Cannot hold primitives, must
use wrapper classes
type[] = new type[length]; - <Type>
OR type[] = new type[] {x, x, x};
ArrayList<type> = new
Methods: ArrayList<type>();
- .length
- array[i] to access an element Methods:
- Cannot add/remove elements - .size()
without making a copy/whole - .add(element)
new array - .add(i, element)
- Arrays.copyOf(oldArra - .remove(i)
y, length to copy to) - .set(i, element)
- .get(i)
- .contains(element)

- Error types
- Compile time
- Syntax error
- Compiler just does not understand what you wrote, will not even compile
- Runtime
- Logical error
- Will compile, but the program will eventually hit a wall and terminate (ex:
StringIndexOutOfBounds)
- Data units
- Inheritance
- “Is a” relationship
- In contrast to interfaces, a class can only inherit from one parent class
- The subclass (child) is derived from the superclass (parent)
- Extends keyword at the top of the Class definition indicates inheritance
- Method overriding
- Creating different implementation for a method in the subclass
- When the method is called on the subclass, the overridden method is
invoked instead of the parent’s original method
- Super keyword
- Refers to the parent class
- If you have an overridden method, and want to specifically call the parent
method instead
- EX: super.methodName();
- If you want to use the super constructor instead
- EX: super(parameters);
- Polymorphism

BankAccount a = new CheckingAccount("Gabbie");

- At compile time, a is a BankAccount


- At runtime, a is a CheckingAccount
- We are only able to execute methods that belong to the
BankAccount class
- The ‘base instantiation’ determines what is acceptable at
compile time
- At runtime the CheckingAccount version will run rather than the
BankAccount version
- The actual object instantiation determines what runs at
runtime
- Runtime Polymorphism
- Java decides the proper method to call at runtime, NOT
compile time
- At compile time, child class must have the same method as
declared in the parent class if method overriding
- At runtime, the specific implementation of the overridden
method is executed

Big Java
Chapter 1
- The central processing unit (CPU) performs program control and data processing.
- Storage devices include memory and secondary storage such as a hard disk.
- Java was originally designed for programming consumer devices, but it was first
successfully used to write internet applets.
- Java was designed to be safe and portable, benefiting internet users and students.
- Java programs are distributed as instructions for a virtual machine, making them
platform-independent.
- Java has a very large library.
- Classes are fundamental building blocks of Java programs.
- Every Java application contains a class with a main method; when the application starts,
the instructions in the main method are executed.
- Each class contains declarations of methods; each method contains a sequence of
instructions.
- A method is called by specifying the method and its arguments.
- A string is a sequence of characters enclosed in quotation marks.
- A compile-time error is a violation of the programming language rules that are detected
by the compiler.
- A run-time error causes a program to take an action that the programmer did not intend.
- An algorithm for solving a problem is a sequence of steps that is unambiguous,
executable, and terminating.
- Pseudocode is an informal description of a sequence of steps for solving a problem.
Chapter 2
- Objects are entities in your program that you manipulate by calling methods.
- A method is a sequence of instructions that access the data of an object.
- A class describes a set of objects with the same behavior.
- A variable is a storage location with a name.
- When declaring a variable, you usually specify an initial value.
- When declaring a variable, you also specify the type of its values.
- Variable names should start with a lowercase letter by convention.
- All variables must be initialized before they are accessed.
- The public interface of a class specifies what you can do with its objects; the hidden
implementation describes how these actions are carried out.
- An argument is a value that is supplied in a method call.
- The return value of a method is a result that the method has computed.
- Use the new operator followed by a class name and arguments to construct new objects.
- Rectangle box = new Rectangle(5, 10, 20, 30);
- box = new Rectangle(4, 5, 25, 35); // to reset
- An accessor method does not change the internal data of the object on which it is evoked.
- Ex: the length method for strings.
- A mutator method changes the data.
- Ex: the toUpper method for strings.
- The API (application programming interface) documentation lists the classes and
methods of the Java library.
- Java classes are grouped into packages; use the import statement to use classes that are
declared in other packages.
- A test program verifies that methods behave as expected.
- Determining the expected result in advance is an important part of testing.
- An object reference describes the location of an object.
- Ex: in the statement Rectangle box = new Rectangle(5, 10, 20, 30); box refers to
the Rectangle object that the new operator constructed.
- Multiple object variables can contain references to the same object.
- Number variables store numbers; object variables store references.
Chapter 3
- An object’s instance variables store the data required for executing its methods.
- Each instance of a class is an object.
- An instance variable declaration consists of an access specifier (private), the type (int),
and the name.
- Each object of a class has its own set of instance variables.
- Private instance variables can only be accessed by methods in the same class.
- Encapsulation is the process of hiding implementation details and providing methods for
data access.
- Encapsulation allows a programmer to use a class without having to know its
implementation.
- Information hiding makes it simpler for the implementer of a class to locate errors and
change implementations.
- In order to implement a class, you need to know which methods are required.
- Constructors set the initial data for objects.
- The constructor name is always the same as the class name.
- The private implementation of a class consists of instance variables and the bodies of
constructors and methods.
- A unit test verifies that a class works correctly in isolation, outside a complete program.
- To test a class, use an environment for interactive testing or write a tester class to execute
test instructions.
- Local variables are declared in the body of a method.
- When a method exits, its local variables are removed.
- Instance variables are initialized to a default value, but you bust initialize local values.
- The use of an instance variable name in a method denotes the instance variable of the
implicit parameter.
- The this reference denotes the implicit parameter.
- It cannot be used in static methods.
- A local variable shadows an instance variable with the same name; you can access the
instance variable name through the this reference.
- Ex: public BankAccount(double balance){ this.balance = balance;}
- A method call without an implicit parameter is applied to the same object.
- Implicit parameter:
- public void monthlyFee(){ withdraw(10); }
- In this, withdraw is the implicit (invisible) parameter.
Chapter 4
- Java gas 8 primitive types, including four integer types and two floating-point types.
- Int 4 bytes, byte 1 byte, short 2 bytes, long 8 bytes, double 8 bytes, float 4 bytes, char 2
bytes, boolean 1 bit.
- A numeric computation overflows if the result falls outside the range for the number
type.
- Rounding errors occur when an exact representation of a floating-point number is not
possible.
- A final variable is a constant; once its value has been set, it cannot be changed.
- Declared in method: final double VALUE = 0.5;
- Declared in a class: public static final double VALUE = o.5;
- Mizing integers and floating point values in an arithmetic expression yields a floating
point value.
- The ++ operator adds 1 to a variable; the - - subtracts 1.
- If both arguments of / are integers, the remainder is discarded.
- The % operator computes the remainder of an integer division.
- The Java library declares many mathematical functions.
- You use a cast to convert a value to a different type;
- Double balance = total + tax;
- Int dollars = (int) balance;
- Use the scanner class to read keyboard input in a console window.
- Use the printf method to specify how values should be formatted.
- Strings are sequences of characters.
- The length method yields the number of characters in a string.
- Use the + operator to concatenate strings.
- Whenever one of the arguments of the + operator is a sting, the other argument is
converted to a string.
- Use the next method of the Scanner class to read a string containing a single word.
- String positions are counted starting with 0;
- Use the substring method to extract a part of a string.
- String str = “Sally”;
- String str2 = str.substring(1, 4); // “all”
- String str3 = str.substring(1); // “ally”
- String str4 = charAt(1); // ‘a’
Chapter 5
- Relational operators include <, >=, <, <=, ==, and !=.
- When comparing floating point numbers, don’t test for equality; instead, check whether
they are close enough.
- If (Math.abs(x - y) <= double)
- Do not use the == operator to compare strings; use the equals method instead.
- if(string1.compareTo(string2) == 0) // strings are equal
- If it's> 0, string 1 comes after string 2 in the dictionary order and vice versa for <.
- The compareTo method compares in lexicographic order.
- The == operator tests whether two object references are identical; to compare the
contents of objects, you need to use the equals method.
- The null reference refers to no object.
- When using multiple if statements, test general conditions after more specific ones.
- When a decision statement is contained inside the branch of another decision statement,
the statements are nested.
- Nested decisions are required for problems that have two levels of decision-making.
- Flow charts are made up of elements for tasks, input/output, and decisions.
- Each branch of a decision can contain tasks and further decisions.
- Black-box testing describes a testing method that does not take the structure of the
implementation into account.
- White-box testing uses information about the structure of a program.
- Code coverage is a measure of how many parts of a program have been tested.
- Boundary test cases are test cases that are at the boundary of acceptable inputs.
- Logging messages can be deactivated when testing is complete.
- The boolean type boolean has two values, true and false.
- Java has two Boolean operators that combine conditions && (and) and || (or).
- To invert a condition use the ! (not) operator.
- && and || are operators computed using short-circuit evaluation: as soon as the truth
value is determined, no further conditions are evaluated.
- De Morgan’s law tells you know how to negate && and || conditions.
- Call the hasNextInt or hasNextDouble method to ensure that the next input is a number.
Chapter 6
- A loop executes instruction repeatedly while a condition is true.
- An off-by-one error is a common error when programming loops.
- Hand-tracing is a simulation of code execution in which you step through instructions
and track the values of the variables.
- The for loop is used when a value runs from a starting point to an ending point with a
constant increment or decrement.
- The do loop is appropriate when the loop body must be executed at least once.
- A sentinel value denotes the end of a data set.
- You can use a boolean variable to control a loop.
- Set the variable before entering the loop, then set it to the opposite to leave the loop.
- Use input redirection to read input from a file.
- Use output redirection to capture program output in a file.
- A storyboard consists of annotated sketches for each step in an action sequence.
- Developing a storyboard helps you understand the inputs and outputs that are required for
a program.
- nextInt(n) returns a random integer between 0(inclusive) and n (exclusive)
- nextDouble() returns a random floating-point number between (inclusive) and 1
(exclusive)
- A debugger is a program that you can use to execute another program and analyze its
run-time behavior
- You can make effective use of a debugger by mastering just three concepts: breakpoints,
single-stepping, and inspecting variables.
- When a debugger executes a program the execution is suspended whenever a breakpoint
is reached.
- The single-step command executes the program one line at a time.
Chapter 7
- An array collects a sequence of values of the same type.
- Individual elements in an array are accessed by an integer index i using the notation
array[i].
- An array element can be used like any variable.
- An array index must be at least zero and less than the size of the array.
- A bounds error, which occurs if you supply an invalid array index, can cause your
program to terminate.
- Declaring an array:
- Int [] numbers = new int[10];
- Int[] squares = {0, 1, 2, 3};
- String[] friends = { “Emily”, “Bob”, “Cindy”};
- Use the expression array.length to find the number of elements in an array.
- An array reference specifies the location of an array.
- Copying the reference yields a second reference to the same array.
- Arrays can occur as method arguments and return values.
- With a partially filled array, keep a companion variable for the current size.
- You can use the enhanced for loop to visit all elements of an array.
- For (double element : values){ };
- Use the enhanced for loop if you do not need the index values in the loop body.
- A linear search inspects elements in sequence until a match is found.
- Before inserting an element, move elements to the end of the array starting with the last
one.
- Use the Arrays.copyOf method to copy the elements of an array into a new array.
- Two-dimensional arrays, or matrices, can be used to store tabular data.
- Int[][] counts = new int[countries][medals];
- Individual elements in a two-dimensional array are accessed by using two index values.
- Array[i][j]
- An ArrayList stores a sequence of values whose size can change.
- The ArrayList class is a generic class: ArrayList<types> collects elements of the
specified type.
- ArrayList<string> friends = new ArrayList<String>();
- Use the size method to obtain the current size of an array list.
- friends.size();
- Use the get and set methods to access an array list element at a given index.
- friend = friends.get(2);
- friends.set(2, “Carolyn”);
- Use the add and remove methods to add and remove array list elements.
- friends.add(1, “bob”);
- friends.remove(1);
- To collect numbers in array lists, you must use wrapper classes.
- byte - Byte, boolean - Boolean, char - Character, double - Double, float -
Float, int - Integer, long - Long, short - Short
- You can't say ArrayList<double>, you have to say ArrayList<Double>.
- If the size of a collection never changes, use an array.
- If you collect a long sequence of primitive type values and you are concerned about
efficiency, use an array.
- Otherwise, use an array list.
- A test suite is a set of tests for repeated testing.
- Regression testing involves repeating previously run tests to ensure that known failures of
prior versions do not appear in new versions of the software.
- In a statement that declares and constructs an array list, you need not repeat the type
parameter in the constructor; you can write ArrayList<String> names = sew
ArrayList<>(); instead of ArrayList<String> names = sew ArrayList<String>(); this is
called the diamond syntax.
Chapter 8
- A class should represent a single concept from a problem domain, such as business,
science, or mathematics.
- The public interface of a class is cohesive if all of its features are related to the concept
that the class represents.
- A class depends on another class if its methods use that class in any way.
- An immutable class has no mutator methods.
- References to objects of an immutable class can be safely shared.
- A side effect of a method is any externally observable data modification.
- When designing methods, minimize side effects.
- In Java, a method can never change the contents of a variable that is passed to a method.
- In Java, a method can change the state of an object reference argument, but it cannot
replace the object reference with another.
- An instance variable for the total is updated in methods that increase or decrease the total
amount.
- A counter that counts events in increments in methods that correspond to the events.
- An object can collect other objects in an array or ArrayList.
- An object property can be accessed with a getter method and changed with a setter
method.
- Ex; getName()
- If your object can have one of several states that affect the behavior, supply an instance
variable for the current state.
- To model a moving object, you need to store and update its position.
- A static variable belongs to the class, not to any object of the class.
- A static method is not invoked on an object.
Chapter 9
- Inheritance is a relationship between a more general class (the superclass) and a
specialized class (the subclass).
- A subclass inherits data and behavior from a superclass.
- You can always use a subclass object in place of a superclass object.
- A subclass inherits all methods that it does not override.
- A subclass can override a superclass method by providing a new implementation.
- Declare instance variables that are added to the subclass.
- Declare methods that are added to the subclass.
- Declare methods that are added to the subclass.
- The reserved word extends denotes inheritance.
- Public class Motorcycle extends Vehicle{ … }
- An overriding method can extend or replace the functionality of the superclass methods.
- Use the reserved word super to call a superclass method.
- Ex; public void deposit(double amount){ super.deposit(amount); }
- If you omit super, the method calls itself.
- Unless specified otherwise, the subclass constructor calls the superclass constructor with
no arguments.
- To call a superclass constructor, use the super reserved word in the first statement of the
subclass constructor.
- Public ChoiceQuestion(String questionText){ super(questionText); }
- The constructor of a subclass can pass arguments to a superclass constructor using the
reserved word super.
- A subclass reference can be used when a superclass reference is expected.
- When the virtual machine calls an instance method, it locates the method of the implicit
parameter’s class. This is called dynamic method lookup.
- Polymorphism allows us to manipulate objects that share a set of tasks, even though the
tasks are executed in different ways.
- In Java, every class that is declared without an explicit extends clause automatically
extends the class object; that is, the class object is the direct or indirect superclass of
every class in Java.
- Override the toString method to yield a string that describes the object’s state.
- If you want your toString method to be usable by subclasses of your class, call the
getClass method (which every class inherits from the Object class) to obtain an object
that describes the class and its properties, the invoke the getName method to get the name
of the class.
- Public string toString() { return getClass().getName() + …… }
- Then the toString method prints the correct class name when you apply it to a
subclass.
- In the subclass, you should override toString and add the values of the subclass
instance variables.
- You must call super.toString to get the instance variable of the superclass because
the subclass can’t access them directly.
- The equals method checks whether two objects have the same contents.
- If you know that an object belongs to a given class, use a cast to convert the type.
- The instanceof operator tests whether an object belongs to a particular type.
- When you extend an existing class, you might be forced to override a method because
there is no good default for the superclass and only the superclass programmer can know
how to implement the method properly.
- Instead of having the method do nothing, the method can be declared as an
abstract method.
- Public abstract void name();
- An abstract method has no implementation, forcing implementors of subclasses to
specify concrete implementations of this method.
- A class for which you cannot create objects is called an abstract class.
- A class for which you can create objects is called a concrete class.
- Sometimes you may want to prevent programmers from creating subclasses or from
overriding certain methods.
- In this situation, use the final methods and classes.
- Public final class String { … }
- That means nobody can extend the String class.
- When a method wants to access the instance variable of the superclass, the superclass can
declare an instance variable as protected.
- Protected String text;
- Protected data in an object can be accessed by the methods of the object's class
and all its subclasses.
- This is in the middle of absolute protection (private instance variables) and no
protection (public instance variables).
Chapter 10
- A Java interface type declares the methods that can be applied to a variable type.
- Public INTERFACE InterfaceName{ method headers }
- The methods of an interface are automatically public.
- No implementation is provided.
- Use the implements reserved word to indicate that a class implements an interface type.
- Public class ClassName implements InterfaceName, InterfaceName, … { instance
variables, methods }
- Use interface types to make code more reusable.
- Inheritance is used to model hierarchies of related classes, but interfaces model a
different relationship.
- Both implement the measurable interface type, but otherwise have nothing in
common.
- A class can implement more than one interface, but a class can only extend
(inherit from) a single superclass.
- Interfaces cannot have instance variables, but it is legal to specify constants.
- A static method of an interface does not operate on object, its purpose should relate to the
interface that contains it.
- A default method is a non-static method in an interface that has an implementation.
- You can convert from a class type to an interface type, provided the class implements the
interface.
- Method calls on an interface reference are polymorphic; the appropriate method is
determined at run time.
- An interface reference can refer to an object of any class that implements the interface.
- You need a cast to convert from an interface type to a class type.
- Country maxCountry = (Country) max;
- Implement the Comparable interface so that objects of your class can be compared, for
example, in a sort method.
- The Comparable interface has a single method.
- Public interface Comparable{ int compareTo(Object otherObject); }
- compareTO method check weather one object is smaller or larger than another.
- He clone method and the clonable interface makes copies of objects.
- The return type of the clone method is the class Object.
- The object.clone method is the starting point for the clone methods in you won classes.
Chapter 11
- Use the Scanner class for reading text files.
- File fileName = new File(“input.txt”);
- Scanner input = swe Scanner (inputFile);
- When writing text files, use the PrintWriter class and the print/println/printf methods.
- fileName.println(“Hello, world!”);
- Close all files when you are done.
- fileName.close();
- The next method reads a sting that is delimited by white space.
- String input = in.next();
- System.out.println(input);
- To read just the words and discard anything that isnt a letter call the useDelimiter method.
- Scanner in = new Scanner(...);
- in.useDelimiter(“...”);
- To read a file one character at a time, call useDelimiter method on your Scanner with an
empty string.
- Scanner in = new Scanner(...);
- in.useDelimiter(“”);
- While (in.hasNext()){char ch = in.next.charAt(0); // then you can process each
ch}
- The Character class has methods for classifying characters.
- isDigit, isLetter, isUpperCase, isLowerCase, isWhitespace
- The nextLine method reads an entire line.
- String line = in.nextLine();
- While (in.hasNextLine()){ String line = innextLine(); // process line }
- You can use a Scanner object to read the characters from a string, and lineScanner like
any other Scanner object.
- String countryName + lineScanner.next();
- While (!lineScanner.hasNextInt()){ …}
- If a string contains the digits of a number, use the Integer.parseInt or Double,parseDouble
method to obtain the number value.
- Constructs such as %-10s are format specifiers, describing how a value should be
formatted.
- Format flags include: - (left alignment), 0 (show leading zeroes ie. 001.3), + (show a +
for positive numbers), ( (enclose negative numbers in parentheses), , (show decimal
separators), ^ (convert letters to uppercase).
- Format types include: d (decimal integer), f (fiked floating point), e (exponential floating
point), g (general floating-point), s (string).
- A format specifier starts with a %, next is a flag, next is the field width (# of characters),
next is the format type.
- A regular expression describes a character pattern.
- Ex; number have a simple form as theu contain one or more digits .The regular
expression describing numbers is [0-9]+. This denotes numbers can be any digit
from 0-9 and there can be one or more digits.
- You can read an entire file into a list of lines or a single string bu using the files and paths
classes.
- String filename = …;
- List<String> lines = Files.readAllLines(Paths.get(filename));
- String content = new String(Files.readAllBytes(Paths.get(filename)));
- When you run a program, you can type additional information beyond the name of the
program which is called the command line argument.
- Programs that start from the command line receive the command line arguments in the
main method.
- To signal an exceptional condition, use the throw statement to throw an exception object.
- If (amount > balance) { throw new IllegalArgumentException(“Amount exceeds
balance”); } //most exception objects can be constructed with an error message.
- Exceptions include:

- When you theon an exception, processing continues in an exception handler.


- Every expedition should be handled in the program, and when there is no handler, an
error message is printed and the program is terminated.
- Place the statements that can cause an exception inside a try block, and the handler inside
a catch clause.
- The try statement contains one or more statements that may cause an exception of the
kind that you are willing to handle.
- Each catch clause contains the handler for an exception type.
- Try { … }catch(xxx exception){//print error};
- There can be multiple exceptions so place more specific expectations first.
- Checked exceptions are due to external circumstances that the programmer cannot
prevent. The compiler checks that your program handles these exceptions.
- OutOfMemoryError
- Descendents of RuntimeException such as IndexOutOfBoundsException or
IllegalArgumentException indicate errors in your called and they are called unchecked
exceptions. All other exceptions are checked.
- The throws clause signals to the caller of your method that it may encounter a
FileNotFoundExcpetion.
- Add a throws clause to a method that can throw a checked exception.
- Public void readData(String filename)
- Throws FileNotFoundException, NumberFormatException
- You must specify all checked exceptions that this method may throw
- You may also list unchecked exceptions.
- The try-with-resources statement ensures that a resource is closed when the statement
ends normally or due to an exception. It calls the close methods of variables declared
within the statement header.
- Sometimes, you need to do some cleanup other than calling a close method; in that case
use the try/finally statement.
- Try{ … }finally{ cleanup executed weather or not an exception occurs}
- To describe an error condition, provide a subclass of an existing exception class.
- You do this when none of the standar exception types describe the error condition
well enough.
- Public class InsufficientFundsException extends IllegalArguementExcpetion{
- Public InsufficientFundsException() {}
- InsufficientFundsException(String message){ super(message); } }
- When the exception is caught, its message string can be retrieved using the
getMessage method of the Throwable class.
- Throw an exception as soon as a problem is detected. Catch it only when the problem can
be handled.
- An assertion is a condition that you believe to be true at all times in a particular program
location.
- An assertion check tests whether an assertion is true.
- Public double deposit (double amount){
- Assert abount >= 0;
- …}
- If the assertion fails, and assertion checking is enabled, the assert statement throws an
exception type of AssertionError.
- When designing a program, as yourself what kinds of exceptions can occur.
- For each exception, you need to decide which part of your program can competently
handle it.
Chapter 12
- To discover classes, look for nouns in the problem description.
- Verbs correspond with methods.
- Concepts from the problem domain are good candidates for classes.
- The CRC card describes a class, its responsibilities, and its collaborating classes.
- A class depends on another class if it uses objects of that class.
- It is a good practice to minimize the coupling between classes.
- A class aggregates another if its objects contain objects of the other class.
- Inheritance is sometimes inappropriately used when the has-a relationship would be more
appropriate.
- Aggregation denotes that objects of one class contain references to objects of another
class.
- You need to distinguish the UML notation for inheritance, interface
implementation, aggregation, and dependency.
- Sometimes it is useful to indicate class attributes and methods in a
class diagram,
- An attribute is an extremely observable property that objects of a
class have.
- Ie. price and name would be attributes of a product class.
- Some designers like to write multiplicity ot the ends of an
aggregation relationship to denote how many objects are
aggregated.
- * (zero or more), 1..* (one or more), 0..2 (zero or one), 1
(exactly one)
- Early in the design phase, it makes more sense to use a more general relationship called
association (solid line).
- The UML standard also recognizes a stronger form of the aggregation relationship called
composition, where the aggregated objects do not have an existence independent of the
containing object.
Chapter 13
- A recursive computation solves a problem by using the solution to the same problem with
simpler inputs.
- For a recursion to terminate there must be special cases for the simplest values.
- Sometimes it is easier to find a recursive solution if you make a slight change to the
original problem.
- Occasionally, a recursive solution is much slower than its iterative counterpart; however,
in most cases, the recursive solution is only slightly slower.
- In many cases, a recursive solution is easier to understand and implement correctly than
an iterative solution.
Chapter 14
- The selection sort algorithm sorts an array by repeatedly finding the smallest element of
the unsorted tail region and moving it to the front.
- To measure the running time of a method, get the current time immediately before and
after the method call.
- Computer scientists use the big-O notation to describe the growth rate of a function.
- Selection sort is an O(pi^2) algorithm; doubling the data set means a fourfold increase in
processing time.
- Common big-O growth rates: O(1) constant, O(log(n)) logarithmic, O(n) linear, O(n
log(n)) log-linear, O(n^2) quadratic, O(n^3) cubic, O(2^n) exponential, O(n!) factorial.
- Insertion sort is another simple sorting algorithm where we start with the second(1) item
and place it where it belongs in the list to the left.
- Insertion sort is also O(pi^2).
- The merge sort algorithm sorts an array by cutting the array in half, recursively sorting
each half, and then merging the sorted halves.
- Merge sort is an O(n log (n)) function, which grows far slower than n^2.
- Quicksort is a commonly used algorithm that has the advantage over merge sort that no
temporary arrays are required to sort and merge the partial results.
- In quick sort, one partitions the elements into two groups, holding the smaller and larger
elements, then one sorts each group.
18.1, 18.2, 18.3, 18.4
- In Java, generic programming can be achieved with inheritance or with type parameters.
- Generic programming is the creation of programming constructs that can be used with
many different types.
- Ex: ArrayList class used the technique of generic programming.
- A generic class has one or more type parameters.
- Type parameters can be instantiated with class or interface types.
- Type parameters make generic code safer and easier to read.
- Here is an example for a generic class that stores pairs of objects, each of which can have
an arbitrary type:
- Pair<String, Integer> result = new Pair<>(“Harry Morgan”, 1729);
- There are different variables for different typed parameters, and it is goo to use short
uppercase names for type variables such ase these:
- E - Element type in a collection, K - key type in a map, V - value type in a map, T
- general type, S, U - additional general types.
- To declare a generic class you write:
- Modifier class GenericClassName<TypeVariable1, TypeVariable2, ,,, >{instance
variables, constructors, methods}
- Public class Pair<T, S>{ private T first; private S second; public T getFirst()
{return first} … }
- Supply a variable for each type parameter.
- Instance variables with a variable data type.
- A method with a variable return type.
- Type variables of a generic class follow the class name and are enclosed in angle
brackets.
- Use type parameters for the types of instance variables, method parameter variables, and
return values.
- A generic method is a type of method with a type parameter.
- Such a method can occur in a class that in itself is not generic.
- For example, we many want to declare a method that can print an array of any type.
- Supply tye type parameters of a generic method between the modifiers and the method
return type.
- When calling a generic method, you need not instantiate the type parameters.
- Syntax:
- Modifiers <TypeVariable1, TypeVariable2,,,> returnType
methodName(parameters){body}
- Public static <E> String toString(ArrayLIst<E> a){}
- Type parameters can be constrained with bounds.
- We can constrain the type of the elements, requiring that the type implement the
Measurable type.
- In Java we add the clause extends Measurable after the type parameter:
- Public static <E extends Measurable> double average(ArrayList <E> objects)
- Wildcard types were invented for when it is
necessary to formulate subtle constraints on
type parameters.
- For example, we can declare the following
method in LinkedList<E> class:
- Public void addAll(LInkedList<?
Extends E> other){...}

Examples
LargestInArrayList: This program reads a sequence of values and prints them, marking the
largest value.
import java.util.Scanner;

public class LargestInArray{


public static void main(String[] args){
final int LENGTH = 100;
double[] values = new double[LENGTH];
int currentSize = 0;

//read inputs

System.out.println("Please enter valuyes, Q to quit:");


Scanner in = new Scanner(System.in);
while (in.hasNextDouble() && currentSize < values.length){
values[currentSize] = in.nextDouble();
currentSize++;
}

//find the largest value

double largest = values[0];


for(int i = 1; i < currentSize; i++){
if (values[i] > largest){
largest = values[i];
}
}

//print all values, marking the largest

for (int i = 0; i < currentSize; i++){


System.out.print(values[i]);
if(values[i] == largest){
System.out.print(" <== largest value");
}
System.out.println();
}
}
}

Returns:
Please enter values, Q to quit:
34.5 80 115 44.5 Q
34.5
80
115 <== largest value
44.5

QuestionDemo2: This program shows a simple quiz with two choice questions.
import java.util.Scanner;
public class QuestionDemo2{
public static void main(String[] args){
ChoiceQuestion first = new ChoiceQuestion() ;
first.setText("What was the original name of the Java language?") ;
first.addChoice("*7", false);
first.addChoice("Duke", false);
first.addChoice("0ak", true);
first.addChoice("Gosling", false);

ChoiceQuestion second = new ChoiceQuestion () ;


second.setText(" In which country was the inventor of Java born?") ;
second.addChoice("Australia", false);
second.addChoice("Canada", true);
second.addChoice("Denmark", false);
second.addChoice("United States", false);

presentQuestion(first);
presentQuestion(second);
}

// Presents a question to the user and checks the response.


// @param q the question

public static void presentQuestion (ChoiceQuestion q){


q.display();
System.out.print("Your answer: ");
Scanner in = new Scanner(System.in);
String response = in.nextLine();
System.out.println(q.checkAnswer(response));
}
}

ChoiceQuestion: A question with multiple choices.


import java.util.ArrayList;

public class ChoiceQuestion extends Question{


private ArrayList<String> choices;

//Constructs a choice question with no choices.


public ChoiceQuestion(){
choices = new ArrayList<String>();
}

//Adds an answer choice to this question.


//@param choice the choice to add
//@param correct true if this is the correct choice, false otherwise

public void addChoice (String choice, boolean correct){


choices.add(choice);
if (correct){
//Convert choices.size () to string
String choiceString = "" + choices.size();
setAnswer(choiceString);
}
}

public void display(){


//Display the question text
super.display();

//Display the answer choices


for (int i = 0; i < choices.size () ; i++){
int choiceNumber = i + 1;
System.out.println (choiceNumber + ": " + choices.get(i));
}
}
}

Question: a question with a text and an answer.


public class Question{
private String text;
private String answer;

//Constructs a question with empty questíon and answer.


public Question(){
text = "";
answer = "";
}

//Sets the question text.


// @param questionText the text of this question

public void setText (String questionText){


text = questionText;
}

// Sets the answer for this question.


// @param correctResponse the answer

public void setAnswer (String correctResponse){


answer = correctResponse;
}

// Checks a given response for correctness.


// @param response the response to check
// @return true if the response was correct, false otherwise

public boolean checkAnswer (String response){


return response.equals (answer);
}

//Displays this question.


public void display (){
System.out.println (text);
}
}

11.3 CesarCipher: This program encrypts a file using Caesar’ cipher.


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class CaesarCipher{


public static void main(String[] args) throws FileNotFoundException {
final int DEFAULT_KEY = 3;
int key = DEFAULT_KEY;
String inFile = "";
String outFile = "";
int files = 0; // Number of command line arguments that are files

for (int i = 0; i< args.length; i++){


String arg = args [i];
if(arg.charAt(0) == '-'){
// It is a command line option
char option = arg.charAt(1);
if (option =='d'){
key = -key;
}
else{
usage();
return;
}
}
else{
// It is a file name
files++;
if (files == 1){
inFile = arg;
}
else if (files == 2){
outFile = arg;
}
}
}

if (files != 2){
usage();
return;
}

Scanner in = new Scanner (new File (inFile) ) ;


in.useDelimiter ("") ; // Process individual characters
PrintWriter out = new PrintWriter (outFile);

while (in.hasNext()){
char from = in.next().charAt(0);
char to = encrypt(from, key);
out.print(to);
}
in.close();
out.close();

//Encrypts upper- and lowercase characters by shifting them


// according to a key.
// @param ch the letter to be encrypted
// @param key the encryption key
// @return the encrypted letter

public static char encrypt (char ch, int key){


int base = 0;

if ('A' <= ch && ch <= 'Z'){


base = 'A';
}
else if ('a' <= ch && ch <= 'z'){
base = 'a';
}
else{
return ch; //not a letter
}

int offset = ch - base + key;


final int LETTERS = 26; // Number of letters in the Roman alphabet

if (offset >= LETTERS){


offset = offset- LETTERS;
}
else if (offset < 0){
offset = offset + LETTERS;
}

return (char) (base + offset);


}

// Prints a message describing proper usage.


public static void usage(){
System.out.println("Usage: java CaesarCipher [-d] infile outfile");
}
}

13.2 Palendrome: Recursive palendrome example.


public class Palindromes
{
public static void main(String[] args){
String sentence1="Madam I'm Adam!";
System.out.println(sentence1);
System.out.println("Palindrome: "+isPalindrome(sentence1));
String sentence2 = "Sir I'm Eve!";
System.out.println(sentence2);
System.out.println("Palindrome: " + isPalindrome(sentence2));

/**
Tests whether a text is a palindrome.
@param text a string that is being checked
@return true if text is a palindrome, false otherwise
*/

public static boolean isPalindrome(String text){


int length = text.length();

//Separate case for shortest strings


if (length<=1){
return true;
}
else{
//Get first and last characters, converted to lowercase
char first = Character.toLowerCase(text.charAt(0));
char last = Character.toLowerCase(text.charAt(length -1));

if(Character.isLetter(first)&&Character.isLetter(last)){
// Both are letters
if(first==last){
// Remove both first and last characters and recurse
String shorter = text.substring(1,length-1);
return isPalindrome(shorter);
}
else{
return false;
}
}
else if(!Character.isLetter(last)){
//Remove last character
String shorter = text.substring(0,length-1);
return isPalindrome(shorter);
}
else{
//Remove first character
String shorter = text.substring(1,length);
return isPalindrome(shorter);
}
}

} // end method
} // end class

14.4 Merge sort: This sorts an array using merge sort.


public class MergeSorter{
public static void sort(int[] a){
if(a.length<=1){
return;
}
int[] first = new int[a.length/2];
int[] second = new int[a.length-first.length];
//copy the first half of a into first, second half into second
for (int i=0;i<first.length;i++){
first[i]=a[i];
}
for (int i=0;i<second.length;i++){
second[i]=a[first.length+i];
}
sort(first);
sort(second);
merge(first,second,a);
}

// Merges two sorted arrays into an array.


// @param first the first sorted array
// @param second the second sorted array
// @param a the array into which to merge the first and second

private static void merge(int[] first, int[] second, int[] a){


int iFirst=0; // Next element to consider in the first array
int iSecond=0; // Next element to consider in the second array
int j=0; //Next open position in array

// As long as neither iFirst nor iSecond is past the end, move


// the smaller element into array
while(iFirst<first.length && iSecond<second.length)
{
if (first[iFirst]<second[iSecond]){
a[j]=first[iFirst];
iFirst++;
}
else{
a[j]=second[iSecond];
iSecond++;
}
j++;
}

// Note that only one of the two loops below copies entries
// This is for copying any remaining entries in first into a
while(iFirst<first.length){
a[j]=first[iFirst];
iFirst++;
j++;
}
// This is for copying any remaining entries in second into a
while(iSecond<second.length){
a[j]=second[iSecond];
iSecond++;
j++;
}
}
}

MergeSortDemo: This demonstrates the merge sort algorithm.


import java.util.Arrays;

public class MergeSortDemo


{
public static void main(String[] args){

// make an array of integers


int[] a = {3,2,1,4,6,43,8,55,0,-4,2,98,12};
System.out.println(Arrays.toString(a));

// use merge sort on it


MergeSorter.sort(a);

// print out the sorted array


System.out.println(Arrays.toString(a));
}
}

Vocab (Quizlet https://quizlet.com/_d82qgc?x=1jqt&i=ttv93)


Accessor method
● Has a return
● Does not actually change the data itself, just returns something for the program to use

Actual parameter
● The parameter name as specified in the method header
● Like a 'placeholder' for the formal parameter to be passed into
● EX: private void deposit (double amt)

Algorithm
● A series of specific instructions that achieve a goal

API
● Application Programming Interface
● Library of classes and their corresponding interfaces/methods
● Can look up methods when unsure

Argument
● The formal parameter provided to be passed into the actual parameter
● Used in method invocation

Array
● An immutable collection of object references
● Fixed length
● Instantiation: type [] name = new type[length]; OR new type[]{x, x, x};
● Can hold primitives
● Methods
○ name.length --> gets the length of the array
○ name[i] --> gets the element at that index
○ Arrays.copyOf(name, length) --> copies the array until that length, static method
■ EX: int[] newArray = Arrays.copyOf(oldArray, oldArray.length);

ArrayList
● Mutable, size automatically adjusts to accommodate new/removed object references
● Instantiation: ArrayList <type> name = new ArrayList<type> ();
● Making a copy: ArrayList <type> name = new ArrayList<type> (oldArrayList);
○ Makes a new set of object references, still refers to the same objects
○ BUT oldArrayList != newArrayList --> they are innately different ArrayList
objects
● Cannot hold primitives, must use wrapper classes
○ <Integer>, <Double>, <String>
● Methods
○ name.size() -- gets the length of the ArrayList
○ name.get(i) -- returns the object at that index
○ name.add(element) -- adds an element to the end of the ArrayList
○ name.add(i, element) -- overloaded method, adds an element to that index of the
ArrayList
○ name.remove(i) -- removes an element from that index of the ArrayList
○ name.contains(element) -- boolean, checks if the element is in the ArrayList
○ name.set(i, element) -- replaces the object at that index with another

ASCII
● American Standard Code for Information Interchange
● Character encoding format for text data in computers
Binary
● 1s and 0s
● Base 2 system, used to represent information to CPU

Bit
● Binary digit
● 1 or 0

Boolean (java type)


● A primitive that can only hold true or false
● 1 byte needed

Boolean variable
● A variable of type boolean that can only be set to true or false
● Same instantiation as other variables
○ EX: boolean found = true;

Boolean expression
● An expression that can only evaluate to true or false
● Often used in conditionals
● Boolean operators
○ == equal to
○ != not equal to
○ >/>= greater than/greater than or equal to
○ </<= less than/less than or equal to
○ && and
○ || or

Bottom up design
● Strategy for tackling OOP
● Working from the 'easiest' class up

Byte
● A 'chunk' or package of bits
● 8 bits = 1 byte

Bytecode
● The 'intermediate' code between the one you write and the one that is read by the CPU
● After you compile your written code --> bytecode
Cast
● A way to convert between primitives
● EX: double price = 42.02
int roundedPrice = (int) price; – converts price from a double to an integer

Checked exception
● An exception that is not your fault/out of your control
○ EX: someone deleted the file you are writing/reading from --
FileNotFoundException

Class
● A blueprint for an object
● Comes with instance variables (unique variables for each object of the class)
● Comes with methods that the class objects can use
● Header: public class ClassName {
}

Class level variable (static variable)


● Not unique for every instance of the class
● Only one copy for the entire class
● Ex: static bankAccountNumber;
○ Increment the static variable after every instantiation of a bankAccount object
instead of creating a new instance variable each object

Command line arguments


● Arguments that are given to String() args and passed into the actual parameters of a
method
● Allows you to get direct user input from the interface

Compiler
● 'Translates' written code into CPU readable code
● javac fileName.java

Computer science
● Study of computers, their language, and how to write/implement algorithms

Constructor
● Job is to instantiate the instance variables
● Header: public className (parameters)
{
instanceVariableName = assignedValue;

Data type
● The 'kind of animal' an object is
● Primitive? A class?

Declare
● Tells java what 'kind of animal' a variable is
● EX: int number;

Encapsulation
● Hiding certain parts of the code from the user interface
● For privacy or for user's ease
● Can be done through visibility modifiers (private)

Exception (java type)

Explicit parameter
● The parameter given to the method during invocation (in the parentheses)

For loop
● A 'well-controlled' while loop that terminates after a given amount of iterations
● for (start; i<some # of iterations; incrementation)

Formal parameter
● The parameter passed into the actual parameter placeholder during method invocation

Garbage collection
● Something that java does automatically to clear up storage
● EX: cleaning up unused object references

Generic class (in Java)

Generic method (in Java)


● A method that takes generic objects as its parameters
● A restriction can be placed on what objects the method takes
○ EX: <T extends Comparable> -- the object must implement the comparable
interface to be used in this method

Hexadecimal
● Base 16 system
Decim Hex
al

0 0

1 1

2 2

3 3

4 4

5 5

6 6

7 7

8 8

9 9

10 A

11 B

12 C

13 D

14 E

15 F

If-else
● Conditional statement
● Every else must be attached to an if
● elseif -- if the first if statement evaluates to false, check this one

Implicit parameter
● The object that the method is acting on
● Comes before the .method()
● If the implicit parameter is the class, the method is static

Immutable
● An object that is unchangeable
● EX: a string, you cannot change its contents, you can only take chunks of the contents
(substring)

Inheritance (in Java)


● Parent class --> subclass
● Subclass inherits the instance variables and methods from the parent class
● Subclass header: public class subclassName <extends parentClass> {
}

Initialize
● Assigning a value to an existing (already declared) variable

Instance
● An 'example' of a class -- an object created with its blueprint\
● EX: myAccount is an instance of a BankAccount

Instance variable
● A unique 'trait' that each object of the class has
● EX: every BankAccount object should have a name, an account number, a balance, etc
private String name;
private int acctNumber;
private double balance;

Instantiation
● Creation of a new instance of a class (a new object)
● Uses the 'new' operator
● EX: BankAccount myAccount = new BankAccount(parameter);

Interface
● Like an 'ability' of an object/class
● EX: comparable interface -- the objects of that class are able to be compared to one
another
● We don't use inheritance because comparable is not really a class, its really just a promise
to java that the compareTo method will be in the class

Method
● Code written to perform/automate a certain task
● Can be called on objects
● Can use parameters to help

Method signature
● Should include…
○ Name of method
○ Description of parameters (type, number, order)

EX: deposit (double amt)

● VS METHOD HEADER
○ Signature + visibility modifier and/or return type

EX: private void deposit(double amt);

Mutator method
● A method that actually changes the data
● Void -- no return type

Object
● The actual 'thing' created with a class blueprint

Object (java type)

Object reference
● The name used to refer to the 'thing'
● Points to the location of the 'thing'
● EX: myAccount is an object reference to the actual account created

Object-oriented programming
● Programming used to ease the accessibility/usage of the user interface

Overloading a method
● Methods of the same name can be written to take different parameters
● When java is given those parameters, it can tell which of the overloaded method to use
● Allows 'choice' between the method type to invoke

Overriding a method
● Adding functionality to a method in the subclass (inheritance)
● If you call the method on an object created under the subclass, java will know to invoke
the overridden method -- polymorphism!

Parameter passing
● Passing the actual parameter (given during method invocation) into the formal parameter
(defined in the method header)

Primitive data type


Type Storage Description
(bytes)

byte 1

boolean 1 True/false

char 2 Letters

short 2

int 4 Integer, no
decimal values

long 8

float 4

double 8 Decimals/fractions
allowed

Pseudocode
● Indexing starts at 1
● Written version of actual code for humans to understand

Recursion
● Repeatedly calling a method on itself to mitigate use of a for/while loop

Scope
● Where the variable 'lives' in the program
● Usually, the variable will only live within the boundaries of its associated curly braces
● Something to be careful of -- don't refer to a variable when it is out of scope

Static method
● Method where the implicit parameter is a class
● EX: Math.random(); Array.copyOf()
Static variable
● Variable that is universal for all the objects of the class (NOT unique for every instance)
● Can be used like a counter
○ EX: the account number can be a static variable and updated with every bank
account made

'this' keyword
● Formal name for the implicit parameter
● Used so that we do not have to create new instance variable references in the constructor
● Instead, just do this.parameter -- 'this' will refer to the most recently created object

EX:
public BankAccount(String name)
{
this.name=name;
}

Throw
● A 'call' to throw an exception, like a call to a method
● Tells java how to handle an exception
● Used within the method
● Can create a new exception object

if(exception condition)
{ throw new ExceptionName("exception");}

Throws
● A 'warning' to the method/exception suppression
● Acknowledges the possibility of an exception
● Tells java you know it is there
● Used in method signature
method header(parameters) throws Exception { method; }

Top down design


● Strategy of OOP that asks 'what do you want to do' and then works from there
● Wishful programming

Unchecked exception
● Exceptions that should not happen, are your fault
○ EX: IndexOutOfBoundsException
● Can still make custom exception throws to catch/throw them

White space
● Spaces, tabs, etc

While loop
● Loop that terminates when the condition specified in the header evaluates to false

You might also like