1/91
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Classes
Containers that hold variables & methods
•accessModifier class MyClass {
•Everything in Java belongs to a class
•Every program must have at least 1 class
But also
The blueprint / template for an object which defines its basic parameters
•Declares variables (private) & sets up methods (public)
accessModifier class MyClass {
Declares a program class
Fields
Aka variables. Data w/ defined types (ex: #s, characters, strings, objects)
Has space in memory, which is filed w/ a value & referred to by a specific name
•type variableName = value;
Methods
Aka functions. A block of statements (code) which does an operation. Only runs when called
•modifiers returnType methodName(parameters) {
•May be called mult times in a program
•Composed of a header & body’
type variableName = value;
Assigns an initial value to variable
modifiers returnType methodName(parameters) {
Method declaration
Private
Accessible by self only
•May be the whole class if its declared not in a method, or just in 1 method or object if its declared in there
Protected
Accessible by self, derived classes, & other classes in the same package
Public
Accessible by self, derived classes, & everyone else
No publicity modifier specified
Accessible by self & other classes in the same package
Static
Method/variable can be called from anywhere (belongs to the class as a whole)
Final
Keyword used for constant method/variables that makes it so they can not be changed in any way
•Variable/method name written in all caps
•Ex: final static int NUM_DOORS = 2; bs all cars will have 2 doors
•Shouldn’t be used for anything other than constants that are common to ALL objects of the class
Calling
•Can be called w/out creating an instance (object) of the class
•Can be refrenced by the class name itself or an object of the cllass
void
Method return type that makes it so it doesn’t return a value
Main() method
public static void main(String[] args)
•Each program should have one (doesn’t mean every class must)
•Can be used to call other methods
Primitive (atomic) type
Predefined data types
•Ex: int, float, double, boolean, & char
•Start w/ a lowercase letter
•Can be null
•Variable directly stores its data in the stack (variable’s memory)
Reference type
Data type that references an object
•Ex: String, Array, Class
•Created by the programmer (except for String)
•Start w/ an uppercase letter
•Can’t be null
•Variable refers to an object & so its memory address is stored in the stack (variable’s memory), which directs to the HEA where the variable data is actually stored
Widening primitive conversion
Implicit conversion of the type from a lower memory type to a larger memory one
•You don’t have to write the code for the cast
Narrowing primitive conversion
Explicit conversion of the type from a higher memory data type to a lower data type
•Casting must be done by the programmer for it to
•May lose info bc there is less space/memory for it
•Ex: int x = int(2.5)
The Stack
When a method is called
A stack frame (shelf) is allocated on the stack (bookshelf) for this method
Each method parameter is placed on the stack
Arguments are mapped to parameters in order, w/ each parameter assigned a copy of the corresponding argument’s value
Any variables (book) declared in the method also gets added to the stack frame’
When the method is done executing, the stack frame is removed from the stack, along w/ all variables in the stack frame
Last thing in the stack is the 1st thing to be removed
•Stores primitive type variable data & reference type variable addresses
•If a mutable ref type is passed to a method
•It’s variable is made to still exist after the method is done executing
•This occurs for ArrayLists & objects
Primitive wrapper class
The reference type ‘wraps’ a primitive in a class
Makes the variable works as a reference type instead of a primitive type
Need to type out the entire reference type name of the associated primitive type
Ex: Type Character for char
Works for Character, Integer, Double, Boolean, & Long
Benefits
Keeps constants related to the primitive types static
Allows methods such as toString() & equals() to be grouped in a class
Some container data types don’t take primitives, so we need to wrap them first
Integer a = 20
Primitive wrapper class version of int
Boxing
Initializing primitive wrapper class w/ class constructor syntax
fullTypeName variable = value
fullTypeName variable = value
Boxes (aka initializes) a primitive wrapper class
Unboxing
An object of a primitive wrapper type is converted to its corresponding primitive type
primitiveType newVariable = prevNamedWrappedVariable
Ex: Integer i = new Integer(10); int j = i;
Integer i = new Integer(10);
int j = i;
Unboxes a primitive type back to its regular primitive type
Print function
System.out.printf()
Print w/ line spacing
\n in the quotes
or
System.out.println()
Concatenating
Allows us to print multiple values by putting a + between them
Scanner method
import java.util.Scanner; | Imports the Scanner class so we can use it
Scanner scnrName = new Scanner(System.in); | Declares a new variable/object of type Scanner
scnrName | Variable name
Scanner | Type that the variable is
System.in | Corresponds to keyboard input
Control flow / Conditional statemetns
Language features that allow you to jump around in the code when a certain condition is true
•Included if, else, & else if
Branching / Selection statements
Tests boolean expressions, executing a dif code block depending of if its true or false
•If else statements are used for the true & false
Chained conditionals
Only 1 block of statements get executed based on the value of x
Iterations
A repeating process which is implemented using a loop
•Usually repeating bc it is approaching a goal incrementally
Loops
Allow us to repeatedly execute a statement or block of statements
•2 types, while & for loops
while();
while(condition);
Loop structure that executes code while a condition is true
Each time the loop body is executed it is = to 1 iteration
Make sure it doesn’t go infinitely
Indefinite loops: # of times the loop body will execute is not known in advance. Usually its executed until some condition is satisfied
for ()
for(initalization ; condition ; updator)
Loop structure that executes code exactly N times
Definite loops: The # of times the loop body will execute is known & can be determined in advanced
for() loops are typically used for these but can also use a while loop
JUnit basic method annotations
•@Test | Must be used b4 Junit testing method
•@Test public void method() | Identifies a method as a test method
Inheritance
All properties from the parent class are extended to the child classes
•public class derivedClass extends baseClass | Derive a class from a base class
•A derived class can be a base class for another class
•A class can serve as a base class for mult derived classes
•A derived class can only be dervied from 1 base class directyl
Has-a relationship
Composition. One class may have another class as a member field
•The 2 classes don’t have any inheritance
Is-a relationship
Inheritance. One class is derived from another class
Objects
An instance of the class that contains unique attributes (variables) & behaviors (methods)
•ClassName variableName = new ClassName(); | Declares an object
Object class
Built in Java class
Base class for all other classes
Top of the hierarchy (doesn’t have a superclass)
Defines methods that can be used by derived class
derived
•Allows inheritance to occur from a base class to a new class
•public class derivedClass extends baseClass
new
•Allows an object to be made from a class
•ClassName variableName = new ClassName();
Member fields
Describe the object (variables)
Typically private
Member methods
Describe what actions the object takes (methods)
Typically public
Local variables
Variables which are owned, delcared, & unique to the method
Instance variables
Variables declared outside the method (usually by the class), but who’s specific version is owned & customized by the instance (object)
Useful when a variable changes between objects
Public getters, public setters, & private helper methods are all instance methods
Factory methods
Static methods that can make an object
Ex: public static SportsCar make UberCar(){
Doesn’t require a prev instance of the class
Constructors
Speical member method of a class that is automatically called when a variable of that class is allocated. Sets up the default settings for a class
public className(class arguments) {
Same name as the class name
No return type (not void- just nothing)
Might have multiple constructor w/ dif arguments so that objects of the class can be made w/ dif amounts of info & so we can call them w/out all info
Should provide at least 1 (if not more) constructors to initialize fields
If you don’t provide one when you define a class, Java provides one by default w/ 0 parameters & initializes all fields to default values
public className(class arguments) {
Creates a constructor of the class (Special member method of a class that is automatically called when a variable of that class type is allocated. Sets up the default settings for the class)
this.variableName = variableName
Inside of a class method, ‘this’ refers to the current object
Helps differentiate between member field & parameters w/ the same names
Ex: this.carColor = carColor
Renaming parameters
this.variableName = variableName | Inside of a class method, ‘this’ refers to the current object
Helps differentiate between member field & parameters w/ the same names
Ex: this.carColor = carColor
Instance methods
Methods that belong to the instance (object) of a class
•Includes getters & setters
Getters
getSomeProperty()
Public instance methods that access private data
Belong to an object of the class
May return dif forms of the data, but don’t modify the og data
Ex: public String getColor() {
Setters
setSomeProperty()
Public instance methods that change private data
May change more than 1 private data element
public String toString() {
Returns a string representation of the object
Default is to return the name of the class & the address in the memory
This is what gets displayed when you call a print method
Overriding the toString method will display useful info about the object
object1.equals(object2);
Compares an object to another object
Returns true if the variables refer to the same object
Doesn’t compare contents, compares addresses (similar to ==)
When overridden, it can compare specific characteristics
Method Overloading
Mult methods that share the same name but differ in parameters
All overloaded methods must be defined in a single class
Parameter lists can differ in #, data types, or order
Allow you to make dif constructors even when you don’t have all the data
Ex: You have a new student at your school who you know the name of but who doesn’t have an ID. You can change the parameters to only require name to allow you to still register them
Ex: public SportsCar(String color, int mileage) { & publicSportsCar(String color) { can both exist
Method Overriding
Mult methods that share the same name & parameters but are redefend in some way in the subclass
Happens across parent class & child class/es
Derived class has methods w/ the same name as base class
Derived class’s method gets called instead of base class’s method
Overriding methods steps
@Override | An annotation on the line before the method
Call the method the same name as name in base class
Calling things
super.methodName | Used to call the overridden method in the parent class
super(arguments) | Calls the superclass' constructor from the subclass
Must call it on the 1st line of the sub class’s constructor
@Override
When overiding a method, this annotation goes on the line before the overiden method
•Call the method the same name as the name in the base class
super.methodName
Used to call the overridden method in the parent class
super(arguments)
Calls the superclass' constructor from the subclass
•Must call it on the 1st line of the sub class’s constructor
Array
type[] arrayName = new type[parameters];
An object which allows us to use 1 name to refer to a collection of variables of the same type
Reference rather than primitive type (store the address of the array object in the heap)
Initializing an array
type[] arrayName = new type[#ofVariables]; | Sets up an array w/ a certain # of default values
type[] arrayName = new type{value1, value2,...}; | Sets up an array w/ some certain variables in its collection
You can’t change the size of an array once it’s created. If you want to add more elements just make a new array
Element
Each item in an array
New operator initializes all the array elements to default values for the type of array declared
ex: int default is 0, reference type default is null
Index
int which refers to an array element. Starts at 0
Array commands
arrayName[#] = value; | Sets the index slot of the array to having this value
arrayName.length | Lets you access the # of elements in the array. Used for viewing or expressions
if (arrayName[i] !=null) { | When i is an int, makes sure that our element actually has a value & isn’t just null before we do some action w/ it
Avoids problems such as printing “null”
Enhanced for loop
for (type elementsName : arrayName) {
Allows you to visit each element in the array
We then refer to that elementsName we assigned in the loop to use it
By default increments 1 by 1 through all the elements
2D Array
An array of arrays
Conceptually think of it as a table
String[][] tableName { {“array0object0”, “array0object1”,...}, {“array1object0”,...} };
Rows are vertical & 1st [], columns horz & 2nd []
Iteration
tableName.length | Returns the # of rows
tableName[rowIndex].length | Returns the # of elements in each row
tableName[row#]{column#] | Iterates to the cell that is in this row & column
Shallow copying
arrayB[i] = arrayA[i]
When array holds primitive types
Copies arrayA’s values to arrayB, creating 2 separate arrays
The arrays are disjointed, so changes to 1 array don’t affect the other array
When array holds reference types (String, objects, arrays)
Copies arrayA’s addresses to arrayB, meaning they both point to the same values
Both arrays refer to the same object
Deep copying
arrayB[i] = arrayA[i] = new className(arrayA[i].constructor1(), arrayA[i].constructor2(), …);
Only works for reference types
New objects are created w/ exact copy of all fields of the original object
The arrays are disjointed, so changes to 1 array don’t affect the other array
ArrayList
A class that functions like a dynamic container
Unlike normal arrays, items can be added or removed
import java.util.ArrayList; | Allows you to use ArrayList
ArrayList<T> listName = new ArrayList<T>(); | Declares an array list
T: Type of object that the ArrayList will hold (ex: book, animal)
Ex: ArrayList<Book> bookList = new ArrayList<Book>();
Can only hold reference type data, so use primitive wrapper classes & objects (ex: Integer instead of int)
Can loop through ArrayLists
name.length();
Returns the # of elements an array can hold
name.size();
Returns the # of elments an ArrayList is currently holding
Abstract class
accessModifier abstract class MyClass {
A class that guides the design of subclasses, tho it cannot create objects of its own
Ex: Animal could be an abstract class as it's too vague to make objects from. You would want to 1st make subclasses like reptile & mammal to make objects from instead
Specifies how the subclass must be implemented
Can have member fields & methods that are shared by subclasses
Keyword in definition: abstract class
Keyword to associate a class: extends
A class can only be derived from 1 class
Abstract methods
accessModifier abstract dataType methodName();
Method that each subclass must implement to be a concrete class
Has an empty body
Must be inside of an abstract class
Concrete class
A class that objects can be createed from
Interfaces
interface
Specific set of methods that an implementing class must override & define
Allows a method to be implement b/ween completely isolated classes (no ship)
Any class that implements this interface must override & implement all of its methods
Keyword in definition: interface
Keyword to associate a class: implements
A class can implement multiple interfaces
extends
Keyword to associate a subclass w/ a parent class
implements
Keyword to associate a class w/ an interface
!=
Not equal
Not equal operator
!=
Equals to operator
==
!
Logical not
!a
True if a is false
Logical not
!
!a
True if a is false
&&
Logical and
a && b
True only if both a & b are true
Logical and
&&
a && b
True only if both a &
||
Logical or
a || b
True if at least one of the operands is true
Logical or
||
a || b
True if at least one of the operands is true
^
Exclusive or
a ^ b
True if only one of the operands is true
Exclusive or
^
a ^ b
True if only one of the operands is true
Floating point comparison
float a, b;
Math.abs(a - b) <= 0.0000001
Increment operator
++i | Increments i first then evaluates the rest
i++ | Evaluates the result first and then increments i