CCPROG3_EXPORT
Created: Oct 28, 2023
GDRIVE https://drive.google.com/drive/folders/1Pkxek9Auq22A0XXrKQyJMbLn5V17JdkH?usp=sharing
JACKSNOTES: https://jacks-notes.vercel.app/ccprog-3-export/
Type: Comprehensive
Description: Used during CCPROG3 finals, contains most of the topics. .md is editable but no images, .pdf contains images.
Issues:
- Was used for my PERSONAL reference for CCPROG3. - Jack
- Not all sources are listed consistently.
- Some images are from Youtube videos, articles, or the slides from Sir Leif. It's not documented though which ones.
- I don't want this to be used as the file to be sent out as is, mostly because of incompleteness and potential copyright issues.
- If the image was made in Excalidraw, then that is mine.
- Possibly unordered in terms of topics
Topics: (Open .md file outline for more topics)
- Week 1 topics
- Object Oriented Paradigm
- Module 2
- Practice 2 String Equivalents
- Module 2 Control Statements
- Parts of a Javafile
- Week 3 topics
- Packages and Import
- UML Diagramming (visibility, relationships, example)
- Package Handling, directory structure
- Smelly Code, UML Planning
- Module 2 Strings and Characters
- Module 2 Methods
- Module 2 Loops
- Getters and Setters
- Week 10a Abstract and Interfaces
- ArrayList vs List
Table of Contents (links will not work on the website, please use the TOC or outline on the side)
- Week 1
- The Object Oriented Paradigm
- Module 2 Object Oriented Paradigm Continued
- Practice 2 String Equivalences
- Module 2 Control Statements
- F2F Parts of a java file
- Week 3
- May 19, 2023 Notes: - Packages and import
- UML diagramming
- UML
- Package Handling
- F2F Smelly code, UML planning, etc
- Module 2 Strings and Characters
- Module 2 Methods
- Methods (Functions)
- Return Type
- Parameters - Module 2 Loops (While, For, Do-while)
- Getters and Setters
- F2F MVC Architecture
- Week 10a Abstract and Interfaces
- ArrayList vs List
Week 1
Java is an object-oriented language
- Object-oriented implies the support of most, if not all, concepts that make up an “OO” environment
- Object-based usually refers to the support of the creation of objects but that there’s a lack of higher “OO” concepts, such as inheritance or polymorphism
Compiled language vs Interpreted Language
Compiled
Source Code → Compiler → Executable File
Interpreted
Source Code + Interpreter = Fetch → Interpret → Execute → Fetch
/**
* @(#)MyApp.java
*
*
* @author
* @version 1.00 2023/5/12
*/
import java.util.Scanner; //put imports on top of the public class
public class MyApp { /*make sure the name of the public class and the file name is the same
(so your file name should be My app aswell)*/
/*public static double getArea(double dRadius){//functions are very simillar to C
double dArea;
dArea = 2 * 3.14 * dRadius * dRadius ;
return dArea;
}*/ //(B)
public double getArea(double dRadius){
double dArea;
dArea = 2 * 3.14 * dRadius * dRadius ;
return dArea;
} //(C)
public static void main(String[] args){//this is your main function
/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some quirks of java printing
int year=2023;
int YoB= 2004;
String name = "Left"; //no more char[] since we have a dedicated
function for String unlike C omg!
System.out.println(name + year + YoB); //outputs Left20232004
System.out.println(year - YoB + name); //outputs 19Left
System.out.println(name + (year - YoB)); //outputs Left19
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
Scanner sc = new Scanner(System.in); //make a scanner object
MyApp ap = new MyApp();
double dArea = 0.0;
double dRadius;
System.out.println("Please input a radius: ");
dRadius = sc.nextDouble();//the object here kinda acts like an input fucntion in C
//dArea = 2 * 3.14 * dRadius * dRadius; (A)
//System.out.println("\nArea is " + dArea); (A)
//System.out.println("\nArea is " + getArea(dRadius)); //(B)
System.out.println("\nArea is " + ap.getArea(dRadius)); //(C)
sc.close(); //make sure to close so there will be no memory leak
}
}
There were 3 ways to show the area:
- There is the procedural way to do it. This is the monkey put everything in main method. In the code comment the codes labeled with (C) and uncomment those labeled with (A)
- There is the CCPROG1&2 way to do it with functions. In the code comment the codes labeled with (C) and uncomment those labeled with (B)
- There is the Object Oriented way to do it, which is what the code is running on currently. The line of code “ap.getArea(dRadius)” is not called a function, rather a method
SRP
Single Responsibility Principle
- This convention states that each class or each function should only do one thing
- Make note of this istg the mp rubric will want this
The Object Oriented Paradigm

Programming Paradigms
- fundamental style or philosophy of programming
- How do i think about and solve a problem?
- Programming paradigms are different from programming languages
- examples: procedural programming, functional programming, object-oriented programming, logical programming
| Programming Paradigm | Programming Language |
|---|---|
| Influences programming languages | is influenced by programming paradigm |
| Serves as the philosophy behind a programming lang | can be influenced by multiple paradigms |
| gives the rationale behind the programming lang | doesn't need to apply all the philosophies of the paradigms that influence it |


Object-oriented programming
- real world objects are entities with attributes (can be composed of variables), and methods (can perform some action)
- allows for objects to interact with each other within an environment
- highly encourages generalization and abstraction
- provides for more complex programming features
- grants control over how data is stored/grouped, how processes are executed, and where each process originates from
- more responsibilities and greater effort required
- offers new ways to view creating solutions
- allows for the simulation of more complex systems and solving larger scale problems through representations, behaviors, and relationships

Classes and Objects
- Class - template or blueprint from which instances of objects may be created through a process called instantiation
- Objects - each object is an instance of a class (distinct), has its own copy of attributes (actual values), and can act in the way the class was designed.
Summary
- a programming paradigm is a style or philosophy or programming
- the object oriented paradigm
- encourages for the modeling of real-world objects
- provides more complex programming features, which entails that OO solutions can (1) better model complex systems, (2) be more complex to build
- objects
- have characteristics (attributes) and can perform actions (methods)
- are distinct from other objects and are based on classes which act as templates
Module 2 Object Oriented Paradigm Continued
Java
- object-oriented language
- object-oriented implies support of most concepts that make up an OO environment
- object-based refers to the support of the creation of objects but that there's a lack of higher OO concepts such as inheritance or polymorphism
- is a compiled and interpreted language
- compiled: source code > compiler > executable file
- interpreted: source code + interpreter -> (fetch->interpret->execute->repeat)

Writing Java Applications

Naming Conventions
- classes start with an uppercase letter
- methods and variables should start with lowercase letters
- apply snake_case for constants (in all uppercase) and camelCase for everything else
Class Declarations
- only have at most one main() method with the signature
public static void main(String[] args) - runtime system calls the main() method
Declaring variables
- Java language is strongly-typed
- all variables and expressions must be known at compile time
- Primitive types: boolean, char, int, long, float, double
- Reference types: String, JFrame, user-defined types
- on indicating datatype
- limits the type of data and the values that the variable can hold
- limits the result of an expression
- all variables and expressions must be known at compile time
- variables can be declared throughout the code but must be declared before first use
<datatype> <variable name>;<datatype> <variable name> = <value>;- variable delcarations must be within the class or method
Output Statements
System.out.print()- print where cursor isSystem.out.println()- print and add\nat the end- parameters to be printed placed inside the parenthesis
- parameters may be any expression that would evaluate into a literal
Getting input through the terminal
- Import the Scanner class so our file has access to it
import java.util.Scanner; - Declare a Scanner variable
- Instantiate a Scanner object passing the InputStream
- Use the Scanner object to get input
- Close the Scanner’s input stream
Scanner class
- Is a reference data type
- Reference data types need to be instantiated before use (we need to create an instance of a class)
- Needs some input stream (from the terminal or a file)
- As we just want to get input from the terminal, we can use the InputStream of System and pass that in as a parameter
import java.util.Scanner;
public class myApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
dRadius = sc.nextDouble();
//nextDouble() returns a double value that was input by the user
System.out.println("Area is " + dArea);
sc.close();
//when done with an InputSteam, close it to avoid a resource leak.
//if you forget to close it, the JVM will eventually collect it.
}
}
Comments in Java (Javadocs)
Documentation is an important skill to develop
- Forces you to explain your code
- Helps others understand your code
- consult API/documentation
//Line commenttexts in same line/* Multiple line comment*/texts within markers are disregarded- ``/** Javadoc comment */
Practice 2 String Equivalences
public class Main {
public static void main(String[] args) {
String s1 = "Hello",
s2 = "Hello",
s3 = s1,
s4 = new String("Hello"),
s5 = new String("Hello");
System.out.println("Usage of ==");
System.out.println("s1 == s2 -> " + String.valueOf(s1 == s2)); //true
System.out.println("s2 == s3 -> " + String.valueOf(s2 == s3)); //true
System.out.println("s1 == s4 -> " + String.valueOf(s1 == s4)); //false
System.out.println("s4 == s5 -> " + String.valueOf(s4 == s5)); //false
System.out.println("Usage of equals()");
System.out.println("s1 == s2 -> " + s1.equals(s2)); //true
System.out.println("s2 == s3 -> " + s2.equals(s3)); //true
System.out.println("s1 == s4 -> " + s1.equals(s4)); //true
System.out.println("s4 == s5 -> " + s4.equals(s5)); //true
}
}
Unlike in other practice exercises, you're not expected to come up with a coded solution. Simply observe what the output of the different statements above and try to answer the following questions. This is a practice exercise, so there's no need to submit anything if you don't want to. The goal of this exercise is to show you different means of asserting equivalence in Java. If there are any questions, feel free to raise them with your instructor.
- What does == assert?
It checks if it has the same string instance of "Hello". It's more like a reference comparison. - When does == result in True? in a False?
It's true in the first two statements of the first section where it refers to the same object in the memory. It's false in the last two statements of the first section because it refers to two different instances with the same "value". - What does the String method equals() do?
It checks the evaluates the "values" within the objects. Here it's checking the content of the two variables if they have the same characters. - Which is more suited for checking whether the String values of two String variables are the same?
Equals() would be more suitable because it ensures that the values, not instances, are being compared. - Are there any issues with using stringVariable.equals(anotherStringVariable)?
If you really meant to compare two different instances, it would only compare the value. Also, a NullPointerException could happen if you call equals() on it
ChatGPT answers
-
What does == assert? The == operator asserts whether two objects or primitive values are equal in terms of reference. In the given code, == is used to compare string references.
-
When does == result in True? When does it result in False? The == operator results in True when two string references point to the same object in memory. In the given code, s1 and s2, as well as s2 and s3, are references to the same "Hello" object, so == returns True for these comparisons. However, s1 and s4, as well as s4 and s5, are references to different objects with the same content, so == returns False for these comparisons.
-
What does the String method equals() do? The String method equals() compares the content of two string objects and returns true if the content is the same, and false otherwise. It checks whether the characters within the strings are identical.
-
Which is more suited for checking whether the String values of two String variables are the same? To check whether the String values of two String variables are the same, it is more suitable to use the equals() method. Comparing string values using equals() ensures that the actual content of the strings is being compared, rather than just their references in memory.
-
Are there any issues with using stringVariable.equals(anotherStringVariable)? There are no inherent issues with using stringVariable.equals(anotherStringVariable) to compare string values. However, it's important to consider the possibility of null values. If either stringVariable or anotherStringVariable is null, calling equals() on it would result in a NullPointerException. To avoid this, it's a good practice to check for null values before using equals(), like this:
if (stringVariable != null && stringVariable.equals(anotherStringVariable)) {
// Perform desired operations
}
Module 2 Control Statements
Recall: Relational Operators
- < less than
- <= less than or equal to
- == equal to
- != not equal to
-
greater than
-
= greater than or equal to
- && and (evaluated first)
- || or (evaluated second)
Control statements are if-else statements
Sequential Execution
- Statements in programs are executed in sequence

Control Statement
- Statements that alters the flow of execution

If Statement
- AKA selection or branching statement
- selects or branches to one of the alternative blocks of execution

if (<boolean expressions>)
<then block>
if (<boolean expressions>) {
<then block>
}
Side trip: Inverse
- opposite
- any conditional statement has an inverse
if (<boolean expressions>)
<then block>
else
<else block>
if (<boolean expressions>) {
<then block>
} else {
<else block>
}
Nested If Statements
- The
<then block>and<else block>could contain any statement including another controlled statement such as if - If a student gets a grade 60 and above, check if the student’s age is less than 10, if so, tell him he did a great job else tell him to prepare for the next exam. Else tell him that he did not pass.
if (g>=60)
if (age<10)
System.out.println("You did great!");
else
System.out.println("Prepare for the next exam");
else
System.out.println("You did not pass");



Dangling Else problem
- Java compiler matches an else with a previous unmatched
- Given numbers x and y, if x is greater than 5 then check if y is greater than 5. If y is greater than 5, then display “x and y are > 5”. Else if x <= 5 then display “x is <= 5”


Switch Statement
- the if statement allows you to select one of two sections of code to execute based on a boolean value (only two possible values)
- the switch statement allows you to choose from many statements based on an integer (including char)
switch (<expression>) {
<case label 1>: <case body 1>
<case label 2>: <case body 2>
<default>: <default body>
}
Default Case
- There can only be 1 default case per switch statement
- If no case value matches the switch expression value, execution continues at the default clause.
- is the equivalent of the "else" for the switch statement.
- It is written after the last case be convention, and typically isn't followed by break because execution just continues out the bottom of switch if this is the last clause
Waterfall Effect
- use break to cause the execution to continue from the statement after the switch statement
F2F Parts of a java file
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
Parts of a .java file
Every java file starts with the public class and all code is inside the class.
public means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and package-private. See here for more details.
static means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.
staticmeans that the method belongs to the Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial. (w3schools)
void means that the method has no return value. If the method returned an int you would write int instead of void.
The combination of all three of these is most commonly seen on the main method which most tutorials will include.
Java methods
A java method follows the SRP (Single Responsibility Principle).
A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions. Why use methods? To reuse code: define the code once, and use it many times. (Reference)
== asserts equality
look into address/memory location and pointers in java
class Test {
public static void main(String[] args) {
//Primitive way
int i=10;
int j=10;
System.out.println(i==j); //true
//OO Way
Integer k = new Integer(10);
Integer l = new Integer(10);
System.out.println(k == l); //false
System.out.println(k.equals(l)); //true
/* You don't have to close the instance for Integer. Mostly it's just Scanner and Files. */
}
}
On Instantiation
Week 3
May 19, 2023 Notes:
Reminders:
Follow these standards:
- Class name should start with capital letters
- Read the specs carefully, don’t create unnecessary features. Bugs ≠ Features 😞
- Test your own code. Know when and how to test your own code
Scanner sc = new scanner(system.in);
^^^ this is technically a structure and “sc” is a reference variable
What the difference of Programming paradigm and language?
- Paradigm is more of the Philosophy or outlook on how to program, while language is how you convey it.
- So programming languages can manifest multiple different paradigms
Procedural Programming
- This is top down, you can trace everything from top to bottom in main; ccprog1 type-beat
- code is a one man army: i do this then this if that then this do this again, very straight eew
Object-Oriented Programming
- thinks about code as objects instead of just sets of instructions.
- these objects have their own goals, attributes, and characteristics
- This philosophy allows for object to interact with each other within an environment
- This philosophy is encourages generalization and abstraction
- Objects have their own job, they get to be developed on their own without breaking each other
- Object oriented is different from functional programming since objects can store their own values, while functions don’t
What is the difference of Classes and Objects?
- Classes
- The template or blueprint from which instances of objects may be created
- Objects
- Each object is an instances of a class
- Has its own copy of attributes
- Can act in the way the class is designed
- TL;DR this dude is the manifestation of the class
Packages and import
- side note: compressed if-statement
<condition>?<true scenario>:<false scenario> - illegal modifier if ????
- subclass and inner class is different
- inner class can use private access modifier
- folder structure can affect access modifiers
Packages
- are folder structures of classes
- java.util
- myfolder.myclass
- be conscious of using package
<name>
Access Modifiers
- default (no access modifier) "package private"
- can only be used within that package
- public (any class can use public) (+)
- open to all classes
- without public it becomes a package default
- private (-)
- exclusive
- other classes cannot access that member
- can be accessed by the same class file
private int yearBorn;
- protected
UML diagramming

- Class (object name)
- Attributes
- significant piece of data containing values that describe each instance of that class
- AKA fields, variables, or properties
- Format:
<visibility><name of variable>:<datatype>
- Methods
- AKA operations or functions
- what are the different behaviors of this animal class?
- Format
<visibility><name of method>(<variables>)
Visibility
-means private (can't be access by any other class or subclass)- attributes are either private or protected
+means public (can be accessed by other classes/subclasses)- methods are often public
#means protected (can only be accessed by the same class or it's subclasses)~(tilde) means package/default (can be used by any other class as long as it's in the same package (file))

Relationships
- Inheritance
--> - Association
-- - Aggregation
--<>- part can exist outside of a whole
- Composition
--<x>- part can't exist outside of a whole


Concept: Abstraction
- "Animal" is an abstract class because every time we have an instance of that class it will be tortoise, otter, or slow loris
- Keeps the code DRY (Don't Repeat Yourself)
- Class names are usually in italics or in
<<these>>

^^ Example of Association

^^ Example of Aggregation (context: a group of tortoises is a creep)

^^ Example of composition (context: if the visitor center was broken down, the lobby and bathroom wouldn't exist)
Concept: Multiplicity
- denotes how many there should be
0..1zero-to-one (optional)nspecific number0..*zero-to-many1..*one-to-manym..nspecific number range

- There would be one lobby (
1) - There are more than one or at least one bathroom (
1..*)
Real world example Link

- customer is a child of user class
- shopping cart has a compositional relationship with customer (can't exist without customer) (there can be 0 to many shopping carts set by the user)
- order has a compositional relationship with customer (can't exist without customer) (customer can have 0 or many orders) (an order can only have 1 customer)
- shipping info has a compositional relationship with order (can't exist without order)
- order details has a compositional relationship with order (can't exist without order) (each order has one order detail, and each order detail has one order)
- admin is a child of user class
From someone in 121
- like for composition: car to engine (a car has an engine, an engine is part of a car); another is a game charac and their hp.
- association: a game character and an enemy (an enemy doesn't necessarily have to exist for the character to exist, and vice versa)
- aggregation: a game character and their inventory (characs can have an empty one, etc.)
- inheritance: from the base character, ypu have different types -- for example, mage, tank etc.! all of them have shared characteristics/attributes like hp, mana (siguro), ganun, but they can also differ with their skillset etc
UML
| admissions | -> | patient |
- admissions gets an instance of the patient class
Association
- two classes in a model can interact with one another
- both classes exist independently*
- the student will still be a student and an instructor will still be an instructor
Aggregation
- subset of association
- child can exist independently without the parent class
- pizza can still exist without pepperoni
Composition
- subset of association
- child class cannot exist independent of the parent
- a person cannot exist without a heart or blood
https://www.w3schools.com/java/java_encapsulation.asp
- on getter and setter encapsulation
https://stackoverflow.com/questions/2411270/when-should-i-use-this-in-a-class - when to use "this." in a class
Package Handling
In Java, we use packages to group related classes, interfaces, and sub-packages. Think of it as a folder in a file directory.
- Making related types easier to find – packages usually contain types that are logically related
- Avoiding naming conflicts – a package will help us to uniquely identify a class; for example, we could have a
com.baeldung.Application, as well ascom.example.Applicationclasses - Controlling access – we can control visibility and access to types by combining packages and access modifiers
Creating Packages
//start of code
package com.baeldung.packages;
Naming
- names in all lowercase
- package names are period-delimited
- determined by the company or organization
- example:
www.baeldung.com==com.baeldung- subpackages will be
com.baeldung.packagesandcom.baeldung.packages.domain
- subpackages will be
Directory Structure
com -> baeldung -> packages
Package Accessibility (Protected, Package-Private)

- public
- whether in a package or not is available to any class, package, and subclass
- protected
- available to any class, any package, any subclass
- none/default
- available to other classes ONLY within the package
- package-private
Using Package Members
Package Example
package com.baeldung.packages.domain;
public class TodoItem {
private Long id;
private String description;
// standard getters and setters
}
Importing the Package
In order to use our TodoItem class from a class in another package, we need to import it. Once it's imported, we can access it by name. We can import a single type from a package or use an asterisk to import all of the types in a package.
import com.baeldung.packages.domain.*; //entire domain subpackage
import com.baeldung.packages.domain.TodoItem; //importing only the class from that package
//importing pre-existing classes
import java.util.ArrayList;
import java.util.List;
public class TodoList {
private List<TodoItem> todoItems;
public void addTodoItem(TodoItem todoItem) {
if (todoItems == null) {
todoItems = new ArrayList<TodoItem>();
}
todoItems.add(todoItem);
}
}
Sometimes, we may be using two classes with the same name from different packages. For example, we might be using both java.sql.Date and java.util.Date. When we run into naming conflicts, we need to use a fully qualified class name for at least one of the classes.
public class TodoList {
private List<com.baeldung.packages.domain.TodoItem> todoItems;
public void addTodoItem(com.baeldung.packages.domain.TodoItem todoItem) {
if (todoItems == null) {
todoItems = new ArrayList<com.baeldung.packages.domain.TodoItem>();
}todoItems.add(todoItem);
}
// standard getters and setters
}
From System Directories
// directory structure
└── com
└── test
└── Test.java
//Test.java
package com.test;
class Test {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
//main java file
import com.test.Test;
Compiling Packages
We need to compile our TodoItem class first because our TodoList class depends on it.
> javac com/baeldung/packages/domain/TodoItem.java
//for com.baeldung.packages.domain.TodoItem class
If our class compiles cleanly, we'll see no error messages and a file TodoItem.class should appear in our com/baeldung/packages/domain directory.
For types that reference types in other packages, we should use the -classpath flag to tell the javac command where to find the other compiled classes.
> javac -classpath . com/baeldung/packages/*.java
Running the application
> java com.baeldung.packages.TodoApp
F2F Smelly code, UML planning, etc
- Java (procedural language)
- OO (object oriented programming)
- class (blueprint) -> members that have attributes and methods
- members access modifiers
- public, private, default, protected
- methods
- constructors -> overloading
- objects are also called instances
- Principles
- SRP (single responsibility principle)
- DRY (do not repeat yourself)
public class Pet {
private String name;
private int yearAdopted;
private char sex;
}
//more code here but i can't see the mf board
- parameters are ordered pairs, look into "constructor overloading" which can be in any method
- Link
- look into addresses and pointers(?) in java >> CALLED REFERENCES Link
Smelly Codes in software engineering
- we don't want our code to be fragile
- side effects
void main(){
myClass mc1 = new Myclass();
mc1.setIvalue(ioc);
function1(mc1)l
SySout(mc1.getIvalue())
void function1(myclass mcgeneric)
mcgeneric.setvalue(90)l
//more code here
}
Smelly Codes
- Side effect (fragile code)
- Spaghetti Code (hard to trace)
- Introduction to Code Smell
- Identifying Code Smells in Java
Feedback
- Make your codes deliberate (Not example: System.out.println(); can be deleted inbetween line VS System.out.println("\n");)
Software Development
-
Requirements come from the client
-
After requirements, do Planning
-
After planning, do coding
-
After coding, do testing
-
After testing, do deployment
-
If you're working on nontrivial code like OO, go back to planning
-
bc of OO, you cna play a game even though not everything is loaded (everything is in packages)
Planning - UML (Universal Modeling Language)
- UML is a drawing, JAVA is a language
- class diagrams (OO) and Entity Relationship diagram ERD (databases)
- Class diagrams are classes and relationships
- Helps you plan your code structurally
EXAMPLE
(ACCESS MODIFIER (-)private, (+)public, (#)protected, ()default)
| name of class | data |
|---|---|
| attributes | access modifier symbol: datatype; |
| methods | method stuff here |

/* MORE NOTES HERE I CANT READ THE BOARD */
https://www.smartdraw.com/uml-diagram/
Relationships
- association
- String
Simple enrollment system

Course Class
- timeslot
- teacher
- room assignment
- section
- prerequisites
- availability
- number of units
- class number
Student Class
- isstudent?
- idnumber
- password
Module 2 Strings and Characters
Characters
- single letter, special character, or digit
char <identifier>;- represented by two
''
Escape Characters
- characters with special functions
- character preceded by a backslash
\is an escape sequence and has a special meaning to the compiler
| Escape Sequence | Description |
|---|---|
\t |
insert a tab in the text at this point |
\b |
insert a backspace in the text at this point |
\n |
insert a newline in the text at this point |
\r |
insert a carriage return in the text at this point |
\f |
insert a formfeed in the text at this point |
\' |
insert a single quote character in the text at this point |
\" |
insert a double quote character in the text at this point |
\\ |
insert a backslash character in the text at this point |





- Is
System.out.println("Hello World");the same asSystem.out.print("Hello World\n");?
String
- reference data type
- stores String literals
- set of characters
- represented using two
""
String <identifier>;
String <identifier>, <identifier>;
String <identifier> = "<String Literal>";
String comparison
- "Albert" is not equal to "albert" because of the capital A
- in comparing Strings, we don't use
"=="instead, we use a methodequals(<arguments>)
Module 2 Methods
Methods (Functions)
- block of codes that performs a specific task
- helps programmers organize programs into parts like books and chapters
- helps reduce lines of code in a program
- states of variables regardless of operations and expressions done inside the method stays inside the method
- main is also a method
- header
- access modifier
- return type
- method name
- parameter/s
- opening curly brace
- body
- close curly brace
<access modifier> <return type> <method name> (<parameter>) {
<method body>;
}
public static void main(String[] args) {
<method body>;
}
//no parameter no return data
public static void PrintHello(){
System.out.println("Hello");
}
//with parameter no return data
public static void PrintParameter(String parameter){
System.out.println(parameter);
}
//with parameter with return data
public static int Increment(int parameter){
parameter = parameter + 1;
return parameter;
}
public static int getIncrement(int a){
a = a + 1;
return a;
}
//no parameter with return data
public static int getSum(){
return 1+2;
}
public static int getSum(){
int a = 1+2;
return a;
}
Return Type
- Since methods are made to perform specific task, they may or may not return data to the caller
- Data type of data to be returned must match the return type and vice versa
- example return types: class, int, double, string, etc
return <expression or variable>;
Parameters
- data passed from the caller to the method
Sample problem
- all programs should compose of 2 or more methods
- write a method that simply displays "Goodbye"
- write a program that asks for username and displays "Hello
<username>!" - Write a program that displays a 5x5 box of asterisks
- Write a program that computes for percentage given 2 numbers, a and b
formula: a/b * 100 - Write a program that multiplies 2 numbers and increments it
- write a program that authenticates username and password
Module 2 Loops (While, For, Do-while)
Loops
- gives our program the ability to execute lines of codes more than once depending on our set condition
- gives our program the ability to be more flexible
- are interchangeable and up to your discretion when to use what loop
While loops


while (<boolean expression>) {
<while block>
}
Practice problems
- What if we want to produce the console output 10 asterisks, 50 asterisks, and then 100 asterisks?
- Write a program that prints alternating 5 asterisks and 5 plus signs.
- Write a program that produces a 3x3 asterisk box
- Write a program that makes a 5x3 asterisk box
- What if we want to produce asterisks only on odd lines of console output in 5 output lines?
- What if we want to produce asterisks only on odd lines of console output in 5 output lines and 5 equal signs for even lines of output in 5 output lines?
- Write a program that prints a triangle (leaning left)
- Write a program that prints HI while the user enters "yes" (regardless of case)
- Write a program that prints a reverse triangle (leaning left)
- Write a program that produces a no-fill 5x5 asterisk box
- Write a program that produces a no-fill 5x5 square
Endless looping
- happens when there is no way the loop terminating boolean expression will become false
- for loop is usually for enumerating arrays, list, etc.
while (true) {
System.out.println("Just looping");
}
For loops
- for loops use integer variables to initiate and end
for (<assignment>;<boolean>;<operation>) {
<for body>
}

Arrays
- container that holds a fixed number of values of a single type
<data type>[] <identifier> = new <datatype>[<size>];
int[] Array_Integers = new Int[10];



Getting Size of an array
System.out.print(Array_Integers.length); //10
Practice Problems
- Write a program that assigns the ff in a 3x3 2d array

- write a program that displays your 3x3 array (clue: use two loops)
Do-while
Challenge Questions
-
Write a program that prints reverse isosceles triangle given a size input (which determines rows)
-
write a program that prints a diamond (input should only be greater than or equal to 3 and an odd number)
-
Write a program that generates a random (1 to 20) number and allows the user to guess the generated number 5 times. Depending on the user’s guess, the program should tell the user whether his next guess should be higher or lower than the current guess. Oracle Random API
-
allows a block of code to be executed repeatedly based on a given boolean condition however instead of evaluating the boolean condition first, the block of code inside will be executed first
do {
<code block>
} while (<boolean expression>);
Getters and Setters
Getters and Setters
Main.java
public class Account {
private String name;
private String age;
public static void main(String[] args) {
Account a = new Account();
a.setName("Pablo");
a.setAge(34);
System.out.println(a.getName());
System.out.println(a.getAge());
a.printDetails();
}
public void printDetails(){
System.out.println(getName() + ", " + getAge());
}
public void setName(String name){
this.name = name;
//this account's name, not the parameter
}
public void setAge(int age){
this.age = age;
//this account's age, not the parameter
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
//eclipse also has a feature called source>generate getters and setters
}
Constructors
Main.java
public class Main {
public static void main(String[] args) {
Shirt s = new Shirt(); //creates a new shirt
s.setColor("White");
s.setSize('M');
s.putOn();
}
}
Shirt.java
public class Shirt {
private String color;
private char size;
Shirt(String newColor, char newsSize){
System.out.println("Inside constructor!");
color = newcolor;
size = newsize;
}
public static void putOn() {
System.out.println("Shirt is on!");
}
public static void takeOff() {
System.out.println("Shirt is off!");
}
public static void setColor(String color){
this.color = color;
}
public static void setSize(char size){
this.size = size;
}
}
F2F MVC Architecture
design pattern
- Model - holds the data; being used by view and controller
- attributes
- View - interface, all I/O
- Controller - manages flow of the application
StudentClass < - - - StudentController < - - - View
https://www.edureka.co/blog/mvc-architecture-in-java/
frontend
- HTML (GUI/View)
- JSS/CSS
backend
- PHP
- JSP (java server pages) ---> controller
UserClass
- -name
- -phone
- +set/get()
ControllerClass
- instantiates User
- +queryDB() //interacts with DB
databases (part of backend)
Week 10a Abstract and Interfaces
Practice Exercise 9 - Phones

Solution 1: Centralize Logic in Landline Phone
- However, all logic inherited from LandlinePhone is dependent on the idea in which the logic inherited will stay the same. Any changes to LandlinePhone will affect MobilePhone.

Solution 2: Elevate Commonalities to a Singular Class
- Have more code to maintain but aids in organization and scalability
- in video: you can have
call(phone: Phone): voidintocall(object: Object): voidand then doif obj instanceof LandlinePhone- Makes documentation harder, "why is it so broad when you can be more specific?" Therefore, don't pass in
object: Object

- Makes documentation harder, "why is it so broad when you can be more specific?" Therefore, don't pass in
When we elevate the responsibility,
- Phone has a purpose as a superclass.
- do we ever imagine instantiating a Phone object? -> No -> Turn the superclass into an Abstract Class
- it's not meant to be instantiated
Four OOP Principles
- Encapsulation - Objects must be the only entity responsible for maintaining its own states
- Abstraction - Only relevant data and behavior are exposed at any given time, the rest are abstracted away
- Inheritance - Objects may acquire some, if not all, the properties and behaviors of another object, typically their parent object
- Polymorphism - Objects may have multiple types; apart from their object type, they also have the object type of their parent objects
Abstraction
- process of hiding certain details and showing only essential information to the suer
- in Java, abstraction can be achieved with either abstract classes, methods, and interfaces
- Helps "force" classes to have certain methods
- applies constraints that allow subclasses to conform to the parent's design
- Once a method is an abstract, the whole class should be an abstract
Abstract Classes
- provide common functionality across a set of related classes and allowing default method impolementation
- can't be instantiated
- need to be extended to be used (only serves as a parent)
- once extended, all methods need to be implemented
- constructors can be public but java will not allow it to be instantiated anyway
- can it have protected constructors?
- Have have abstract and concrete methods
- concrete - method that has logic
- abstract - no functionality (just an access modifier, return datatype, parameters)
- When to use an abstract class?
- when you want to provide properties and methods across related classes, but instantiating the parent class makes no sense
- when you want all related classes to contain a specific implementation of some methods, but also want the implementation of other methods to be determined by specific child classes
Abstract Methods
- don't have a method body; the declaration is done in the abstract class but the implementation is defined in a child class
- the first non-abstract class that extends an abstract class with abstract methods must define the implementation of all undefined abstract methods

- the implementation has to be defined in Class instead of AC2.
public abstract class Animal {
public Animal() {
//constructor
}
abstract public void makeSound();
public void doSomething(){
//something
}
}
public class Dog extends Animal {
//the program will not compile if we don't implement abstract public void makeSound because it's mandatory that all abstract methods are defined in the class where the abstract method is extended
// you can interchange abstract and the access modifier ex. public void public abstract
@Override
public void makeSound(){
Sysout.println("Bark");
}
//you can also call doSomething or override it
}
- Using the concept of polymorphism
- if we have an
ArrayList<Animal>, we can call and put instanceOf Dog or any child classes within that ArrayList - Ex. ActionPerformed is overridden in GUI MainView
public abstract class Animal {
public Animal() {
//constructor
}
abstract public void makeSound();
public void doSomething(){
//something
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal(); //not allowed
Animal animal = new Dog(); //allowed
ArrayList<Animal> animals;
animals = new ArrayList<Animal>(); //allowed because the reference type of animals is ArrayList
//non abstract subclasses can be put into ArrayLists
//we can store anything that is a subclass of Animal within the animals ArrayList
}
}
Multiple Inheritance
- You cannot extend multiple parent classes.
- In Java, a class can only have one direct superclass.
- Other languages like C++ has support for multiple inheritance
- Multiple inheritance is the concept of inheriting members from multiple superclasses but there issues to this: such as tracing which members belong to which class and how memory is managed
- There are ways to achieve this in Java though, such as using Interfaces
Interfaces
- Methods are easier to spread out compared to variables.
- Similar to classes but only contain method declarations with no implementation (total abstraction of the methods)
- Have been known to be more useful than simple inheritance because you can implement multiple interfaces
- Better maintains the integrity of a class's attributes and methods
- Ensures common behavior between two otherwise unrelated classes
- Sole purpose is to ensure that any class that implements an interface is to have specific methods
- Think of it as an abstract class with only abstract methods
- No variables or characteristics
- An interface requires one or more abstract methods, cannot contain concrete methods
- While an Abstract class can have complete concrete methods but cannot be instantiated
- Use an interface if you want to define commonality among subclasses but only want to define behavior/functionality and not characteristics (variables)
- Interfaces normally force method implementation, they're known to force behavior, thus giving class an "ability" name or X-able like Killable
- There's no required "abstract" keyword within interfaces as all methods in an interface is abstract. There's no harm in declaring it anyway
Example
- Monster, Hero, Chicken, and Lovelife -> they can all Die
public interface Killable {
public void die();
//parameters should be defined here and copied among the subclasses, as they are carried over
}
public class Monster implements Killable {
public void die() {
//game mechanics
}
}
public class Hero implements Killable {
public void die() {
}
}
public class Main {
public static void main(String[] args) {
Killable K = new Killable() {
public void die() {
//logic here
}
}
}
}
| Interface | Abstract |
|---|---|
| No concrete methods | Can have variables |
| Only methods without implementation are allowed | Can have concrete methods |
| No Variables allowed | Can have abstract methods |
| Cannot be instantiated |
- ActionListener is an interface but we need to define the logic behind it
- a Button is a class on its own
UML

ArrayList vs List
Arrays
String[] friendsArray = new String[10]; //Arrays - size never varies
String[] friendsArray2 = {"John", "Chris", "Eric", "Luke"};
System.out.println(friendsArray[1]);
System.out.println(friendsArray.length);
// can't add elements to array because of fixed size
friendsArray[0] = "Carl"; //changing an element
//can't remove elements due to fixed size
System.out.println(friendsArray); //java just gives you the memory address
- Arrays can hold objects and primitive types
- Specify index to access array
ArrayList
import java.util.ArrayList;
ArrayList<String> friendsArrayList = new ArrayList<>();
ArrayList<String> friendsArrayList2 = new ArrayList<>(Arrays.asList("John", "Chris", "Eric", "Luke")); //comma-separated values
System.out.println(friendsArrayList.get(1));
System.out.println(friendsArrayList.size());
friendsArrayList.add("Mitch");
friendsArrayList.set(0, "Carl"); //replacing at an index
friendsArrayList.remove("Chris"); // friendsArrayList.remove(1);
System.out.println(friendsArrayList); //java uses toString
- ArrayLists can only hold Objects but supports wrapper types for primitives
List vs ArrayList
//List is an interface
List<Integer> intsList = new ArrayList<>();
List<Integer> intsList2 = new LinkedList<>();
//declare as the interface and create the object with the class
