CCPROG3_EXPORT

README

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

Java is an object-oriented language

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:

SRP

Single Responsibility Principle


The Object Oriented Paradigm

_attachments/Pasted image 20230516141035.png

Programming Paradigms

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

_attachments/Pasted image 20230516141413.png

_attachments/Pasted image 20230516141420.png

Object-oriented programming

Classes and Objects

Summary


Module 2 Object Oriented Paradigm Continued

Java Tutorial

Java

_attachments/Pasted image 20230516142315.png

Writing Java Applications

_attachments/Pasted image 20230516142343.png

Naming Conventions

Class Declarations

Declaring variables

Output Statements

Getting input through the terminal

  1. Import the Scanner class so our file has access to it import java.util.Scanner;
  2. Declare a Scanner variable
  3. Instantiate a Scanner object passing the InputStream
  4. Use the Scanner object to get input
  5. Close the Scanner’s input stream

Scanner class

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


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.

  1. What does == assert?
    It checks if it has the same string instance of "Hello".  It's more like a reference comparison.
  2. 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".
  3. 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.
  4. 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.
  5. 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

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

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

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

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

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

Control statements are if-else statements

Sequential Execution

Control Statement

If Statement


if (<boolean expressions>)
	<then block>

if (<boolean expressions>) {
	<then block>
}

Side trip: Inverse

if (<boolean expressions>)
	<then block>
else
	<else block>

if (<boolean expressions>) {
	<then block>
} else {
	<else block>
}

Nested If Statements

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

_attachments/Pasted image 20230604172650.png

_attachments/Pasted image 20230604172701.png

_attachments/Pasted image 20230604172707.png

Dangling Else problem

_attachments/Pasted image 20230604172754.png
_attachments/Pasted image 20230604172824.png

Switch Statement

switch (<expression>) {
<case label 1>: <case body 1>
<case label 2>: <case body 2>
<default>: <default body>
}

Default Case

Waterfall Effect


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

Stack Overflow

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.

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

Reference


Week 3

May 19, 2023 Notes:

Reminders:
Follow these standards:

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?

Procedural Programming

Object-Oriented Programming

What is the difference of Classes and Objects?


Packages and import

Difference

Packages

Access Modifiers


UML diagramming

_attachments/Pasted image 20230603164244.png

Visibility

_attachments/Pasted image 20230603164952.png

Relationships

_attachments/Pasted image 20230603165112.png

_attachments/Pasted image 20230603165125.png

Concept: Abstraction

_attachments/Pasted image 20230603165358.png
^^ Example of Association

_attachments/Pasted image 20230603165556.png
^^ Example of Aggregation (context: a group of tortoises is a creep)

_attachments/Pasted image 20230603165719.png
^^ Example of composition (context: if the visitor center was broken down, the lobby and bathroom wouldn't exist)

Concept: Multiplicity

_attachments/Pasted image 20230603170147.png

From someone in 121

UML

| admissions | -> | patient |

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


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.

Creating Packages

//start of code
package com.baeldung.packages;

Naming

Directory Structure

com -> baeldung -> packages

Package Accessibility (Protected, Package-Private)

Reference Oracle Educative

_attachments/Pasted image 20230603184043.png

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

Reference

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

  1. Java (procedural language)
  2. 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
  3. Principles
public class Pet {
          private String name;
          private int yearAdopted;
          private char sex;
          }
          //more code here but i can't see the mf board

Smelly Codes in software engineering

      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

Feedback

  1. Make your codes deliberate (Not example: System.out.println(); can be deleted inbetween line VS System.out.println("\n");)

Software Development

Planning - UML (Universal Modeling Language)

_attachments/01-class-diagram-in-uml-diagram-hierarchy.webp
Reference

EXAMPLE
(ACCESS MODIFIER (-)private, (+)public, (#)protected, ()default)

name of class data
attributes access modifier symbol: datatype;
methods method stuff here

_attachments/Pasted image 20230603162715.png

/* MORE NOTES HERE I CANT READ THE BOARD */
https://www.smartdraw.com/uml-diagram/

Relationships

Simple enrollment system

_attachments/Annotation 2023-05-26 141216.png

Course Class

Student Class


Module 2 Strings and Characters

Characters

Escape Characters

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

_attachments/Pasted image 20230604174001.png
_attachments/Pasted image 20230604174006.png
_attachments/Pasted image 20230604174013.png
_attachments/Pasted image 20230604174019.png
_attachments/Pasted image 20230604174027.png

String

String <identifier>;
String <identifier>, <identifier>;
String <identifier> = "<String Literal>";

String comparison


Module 2 Methods

Methods (Functions)

- 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

Parameters

Sample problem

  1. write a method that simply displays "Goodbye"
  2. write a program that asks for username and displays "Hello <username>!"
  3. Write a program that displays a 5x5 box of asterisks
  4. Write a program that computes for percentage given 2 numbers, a and b formula: a/b * 100
  5. Write a program that multiplies 2 numbers and increments it
  6. write a program that authenticates username and password

Module 2 Loops (While, For, Do-while)

Loops

While loops

_attachments/Pasted image 20230604175454.png
_attachments/Pasted image 20230604175513.png

while (<boolean expression>) {
	<while block>
}

Practice problems

Endless looping

while (true) {
	System.out.println("Just looping");
}

For loops

for (<assignment>;<boolean>;<operation>) {
	<for body>
}

_attachments/Pasted image 20230604180539.png

Arrays

Oracle

<data type>[] <identifier> = new <datatype>[<size>];

int[] Array_Integers = new Int[10];

_attachments/Pasted image 20230604180757.png
_attachments/Pasted image 20230604180808.png
_attachments/Pasted image 20230604180814.png

Getting Size of an array

System.out.print(Array_Integers.length); //10

Practice Problems

Do-while

Challenge Questions

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

StudentClass < - - - StudentController < - - - View

https://www.edureka.co/blog/mvc-architecture-in-java/

frontend

backend

UserClass

ControllerClass

databases (part of backend)


Week 10a Abstract and Interfaces

Practice Exercise 9 - Phones

_attachments/Pasted image 20230802192017.png

Solution 1: Centralize Logic in Landline Phone

Solution 2: Elevate Commonalities to a Singular Class

When we elevate the responsibility,

Four OOP Principles

  1. Encapsulation - Objects must be the only entity responsible for maintaining its own states
  2. Abstraction - Only relevant data and behavior are exposed at any given time, the rest are abstracted away
  3. Inheritance - Objects may acquire some, if not all, the properties and behaviors of another object, typically their parent object
  4. Polymorphism - Objects may have multiple types; apart from their object type, they also have the object type of their parent objects

Abstraction

Abstract Classes

Abstract Methods

_attachments/Pasted image 20230802195141.png

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

Interfaces

Example

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

UML

_attachments/Pasted image 20230802202652.png


ArrayList vs List

Video

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

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

List vs ArrayList

Video

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