Intro Java
Intro Java
Intro Java
- 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
- 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
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:
Examples
LargestInArrayList: This program reads a sequence of values and prints them, marking the
largest value.
import java.util.Scanner;
//read inputs
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);
presentQuestion(first);
presentQuestion(second);
}
if (files != 2){
usage();
return;
}
while (in.hasNext()){
char from = in.next().charAt(0);
char to = encrypt(from, key);
out.print(to);
}
in.close();
out.close();
/**
Tests whether a text is a palindrome.
@param text a string that is being checked
@return true if text is a palindrome, false otherwise
*/
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
// 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++;
}
}
}
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 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 {
}
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)
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
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)
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)
● VS METHOD HEADER
○ Signature + visibility modifier and/or return type
Mutator method
● A method that actually changes the data
● Void -- no return type
Object
● The actual 'thing' created with a class blueprint
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)
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; }
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