diff --git a/Abstraction/README.md b/Abstraction/README.md new file mode 100644 index 0000000..9919894 --- /dev/null +++ b/Abstraction/README.md @@ -0,0 +1,35 @@ +## Abstraction + +- Hide certain details and show only what's necessary to the User +- Used through Abstract Classes/Interfaces +- Any class that inherits from an abstract class must implement all the abstract methods declared in the abstract class +- An abstract Class Cannot be instantiated + + +### Example + + +```java +public abstract class Animal{ + public abstract void animalSound(); + + public void sleep(){ + System.out.println("Zzz"); + } +} + +public class Dog extends Animal{ + public void animalSound(){ + System.out.println("Woofwoof"); + } +} + +public class Base{ + public static void main(String [] args) + { + Dog olivia = new Dog(); + olivia.animalSound(); + olivia.sleep(); + } +} +``` \ No newline at end of file diff --git a/Dynamic_Pro/Fib.class b/Dynamic_Pro/Fibonacci/Fib.class similarity index 100% rename from Dynamic_Pro/Fib.class rename to Dynamic_Pro/Fibonacci/Fib.class diff --git a/Dynamic_Pro/Fib.java b/Dynamic_Pro/Fibonacci/Fib.java similarity index 100% rename from Dynamic_Pro/Fib.java rename to Dynamic_Pro/Fibonacci/Fib.java diff --git a/Dynamic_Pro/README.md b/Dynamic_Pro/README.md index 423adf3..db9496e 100644 --- a/Dynamic_Pro/README.md +++ b/Dynamic_Pro/README.md @@ -1 +1,47 @@ ### Dynamic Programming + + + +#### Fibonacci Algorithm + +- A Tree like data structure +- Any computation I made within the tree that I plug into the formula ... +- I shouldn't have to compute again thanks to memoization it stores the value +- in an object and spits it out whenever there is a call to it +- I store the answer within the memo and caches that result +- My key is the nth number in the fibonacci sequence +- My value is the value i.e. output +- When making recursive calls, thanks to memoization, it outputs a stored value + - and doesn't have to travel through any further subtrees +- So memoizing my fib function ends up reducing the number of recursive calls I make + +##### Runtime Complexity + +- Memoizing my algo I see a linear functional call pattern +- i.e. I have n node and that's why the runtime complexity is O(n) +- where n is the top level call + +##### Space Time Complexity + +- O(n) + + +#### Grid Traveler + +- You want to travel +- You start at the top left corner and your goal is to end in the bottom right corner +- You can only go down or to the right +- You CANNOT move up or left or diagonally +- Find the # of different ways you can travel +- gridTravelTo(2,3) means how many different ways you can travel +- ...from the top left to bottom right in a 2x3(2 rows by 3 columns) + - 3 dif ways: + - right, right, down + - right,down, right, + - down, right, right +- gridTravelTo(1) means do nothing because you are already there +- gridTravelTo(0,1) means 0 rows and 1 column i.e. the grid is empty +- gridTravelTo(1,0) means 1 row and 0 columns i.e. the grid is empty +- gridTravelTo(8,0) means 8 rows and 0 columns i.e. the grid is empty +- gridTravelTo(0,0) means 0 rows and 0 columns i.e. the grid is empty +- base case: if one of your dimensions is empty then there is no grid diff --git a/Encapsulation/README.md b/Encapsulation/README.md new file mode 100644 index 0000000..0d55687 --- /dev/null +++ b/Encapsulation/README.md @@ -0,0 +1,83 @@ +### Encapsulation + +- One of the 4 pillars of OOP(A,E,I,P): +- I have 3 elements: + - Class + - Method + - Variables +- I wrap the variables and the code implementation which interacts with the methods as one +- Variables within my class cannot be accessed by other classes +- Only the methods of that particular class can access them +- All in all, it is the process by which I group information + + +#### Good Practice + +- Class Variables should always be declared private +- Setter and Getter Methods should be public + + +#### Example Encapsulating Class + +```java +public class EncapsulatingThis{ + + + + private String myFullName; + private String myIdentifNum; + private int myAge; + + + + public int getMyAge(){ + return myAge; + } + + public void setMyAge(int theAge){ + myAge = theAge; + } + + public String getMyId(){ + return myIdentifNum; + } + + public void setMyId(String myNewId){ + myIdentifNum = myNewId; + } + + + public String getMyName(){ + return myFullName; + } + + public void setMyName(String fullName){ + myFullName = fullName; + } + + //overriding the toString() method + @Override + public String toString() + { + return ("Hi my Name is: " + getMyName() + " and I am " + getMyAge() + " and my ID is: " + getMyId()); + } + +} +``` + + +#### Main Class + +```java +import java.util.*; +public class RunnerClass{ + public static void main(String [] args){ + EncapsulatingThis encapsObj = new EncapsulatingThis(); + encapsObj.setMyName("Omar"); + encapsObj.setMyAge(27); + encapsObj.setMyId("165X70B15D"); + + System.out.println(encapsObj.toString()); + } +} +``` \ No newline at end of file diff --git a/Interfaces/README.md b/Interfaces/README.md index 38bad94..b6e0cd5 100644 --- a/Interfaces/README.md +++ b/Interfaces/README.md @@ -1,8 +1,20 @@ -Interfaces are a little bit similar in concept to Inheritance. An interface defines behavior. So we have an object and right after it is a biiiig barrier, -this barrier is the interface. The barrier serves as to limit on how we interact with the object. We use an interface to work with an object. -When we program we tell the class that the object has to meet the requirements imposed by interface. Say I have a class Dog. The dog has the following behaviors -which are: walk(), woof(), eat(). We can define the behaviors thanks to interfaces. All in all, interfaces define behavior/characteristics that -classes need to implement. We can define how an animal eats/walks within the interface. Then the class can implement the interface. -A class does not extend an interface, it implements it. Whenever we work with multiple classes as a team of developer. We must believe that every developer will do -their part to implements the works of the interface of the designated class they are working on. Say for example, a class that implements the interface -walking well then we can trust that class that it can walk properly and not limp. An interface can extend interfaces but cannot extend/implement the class. +### Interfaces + +
+ +- Similar in concept to Inheritance. +- defines behavior. So we have an object and right after it is a biiiig barrier, this barrier is the interface +- The barrier serves as to limit on how we interact with the object. We use an interface to work with an object. + +- I tell the class that the object has to meet the requirements imposed by interface. Say I have a class Dog. The dog has the following behaviors which are: + - walk() + - woof() + - eat() +- We can define the behaviors thanks to interfaces. All in all, interfaces define behavior/characteristics that classes need to implement. +- We can define how an animal eats/walks within the interface. Then the class can implement the interface. + +- A class does not extend an interface, it implements it. Whenever we work with multiple classes as a team of developer. We must believe that every developer will do their part to implements the works of the interface of the designated class they are working on. + +- Say for example, a class that implements the interface walking well then we can trust that class that it can walk properly and not limp. + +- An interface can extend interfaces but cannot extend/implement the class. \ No newline at end of file diff --git a/Maps/README.md b/Maps/README.md index c9beb03..493c697 100644 --- a/Maps/README.md +++ b/Maps/README.md @@ -1,89 +1,134 @@ -### A map is an object that maps keys and values -### A map cannot contain the same keys -### A map is similar to a dictionary in Python and a Key-Value pair in JS -### Each key must be unique within a map -### Maps are very important to know when dealing with Abstraction in OOP -### Java has three types of maps: HashMap , TreeMap and and LinkedHashMap -### Ordering: - 1- HashMap:Key Order - 2- TreeMap: Key Order - 3- LinkedHasMap: Reverse Insertion Order FIFO - -### HashMap: - ``` - Key Order - ``` + +## Maps + +- A map is an object that maps keys and values + +- Cannot contain the same keys + +- similar to a dictionary in Python and a Key-Value pair in JS + +- Keys must be unique within a map + +- Maps are very important to know when dealing with Abstraction in OOP + +- Java has three types of maps: HashMap, TreeMap and LinkedHashMap + +
+ +### Ordering + +
+ +1. HashMap + +- Check if Empty: isEmpty() +- Remove a particular key: .remove() +- Does Not Maintain Insertion Order +- Holds A Value Depending on A Key +- Only Holds Unique Elements +- Lookup & Insertion: O(1) +- Only allowed to store 1 Null Key +- Allowed to store multiple null values + +2. TreeMap + +- Key Order +- Only Holds Unique Elements +- Lookup & Insertion: O(log(n)) +- Cannot Store Null as a key +- Allowed to store multiple null values +- Maintains Ascending Orders + +3. LinkedHasMap: + +- Only Holds Unique Elements +- Allowed to store only one null key +- Allowed to store multiple null values. +- Maintains Insertion Order +- FIFO + + + ```java + import java.util.*; -public class HashMap +public class HashMap { - public static void main(String args[]) - { - //HashMap Declaration - //HashMap
nameOfHashMap= new HashMap
(); - HashMap myHashMap=new HashMap();//Creating HashMap. - - myHashMap.put(2,"Papaya"); //Putting elements in Map. - myHashMap.put(3,"Mango"); - myHashMap.put(1,"Apple"); - myHashMap.put(4,"Lemon"); - - System.out.println(myHashMap); - } - - //Output: {1=Apple, 2=Papaya, 3=Mango, 4=Lemon} meaning Key Order + public static void main(String args[]) + { + //HashMap Declaration + //HashMap
nameOfHashMap= new HashMap
(); + + HashMap myHashMap=new HashMap();//Creating HashMap. + + myHashMap.put(2,"Papaya"); //Putting elements in Map. + + myHashMap.put(3,"Mango"); + + myHashMap.put(1,"Apple"); + + myHashMap.put(4,"Lemon"); + + System.out.println(myHashMap); + } + +//Output: {1=Apple, 2=Papaya, 3=Mango, 4=Lemon} meaning Key Order } + ``` + ### TreeMap + + ```java import java.util.*; -public class Main + +public class Main { - public static void main(String args[]) - { - //Tree Declaration - //TreeMap
nameOfTreeMap= new HashMap
(); - TreeMap myTreeMap=new TreeMap();//Creating HashMap. - - myTreeMap.put(2,"Papaya"); //Putting elements in Map. - myTreeMap.put(3,"Mango"); - myTreeMap.put(1,"Apple"); - myTreeMap.put(4,"Lemon"); - - System.out.println(myTreeMap); - } - - //Output: {1=Apple, 2=Papaya, 3=Mango, 4=Lemon} - //meaning Key Order + public static void main(String args[]) + { + //Tree Declaration + + //TreeMap
nameOfTreeMap= new HashMap
(); + + TreeMap myTreeMap=new TreeMap();//Creating HashMap. + + myTreeMap.put(2,"Papaya"); //Putting elements in Map. + + myTreeMap.put(3,"Mango"); + + myTreeMap.put(1,"Apple"); + + myTreeMap.put(4,"Lemon"); + + System.out.println(myTreeMap); } - - - - ``` -### LinkedHashMap - ``` - Ordered by Insertion FIFO - ``` - + +//Output: {1=Apple, 2=Papaya, 3=Mango, 4=Lemon} +//meaning Key Order +} +``` + ```java import java.util.*; -public class Main + +public class Main { - public static void main(String args[]) - { - //LHM Declaration - //LinkedHashMap
nameOfLinkedHashMap= new LinkedHashMap
(); - LinkedHashMap myLHashMap=new LinkedHashMap();//Creating Linked HashMap. - - myLHashMap.put("MW","Calculus3"); //Putting elements in Map. - myLHashMap.put("MWF","OrgCh1"); - myLHashMap.put("T","DS"); - myLHashMap.put("F","Music"); - - System.out.println(myLHashMap); - } - - //Output: {MW=Calculus3, MWF=OrgCh1, T=DS, F=Music} - //meaning Reverse Insertion Order FIFO + public static void main(String args[]) + { + //LHM Declaration + + //LinkedHashMap
nameOfLinkedHashMap= new LinkedHashMap
(); + + LinkedHashMap myLHashMap=newLinkedHashMap();//Creating Linked HashMap. + + myLHashMap.put("MW","Calculus3"); //Putting elements in Map. + myLHashMap.put("MWF","OrgCh1"); + myLHashMap.put("T","DS"); + myLHashMap.put("F","Music"); + + System.out.println(myLHashMap); + } + } - ``` +``` \ No newline at end of file diff --git a/Maven/README.md b/Maven/README.md new file mode 100644 index 0000000..ef521d9 --- /dev/null +++ b/Maven/README.md @@ -0,0 +1,308 @@ +## Maven + +- PM tool for JVM Languages + +- Used To Perform Major Tasks: + - Build Your Source Code + + - Testing Your Code + + - Packaging Your Code(JAR, WAR, EAR) + + - Generate Java docs + + - Dependency Management + + - Handling, Versioning Your Artifacts + +### How To Install + + - Head over to: https://maven.apache.org/download.cgi + - Download the Binary Zip Archive + - Extract It + +### 2- Create an environment variable in your system name it M2_HOME + + - This is where Other SW and libraries look for the Maven Installation + - Give it a path in the bin folder + +### Checking if the installation is successful + +```bash +mvn --version +``` + +### File Structure + +``` +├── /my-project-demo + ├── /.idea + ├── /src + ├── /main + ├── /java + └── /resources + ├── /test + └── /java + ├── /target + └── pom.xml +├── /External Libraries +└── /Scratches and Consoles +``` + +- All the static files go in our resources folder +- e.g. Property Files, or any file we need to read from(xml, csv,html, css, js) +- test file I store all my unit tests and integration tests +- pom.xml holds all the metadata of my Application i.e. project dependencies +- target folder holds all the java compiled class files + +### Creating A Project + + - Give it an artifact id(this is usually the name of your project) e.g. my-project-demo + - Give it group Id(this is usually the name of your company id in reverse order i.e. com.herokuapp.omarbelkady) + - Give it a version number e.g. 1.0-SNAPSHOT + + +### 3rd Party JAR files i.e. Dependencies + +- External Libraries are called "dependencies" +- Maven provides me with functionality on how to manage my dependencies +- ...thanks to the pom.xml file + +### Life Without Maven + +- I have to manually download the JAR files from the internet +- then I add them one by one + +### Dependency Section Thanks To Maven + +- Maven provides me with a dependency section where I can specify the info of the JAR I require in my project + - artifactid + - groupid + - version +- Maven will then automatically download these dependency specified, from the internet and load them into my project +- Load each dependency in a "dependency" tag +- And all your depenency tags should be in between 1 dependencies tag + +```xml + + + + + + + + + +``` + +- To add a dependency go to + +- Click on the Maven Icon to force IntelliJ to download the dependencies you have specified + +### Transitive Dependencies + +- Dependencies of my dependencies + +``` +├── /my-project-demo + ├── /.idea + ├── /src + ├── /main + ├── /java + └── /resources + ├── /test + └── /java + ├── /target + └── pom.xml +├── /External Libraries +└── /Scratches_and_Consoles +``` + +- All the static files go in our resources folder +- e.g. Property Files, or any file we need to read from(xml, csv,html, css, js) +- test file I store all my unit tests and integration tests +- pom.xml holds all the metadata of my Application i.e. project dependencies +- target folder holds all the java compiled class files + +### Maven Dependency + +- Can be categorized into two categories: + - Snapshot Dependency + - This dependency was created when the software was in active development + - Unstable + - Release Dependency: + - This dependency was created after the software was developed and is ready to be released i.e. ready to be deployed for production + - Stable + +- In all, when I am developing the software I use the snapshot versions for the dependencies. When the software is released, I use the release versions + +--- + +### Dependency Scopes + +- enables me to control the visibility of a Maven depenendency +- 5 types: + +1. **Compile**: made available at compile time within classpath [default scope] + +2. **Provided**: dependency provided at runtime by JDK or webserver, e.g. Servlet API dependency. The web server which is running my project provides me with the java servlet-api during runtime. This means that the dependency will be available in the class path of the project but will not be packaged in the JAR file nor the WAR file + +3. **Runtime**: dependency provided ONLY at runtime and NOT at compile time e.g. MySQL JDBC connector dependency. I mark the dependency as runtime to make sure I do not use the MySQL JDBC classes in my code instead of standard jdbc api + +4. **Tests**: dependency only available at the time of writing and running my unit tests e.g. junit, spring-boot-starter-test + +5. **System**: the path to the JAR should be specified manually using the < systemPath > tag. The only restriction is that I must specify the exact path of where to locate this dependency within my system. + +### Repositories + +- a special directory called a **repository** is the location where Maven stores my dependencies +- Local Repository[directory/folder in your machine] +- Remote Repository[Maven Website] where I can download the Maven dependencies +- If a dependency I specified in my pom is not in my local repository it goes ahead and connects to the remote repository and downloads the remote repository and stores the dependency within my local repository + +#### How To Define A Repository within my POM always after my closing dependency tag + +```xml + + + my-internal-website + https://myserver/repo + + +``` + +### Build Lifecycle Within Maven + +- How Does Maven Build Our Projects? + 1. default + 2. clean + 3. site + +#### Default Lifecycle Build Step Phases + +1. validate + - Makes sure pom.xml is validated or not validated +2. compile + - Compiles my source code +3. test + - Runs the unit tests in my project +4. package + - Packages the source code into an artifact +5. integration-test + - Executes the integration tests +6. verify + - Verifies the results of the integrations tests +7. install + - Installs the newly created package files(JAR or any other artifact) within my local repository + - Maven +8. deploy + - Deploy the newly created package to the remote repository + - If the newly created package is configured in the pom.xml file it will deploy the new package into the remote repository + +### Command + +```java +mvn clean install +``` + +- This command compiles the source code +- Runs the unit tests +- Creates the JAR file +- Install the JAR file into your local repository + +### Site Step + +- generate Java documentation that is present in my project + +### Plugins and Goals + +- To be able to execute the different lifecyle phases, Maven provides me with different plugins in order for me to perform each task in the lifecycle +- Every plugin has a relationship to a goal which is linked to the lifecycle phase(e.g. compile) +- To declare a plugin simple place in between a **plugin** tag that is within the **plugins** tag +- Any plugin I want to define must be within the build tag +- The build tag will usually be right below the dependencies section + +```xml + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + + +``` + +- The plugin above is in charge of compiling any test files or source files I have within my project. This is familiar to running + +```java +javac nameofclass.java +``` + +#### To trigger the compile lifecycle phase + +```java +mvn compiler:compile +``` + +### Maven tab⇒ Plugin section ⇒ Hit Expand ⇒ Click on Compile Goal + +- Compilation fails +- Java compiler of Maven within IntelliJ is configured to Java version 1.X +- To fix: +      0. Go to your pom.xml +      1. Head to build section +      2. Plugins ⇒ plugin +      3. Configuration Tag +      4. Change the source & target properties to the java version installed on your machine + +### Maven Install Plugin + +- This plugin is used to run the install lifecycle phase within the maven build lifecycle + +1. Compiles My Source Code +2. Runs Our Unit Tests +3. Package The Cource Code into an Artifact +4. Installs The Artifact Within My Local Repository + + +### Maven Deploy Plugin + +- Self-explanatory plugin +- runs all the phases which are part of the install phase +- deploys the created artifact to the remote repository + +0. To deploy the artifact to the remote repo you have to specify the remote repo details within your pom +1. Create a tag right above your dependencies tag and give it a name of **distributionManagement** +2. Within the distributionManagement tag create a tag named **repository** and place the information of your repository there +3. To uniquely identify a repository I specify the **id**, **name** and **url** +4. Run the command below to deploy your plugin + +```java +mvn clean deploy +``` + +### Maven Profiles + +- Profiles can be used within maven to create customized build configurations within my project +- I can customize the behavior of a build based upon specific conditions +- e.g. I can skip the test execution due to the fact that my build process may take a long time +- I create a profile that will skip the test execution phase + +#### How To Create + +- Right below your build tag create a **profiles** tag + +- Within your profiles tag create a **profile** tag I give it an: + - *id* + - *properties* + +- After creating a profile for the above example Maven will make sure to skip the test execution + +- I head over to the terminal and run the following command: +- -P flag indicates the id of the profile + +```java +mvn -Pskip-tests clean install +``` diff --git a/MustKnow/AlgoTypes/README.md b/MustKnow/AlgoTypes/README.md new file mode 100644 index 0000000..b2bc520 --- /dev/null +++ b/MustKnow/AlgoTypes/README.md @@ -0,0 +1,33 @@ +## Types of Algorithms + +- Backtracking Algorithm + - recursive problem solving approach + - I come up with N number of solution + - If the first solution does not solve my problem I go back + - I try the second solution and so forth + - I remove the first solution + - Playing soduku you find 4 is in the row, column and box therefore you backtrack and check 5 + - Trying to find your way out in a maze + +- Brute Force Algorithm + - Check every possible solution for the problem to be solved + +- Divide And Conquer Algorithm + - Divide the problem into sub-problems and solve each sub-problem independently + - i.e. Binary Search + +- Dynamic Programming Algorithm + - function X generates the output Y + - I store the result of Y and use it in function D + +- Greedy Algorithm + - Always chooses the best solution + - Solution is built piece by piece + - The subsequent piece chosen by the algorithm is usually the most obvious + - Examples in Various DS: + +- Recursive Algorithm + - an algorithm which calls itself + - i.e. factorial + + diff --git a/MustKnow/Array Algo/README.md b/MustKnow/Array Algo/README.md new file mode 100644 index 0000000..fba5e6e --- /dev/null +++ b/MustKnow/Array Algo/README.md @@ -0,0 +1,88 @@ +### Array Algorithms + + +#### Floyd's Cycle Detection Algorithm +```java +class ListNode { + int val; + ListNode next; + + ListNode(int val) { + this.val = val; + this.next = null; + } +} + + public class FloydCycleDetection { + public static boolean hasCycle(ListNode head) { + if (head == null || head.next == null) { + return false; // No cycle if head is null or only one node exists + } + + ListNode slow = head; // Slow pointer moves one step at a time + ListNode fast = head; // Fast pointer moves two steps at a time + + while (fast != null && fast.next != null) { + slow = slow.next; // Move slow pointer one step + fast = fast.next.next; // Move fast pointer two steps + + if (slow == fast) { + return true; // Cycle detected if slow and fast pointers meet + } + } + + return false; // No cycle found + } + + public static void main(String[] args) { + // Create a linked list with a cycle + ListNode head = new ListNode(1); + ListNode node2 = new ListNode(2); + ListNode node3 = new ListNode(3); + ListNode node4 = new ListNode(4); + ListNode node5 = new ListNode(5); + + head.next = node2; + node2.next = node3; + node3.next = node4; + node4.next = node5; + node5.next = node2; // Cycle: node5 points back to node2 + + System.out.println("Does the linked list have a cycle? " + hasCycle(head)); + } + } +``` + +#### Kadane's Algorithm + +```java +public class KadanesAlgorithm { + public static int maxSubArraySum(int[] nums) { + int maxSum = nums[0]; // Initialize maxSum with the first element of the array + int currentSum = nums[0]; // Initialize currentSum with the first element of the array + + for (int i = 1; i < nums.length; i++) { + /** + Calc the currentSum for the current element by taking + the maximum of the current element itself or the sum + of the current element and the previous subarray sum + **/ + currentSum = Math.max(nums[i], currentSum + nums[i]); + + /**Update the maxSum with the maximum of the currentSum and the previous maxSum + * + * + **/ + maxSum = Math.max(maxSum, currentSum); + } + + return maxSum; // Return the maximum subarray sum + } + + public static void main(String[] args) { + int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; + int maxSum = maxSubArraySum(nums); + System.out.println("Maximum subarray sum: " + maxSum); + } +} +``` \ No newline at end of file diff --git a/MustKnow/Design Pat/README.md b/MustKnow/Design Pat/README.md new file mode 100644 index 0000000..d570b02 --- /dev/null +++ b/MustKnow/Design Pat/README.md @@ -0,0 +1,8 @@ +### Design Patterns + + +#### Adapter Design Pattern +- Convert An Interface of A Class into Another Interface that clients expect +- Enables us to make incompatible classes work with one another +- i.e. delegate logic to the Adapter +- ![example](https://www.baeldung.com/wp-content/uploads/2019/02/Adapter.png) \ No newline at end of file diff --git a/MustKnow/GCDeuclid/README.md b/MustKnow/GCDeuclid/README.md new file mode 100644 index 0000000..1f940c5 --- /dev/null +++ b/MustKnow/GCDeuclid/README.md @@ -0,0 +1,25 @@ +```java +public class GCDeuclid{ + public static void logLn(Object o){ + System.out.println(o); + } + + public static void main(String [] args){ + logLn(euclidgcd(1800,54)); + } + + public static int euclidgcd(int divid, int divis){ + //2526 56837 35 + /* + * if divisor i.e. divis completely divid i.e. dividend + * remain=0 i.e. therefore divis is the gcd + * */ + int remain = divid%divis; + if(remain==0){ + return divis; + } + + return euclidgcd(divis,remain); + } +} +``` \ No newline at end of file diff --git a/MustKnow/Graphs/README.md b/MustKnow/Graphs/README.md new file mode 100644 index 0000000..21f602f --- /dev/null +++ b/MustKnow/Graphs/README.md @@ -0,0 +1,35 @@ +### Graphs Implementation + + +
+ +##### DFS +```java +import java.util.*; +class Main{ + public final int depthfirsts(int node, int result){ + /*PRE ORDER + * + * result.push(node,value); + * */ + + if(node.left) { + depthfirsts(node.left, result); + } + + + result.push(node,value); + + + if(node.right){ + depthfirsts(node.right); + } + + /*POST ORDER + * + * result.push(node,value); + * */ + return result; + } +} +``` \ No newline at end of file diff --git a/MustKnow/Main.java b/MustKnow/Main.java deleted file mode 100644 index 8b15607..0000000 --- a/MustKnow/Main.java +++ /dev/null @@ -1,30 +0,0 @@ -public class Main{ - - public void logLn(Object o){ - System.out.println(o); - } - - public void log(Object o){ - System.out.print(o); - } - - public void printArr(int [] arr){ - logLn(arr[0]); //has one operation and takes constant time to run ===> O(1) - logLn(arr[0]); //has two operation but still O(1) - } - - /* - small small will run fast but as the sample size increase e.g. 1,000,000 items then you will have it running slowly - - cost of algo: linear and is directly proportional to the size of the input therefore the runtime complexity O(n) - */ - public void logging(int [] nums){ - for(int i=0; i Docker; + Docker -- CI/CD Tools --> Gitlab; + Gitlab -- VCS --> GitHub/BitBucket; + GitHub/BitBucket -- Frameworks --> Express/Flask/Laravel/RubyOnRails; + Express/Flask/Laravel/RubyOnRails -- Prog_Lang --> Java/Python/Ruby/C#/NodeJS/Rust/PHP; + Java/Python/Ruby/C#/NodeJS/Rust/PHP -- Archi Pattern --> Microservices/Monolithic/Serverless/SOA; + Microservices/Monolithic/Serverless/SOA -- APIs --> REST/JSON/SOAP; + REST/JSON/SOAP -- Caching--> Client/Server/CDN; + Client/Server/CDN -- Testing --> + Integration/Unit/Functional; + Integration/Unit/Functional -- Database -- SQL --> MYSQL/Postgres; + Integration/Unit/Functional -- Database -- NoSQL --> MongoDB; + MongoDB --> START/FINISH + MYSQL/Postgres --> START/FINISH + +``` + + +##### Things You Must Know To Understand Java +- Abstract +- Arrays And ArrayList +- Collections +- Conditionals +- Default +- Enum +- Exception Handling +- Final Keyword +- Generics +- Interfaces +- Loops +- Maps +- OOP(Abstraction, Encapsulation, Inheritance, Polymorphism) +- Passing By Value Vs. Passing By Reference +- Reference Types Vs Primitive Types +- Sets +- Static +- ToString & Equals & Hashcode + +
+ +##### ★★★★Operations You Can Perform On A Data Structure★★★★ - Delete: Remove an item from the data structure @@ -34,6 +83,8 @@ - Used in the Average Case + + ##### DS Operations - Traverse: Visiting each item in the DS once AND ONLY ONCE @@ -45,14 +96,30 @@ -1. Stack +1. **Stack** - Linear - LIFO/FILO - Dinner Plates - When items are pushed they are placed on the top +- Only can push/pop an element from this DS at one end only +- Requires You To Have One Reference Pointer i.e. "TOP" +- Applications: + - Redoing/Undoing stuff within your application + - Memory Management +- Allows you to fully control how memory is allocated and deallocated +- Pitfalls of Stack: + - Cannot access a random element + - Not able to be scaled i.e. not flexible -2. Linked List +```java +import java.util.*; + +Stack myStack= new Stack(); +``` + + +2. **Linked List** - Sequential Order - No Random Access @@ -62,26 +129,114 @@ - A Node is composed of data and a pointer - Last node has a null pointer i.e. the pointer is used but doesn't point to anything - Folders on your computer(i.e. last folder is null because it has no folder within it) +- Node[0] = Head +- Node[n-1] = Tail + + +```java +import java.util.*; +/* +How To Declare: +LinkedListnameOfLL = new LinkedList() */ +LinkedList mylist=new LinkedList(); +``` -3. Array +3. **Array** - Indexed - When Size increases performance decreases - All the elements in the DS must be of the same type - Muffin/Egg Tray - Rectangular in shape +- Good For Storing Multiple items in it +- Address in Memory increases by the size of the datatype you store +- I.e. say I have 6 ints location in memory of the first is 104 second is 108 third is 112 +- because an int = 4 bytes that's why you increment by 4 +- Searching an Array by index is super fast, supply to an idx to the array and it will be super fast to locate it +- Calc of Mem Address Runtime is: O(1) +- Downsides: Static, failure to know size if too large: waste memory too small: array gets filled quickly +- And If I fill it up quickly I must create a 2nd array and copy the elements of the first array into the second + +- Cost of Lookup: O(1) +- Cost of Insertion: O(n) +- Cost Of Removal: O(n) + +1. Best Case: I remove from the end of the array and I delete that index +2. Worst Case: I remove from the beginning of the array and shift all the items in the right one index less to fill +3. Therefore, for the worst case it is O(n) when removing an item in the array + + +- Dynamic Array DS in Java: ArrayList +- Grows by 50% of its size everytime I add sth to it +- synchronous aka one 7652626 thread at a time + +#### Declaring an array in Java +```java +import java.util.*; +public class Arr{ + public static void main(String [] args){ + /* + 1. declare the data type of the array + 2. indicate that I want an array data structure by using the brackets.. MUST BE EMPtY + 3. give it a name + 4. use the new operator to allocate memory for the array + 5. repeat the data type of the array + 6. indicate the size of the array + + */ + int [] myArr = new int[7]; + //this output the memory location of the array + //System.out.println(myArr); + + /* + if you know the vals: + + */ + int [] myArrTw = {7, 6, 5, 2, 6, 2, 6} + + //proper way to output + System.out.println(Arrays.toString(myArr)) + } +} +``` -4. Queues +4. **Vector** : Grows by 100% of its size everytime I add sth to it... asynchronous aka multiple threads at a time -- Movie Theatre + +5. **Queues** + +- People waiting in line in the Movie Theatre +- Linear - FIFO -- aka people waiting in line +- Has Side A and Side B +- Pushes On Side A i.e. Enqueue +- Pops On Side B i.e. Dequeue - Ordered Collection - Operations: add(), remove() - +- Part of the java.util.* package +- Part of the collection Interface +- Two Classes Implement the Queue Interface: + - Linked List + - Priority Queue +- Supports all the methods in the Collection Interface +- Element & Remove Method Throws NoSuchElementException if the queue is empty +- Poll Method removes the head of the queue and returns it + - if the queue is empty the poll method call returns null +- Requires You To Have Two Reference Pointers i.e. "FRONT" & "REAR" + +```java +//How To Declare a Priority Queue of type String +import java.util.*; + +public class queueimpl{ + public static void main(String [] args){ + Queue mypq = new PriorityQueue<>(); + } +} +``` -5. Hash Table +6. **Hash Table** - Contains an index and its corresponding Hash_Value @@ -89,17 +244,52 @@ - Cannot store null as a key nor as a value - First parameter within your Hash Table declaration is the data type of the key - Second parameter within your Hash Table declaration is the data type of the value +- Restaurant Pager i.e. you give your name and they assign a number to you when a seat frees up you get an empty table + +```java +/* +How To Declare a Hash Table of type: +- Integer for the key +- String for the value +*/ + +import java.util.*; + +public class HashTable{ + public static void main(String [] args){ + Integer mystr; + Hashtable myhashtable = new Hashtable(); + myhashtable.put(1,"Blue"); + myhashtable.put(2,"Red"); + myhashtable.put(3,"Yellow"); -6. Trees + //Storage of the keys in the HashTable Set + Set keys = myhashtable.keySet(); + + Iterator itr = keys.iterator(); + + + while (itr.hasNext()) { + // Getting Key + mystr = itr.next(); + System.out.println("Key: "+mystr+"\nValue: "+myhashtable.get(mystr)); + } + } +} + +``` + +7.**Trees** - Hierarchical Structure where data is org in a hierarchy and everything is linked together - Not the same as linked list because LL is linear +- Log(n) runtime complexity where n is the number of levels - Trees are faster to access than a LL because they are non-linear - Node: person who holds our data - Child Node: person who has a parent -- Leaf Node: person who has no children +- Leaf: person who has no children - Edge: person who connects two nodes -- Root: Person who is the topmost node +- Root: person who is the topmost node - Node Height: # of edges from the node to the deepest leaf node - Node Depth: # of edges from the root to the node - Tree Height: Depth of the deepest node @@ -107,74 +297,340 @@ - Leaves: Person who has no children - Use when you want to store items in a hierarchial fashion - Quicker to access/search than a LL but slower than an Array - - Binary Tree + - AVL Tree: + - Self-balanced trees + - Searching, Inserting, Deleting in the worst case is logarithmic time complexity + - Balance factor is determined by the height of the right subtree tree + - ... minus the height of the left subtree + - I have a height of 1 in the left subtree ... I have a height of 1 in the right subtree + - balance factor = 0 + - Objective: make sure every node is balanced i.e. bf = -1,0,1 + - all nodes must be balanced ... if one node is not balanced the whole tree is unbalanced + - balance factor in relation to its neighboring subtree + - -1 means the right subtree is greater than the left subtree + - 1 means the left subtree is greater than the right subtree + - 0 means the left subtree and right subtree have equal lengths + - LL rotation means I inserted a node in the left subtree of the left subtree of A + - LR rotation means I inserted a node in the right subtree of the left subtree of A + - RR rotation means I inserted a node in the right subtree of the right subtree of A + - RL rotation means I inserted a node in the left subtree of the right subtree of A + - Binary Tree - Can Have 0,1,2 nodes + - right child is always larger & left child is always smaller - Binary Search Tree: - Used for sorting, getting and searching data - Non-linear - Arranged in some order - no duplicate vals - val on the left most subtree of the node is always smaller than the val on its immediate right + - B-tree + - every b-tree has an order i.e. the number of levels + - Root node must have a minimum of two children + - A leaf in a b-tree the i.e. the parent to the last level in a b-tree(i.e. child nodes) + - ...must always have more nodes than the child so as the keys(1 key... 2 child nodes, 2 keys, 3 child nodes) + - the keys cannot be larger than the leaf nodes + - All leaf nodes must be at the same level + - whenever you delete a leaf node all you have to do is do a rotation to the values + - if you delete a middle value you must do rebalancing + - whenever one of the rules is violated, I have to rebalance and restructure my tree + - ... by shifting the center value + - once you access one element in the block you have access to all the elements in the block + - B*-tree + - Values in the middle are not essentially referred to as value + - they are just navigation values(go left, go down, go right) + - the parent is always the largest value of its left child subtree + - the number of values I am allowed to store at the leaf level is determined by a parameter k* + - so if k* = 2 that means I am allowed to have a max of 2k* elements at the leaf level + - ...and a minimum of 2 + - m is the order of the tree i.e. the number of the levels + - B* trees have a smaller height than Btrees because all the data is stored in the leaf level - Node on the left is always less than the node on the right +- Linux File Structure +- Classification Tree in Biology + +- Runtime of Operations Performed on A Balanced Tree + +| Operation | Runtime | +| ----------- | ----------- | +| Inserting | log(n) | +| Deleting | log(n) | +| Rebalancing | log(n) | +| Searching | log(n) | +#### 4 Cases of AVL Trees of Balance Factors + +- We will never have to make more rotations than the number of levels +- Number of level is log2(n) + +##### Case A +``` + A(-2) + / \ + B(-1) C(0) height of 3 vs height of 1 + / \ ∴ BF=-2 + D(-1) E(0) + / +F(0) +``` + +- Balance Factor of: -2 +- The left most subtree has a height that is 2 levels greater than the right subtree +- Perform a single right rotation + +``` + B(0) + / \ + D(0) A(0) + / / \ + F(0) E(0) C(0) + +``` +
+
+ + +##### Case B +``` + A(-2) + / \ + B(1) C(0) + / \ +D(0) E(1) + \ + F(0) +``` +
+
+ +- Perform a single left rotation on the subtree +- Make E the root node of the left subtree +- Make B the left child node of E +- Make F the right child node of E +``` + A(-2) + / \ + E C(0) + / \ + B F + / + D +``` + + + + +##### Case C + +``` + A(-2) + / \ + B(1) C(0) + / \ + D(0) E(1) + \ + F(0) +``` + +- Perform a single left rotation +- Make A the root node of the left subtree +- Make E the root node of the right subtree +- Make F the child node of E +- Make B the left child node of A +- Make D the right child node of A + +``` + C(0) + / \ + A(0) E(1) + / \ \ +B(0) D(0) F(0) + +``` + + + + +##### Case D + +``` + A + / \ + B C + / \ + D E + / + F +``` + +1. Perform a single right rotation now we are in Case C +2. That means To Solve Case D I perform a double right-left rotation + +``` + A + / \ + B D + / \ + F C + \ + E +``` + + + + + -7. Heap +8. **Heap** - Special Tree Based DS - Binary Tree -- Patients Being Admitted to the Hospital - - Patients with life-threatning situation get taken care of first - - Patients that don't have threatening situation wait in line - Parent node makes a comparison with its child nodes and are arranged accordingly - Two Scenarios: - Key present at the root node is the greatest among all of its children and successors - Key present at the root node is the smallest among all of its children and successors +- Patients Being Admitted to the Hospital + - Patients with life-threatning situation get taken care of first + - Patients that don't have threatening situation wait in line -8. Graphs + +9. **Graphs** - Finite set of vertices, nodes and edges. The edges are what connect one vertex with another - Graphs are connected in a network form +- Vertex: Circle +- Edge: Arrow - Non-linear - Nodes are the vertices(i.e. endpoints) - Edges are the lines/arcs that connect one node with another node -- Two Types: - - Directed - - Undirected +- Types: + - **Directed**: no particular direction and two-way relation + - e.g. Friends on Facebook + - **Undirected**: Particular Direction and one-way relation + - e.g. who you're following on Twitter + - **Unweighted**: Every edge has no particular weight + - **Weighted**: Each edge has a respective value this is referred to as weight + - e.g. distance between cities +- **Note** A (directed/undirected )graph is independent of being weighted or not +- We can have: + - Direct Weighted Graphs + - Direct Unweighted Graphs + - Undirected Weighted Graphs + - Undirected Unweighted Graphs +## Important Algorithms +- Graph Algorithms: + - BFS + - DFS + - Dijkstra(Shortest Path) - Simple Graph: Each edge connects to two different vertices whereby no two edges connect to the same group of vertices -- Multigraph: An edge can connect to the same pair of vertices -- +- Multi-graph: An edge can connect to the same pair of vertices +- Google Maps Usage of Connecting Roads i.e. vertex therefore, I use an algo to determine the shortest path between vertex A & B -9. Queues +```java +//basic example -- FIFO DS -- Linear -- Pushes To The End -- Pops From The Front -- Part of the java.util.* package -- Part of the collection Interface -- Two Classes Implement the Queue Interface: - - Linked List - - Priority Queue -- Supports all the methods in the Collection Interface -- Element & Remove Method Throws NoSuchElementException if the queue is empty -- Poll Method removes the head of the queue and returns it - - if the queue is empty the poll method call returns null +import java.util.*; +class Graph { + private int V; // Number of vertices + private LinkedList[] adjList; // Array of adjacency lists + + // Constructor + public Graph(int V) { + this.V = V; + adjList = new LinkedList[V]; + + for (int i = 0; i < V; i++) { + adjList[i] = new LinkedList(); + } + } + + // Add an edge to the graph + public void addEdge(int src, int dest) { + adjList[src].add(dest); + adjList[dest].add(src); // Uncomment this line for undirected graph + } + + // Print the graph + public void printGraph() { + for (int i = 0; i < V; i++) { + System.out.print("Vertex " + i + " is connected to: "); + for (int neighbor : adjList[i]) { + System.out.print(neighbor + " "); + } + System.out.println(); + } + } +} -1. When the sample size increases of an Array what should you do? +public class Main { + public static void main(String[] args) { + // Create a graph with 5 vertices + Graph graph = new Graph(5); + + // Add edges + graph.addEdge(0, 1); + graph.addEdge(0, 4); + graph.addEdge(1, 2); + graph.addEdge(1, 3); + graph.addEdge(1, 4); + graph.addEdge(2, 3); + graph.addEdge(3, 4); + + // Print the graph + graph.printGraph(); + } +} + +``` + + +### Sorting +- Bubble Sort +- Bucket/Insertion Sort + - Runtime: O(n^2) ... ie terrible + - useful when paired with other more complex sorting algo + - i.e. Quicksort, Merge Sort + - good for ordering a small sample size + - Step 1: iterate from the 2nd array to the nth array over the array + - Step 2: compare the element which you are at with its parent/predecessor + - Step 3: if the key is less than its predecessor compare it to the preceding elements + - Step 4: Move the greater element up one spot to give space for the modified element +- Counting Sort +- Heap Sort +- Merge Sort +- Quick Sort +- Selection Sort + + + +
+ +## Search Algorithms + +1. Breath First Search[Graphs] +2. Depth First Search[Graphs] +3. Binary Search[Linear] +4. Linear Search + +**Other** +- Recursive Algorithms +- Hashing Algorithms +- Randomized Algorithms -- Use A Linked List DS because it increases performance and isn't slow as the sample size increases + + +1. When the sample size increases of an Array what should you do? + - Use A Linked List DS because it increases performance and isn't slow as the sample size increases 2. For Loop Runtime: O(n) where n is the size of the input 3. Function with 1 operation: O(1) 4. Say I have a print statement before a for loop and after what's the runtime: - -- Print statement: O(1) -- For Loop: O(n) -- Print statement: O(1) + - Print statement: O(1) + - For Loop: O(n) + - Print statement: O(1) Total: O(1+n+1)= O(n+2) @@ -213,6 +669,78 @@ But actually the runtime is O(n) because when we calculate runtime we drop the c - In the worst case scenario, if the number I am looking for is at the end of the array then I have to inspect one index at a time - The more items I have the longer the operation will take +```java +import java.util.*; + +public class LinSearch{ + + public static void main(String [] args){ + int [] myArr = {18, 34, 65, 92, 32, 94, 15, 10, 16, 8, 26}; + int elem,elemExistsTimes=0; + Scanner sc = new Scanner(System.in); + System.out.println("Enter The Element You Are Hunting For: "); + elem = sc.nextInt(); + + for(int x = 0; x<10; x++){ + if(myArr[x] == elem){ + elemExistsTimes= x + 1; + break; + } + + else{ + elemExistsTimes = 0; + } + } + + if(elemExistsTimes != 0) + { + System.out.println("I found the item at location: "+elemExistsTimes); + } + + else{ + System.out.println("Not Found Man"); + } + + } + +} +``` + +```java +public class Main{ + + public void logLn(Object o){ + System.out.println(o); + } + + public void log(Object o){ + System.out.print(o); + } + + public void printArr(int [] arr){ + logLn(arr[0]); //has one operation and takes constant time to run ===> O(1) + logLn(arr[0]); //has two operation but still O(1) + } + + /* + small small will run fast but as the sample size increase e.g. 1,000,000 items then you will have it running slowly + + cost of algo: linear and is directly proportional to the size of the input therefore the runtime complexity O(n) + */ + public void logging(int [] nums){ + for(int i=0; i; -//where E is the generic key type -//Integer keyword is the wrapper class around the native/primitive type int -``` -2. Vector: Grows by 100% of its size everytime I add sth to it... asynchronous aka multiple threads at a time - - -### LinkedList - -- We use a LL when wanting to store an object in sequential||7652626 order -- LinkedList are better than arrays because they can grow/shrink auto -- It consists of a group of nodes in seq order. Every node has two pieces of data: - 1. value - 2. address of the next node in the list -- AKA every node (points to)/references the next node in the list -- Node[0] = Head -- Node[n-1] = Tail - -#### Searching A LL value Time C - -- O(n) because the val we are searching for maybe stored in the last node aka n that is worst case. +/* + + 1. Compare the first two elements if the first is + bigger than the second swap + + 2. compare the rest and if the second is less than + the first move the second to the left of the first + + */ + + +public class BubbleSort{ + + public static void bubbleSort(int [] arr){ + int arrsize = arr.length; + for(int s=0;sarr[t+1]){ + int temporary = arr[t]; + arr[t]=arr[t+1]; + arr[t+1]= temporary; + } + } + } + } + public static void main(String [] args){ + int myarr[] ={3,60,35,2,45,320,5}; + System.out.println("Before Bubble Sort"); + for(int x=0; x -- O(n) because the val we are searching for maybe stored in the last node aka n that is worst case. #### Insertion Sort Implementation @@ -378,6 +887,182 @@ Space C: O(1) because I am adding a var */ ``` +
+ +#### Merge Sort Implementation + +```java +public class MergeSort +{ + // Merges two subarrays of arr[]. + // First subarray is arr[left half..middle index] + // Second subarray is arr[middle+1..right half] + void merge(int arr[], int l, int m, int r) + { + // Find sizes of two subarrays to be merged + int n1 = m - l + 1; + int n2 = r - m; + + /* Creating two temporary arrays */ + int L[] = new int [n1]; + int R[] = new int [n2]; + + /* + Copy the + info into + temporary arrays + */ + for (int i=0; i + + +#### Selection Sort Implementation + +```java +import java.util.*; + +public class Selectionso { + public static void Selectionso(int myArr[]) + { + /* + 0. take an unsorted num of elements within an array + 1. find the minimum and place it on its own + 2. find the second min and place it after the min in the other array + 3. repeat till you have one left(i.e. largest) and place it at the end of the array + */ + int arr_size = myArr.length; + for(int x=0;x + + #### Insertions at the End in a LL index Time C @@ -451,23 +1136,9 @@ O(n) - compare using .compareTo() method -### Important Algo - -#### Sorting -1. Merge Sort -2. Quick Sort -3. Bucket/Insertion Sort -4. Heap Sort -5. Selection Sort -6. Counting Sort -#### Searching - -1. Breath First Search[Graphs] -2. Depth First Search[Graphs] -3. Binary Search[Linear] #### Divide & Conquer @@ -492,4 +1163,4 @@ public class myclass{ //Total: O(1) + O(n) + O(n^2) ≈ O(n^2) } } -``` \ No newline at end of file +``` diff --git a/README.md b/README.md index 04e7a6a..6e9f0c8 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,11 @@ 6. UI: How We Present the data +### == vs .equals() + +- ==: compares content and reference +- .equals(): compares just the content + ## Class Naming is Pascal Case The case name is = to 2526 fav programming language and fav screen color: ```java class PascalCase{} @@ -26,9 +31,9 @@ ## Method Naming is Camel Case: ```java public void theBestMethod() -{ - logln("2526: 727225, 27736259, 27429, 27375, 746867 ARE THE BEST THINGS EVER and 557 AKA LLP Prog is also my fav!!!"); -} + { + logln("2526: 727225, 27736259, 27429, 27375, 746867 ARE THE BEST THINGS EVER and 557 AKA LLP Prog is also my fav!!!"); + } ``` ## Data Structures @@ -36,18 +41,19 @@ public void theBestMethod() #### Primitive DS: 1. Integer 2. Float -3. Char` +3. Char 4. Pointers + #### Non-Primitive DS: 1. Arrays 2. List - - Linear: - - Stacks - - Queues - - Non-Linear: - - Graphs - - Trees + - Linear: + - Stacks + - Queues + - Non-Linear: + - Graphs + - Trees @@ -71,16 +77,16 @@ $~ java callingProgram.java MethodProgram.java ## What is the "this" keyword in Java and why do we use it ```java class NelanLvsBDAndCSunAndFTN{ - int cobolfb = 2626532; - int pascalfb= 72722532; - - public void setVals(int cobolfb, int pascalfb){ + int cobolfb = 2626532; + int pascalfb= 72722532; + + public void setVals(int cobolfb, int pascalfb){ /*here is where the this keyword comes to play to tell java that I want to use the parameter of my function aka local variables and not the instance variables(up top) */ - this.cobolfb = cobolfb; - this.pascalfb = pascalfb; - } + this.cobolfb = cobolfb; + this.pascalfb = pascalfb; + } } ``` @@ -92,14 +98,14 @@ class NelanLvsBDAndCSunAndFTN{ Raised when you try to call an undeclared variable ```java public class Omar{ - public static void main(String [] args) - { - int a = 1; - int b= 2; - int c= 3; - mean = (a+b+c)/2; - System.out.println(mean); - } + public static void main(String [] args) + { + int a = 1; + int b= 2; + int c= 3; + mean = (a+b+c)/2; + System.out.println(mean); + } } ``` @@ -107,30 +113,30 @@ In line 8 we try to print to the console mean we have set the value of mean but To solve we do this ```java public class Omar{ - public static void main(String [] args) - { - int a = 1; - int b= 2; - int c= 3; - double mean = (a+b+c)/2; - System.out.println(mean); - } + public static void main(String [] args) + { + int a = 1; + int b= 2; + int c= 3; + double mean = (a+b+c)/2; + System.out.println(mean); + } } ``` ### 2- cannot find symbol PART 2 Raised when you try to call an undeclared variable ```java public class Great{ - public static void main(String [] args) - { - the_best_method; - } - - public static void the_best_method() - { + public static void main(String [] args) + { + the_best_method; + } + + public static void the_best_method() + { System.out.println("This is the best method in the world"); - } - + } + } ``` @@ -138,41 +144,41 @@ In line 4 we are incorrectly calling the_best_method but we forget the parenthes ```java public class Great{ - public static void main(String [] args) - { - the_best_method(); - } - - public static void the_best_method() - { + public static void main(String [] args) + { + the_best_method(); + } + + public static void the_best_method() + { System.out.println("This is the best method in the world"); - } - + } + } ``` -### 3- cannot find symbol : -### symbol: class Scanner +### 3- cannot find symbol : +### symbol: class Scanner ### location: class Great Raised when you are using the scanner ```java public class Great{ - public static void main(String [] args) - { - Scanner useInput= new Scanner(); // scanner is not imported - int l = useInput.nextInt(); - } + public static void main(String [] args) + { + Scanner useInput= new Scanner(); // scanner is not imported + int l = useInput.nextInt(); + } } ``` -In line 4 we are using the scanner but we never imported the library that enables us to use it +In line 4 we are using the scanner but we never imported the library that enables us to use it ```java import java.util.Scanner; public class Great{ - public static void main(String [] args) - { - Scanner useInput= new Scanner(); // scanner has no default constructor - int l = useInput.nextInt(); - } + public static void main(String [] args) + { + Scanner useInput= new Scanner(); // scanner has no default constructor + int l = useInput.nextInt(); + } } ``` @@ -181,10 +187,10 @@ public class Great{ ```java public class Thebest -{ - public static void main(String[] args) { - System.out.println("Hello, world!"); - } +{ + public static void main(String[] args) { + System.out.println("Hello, world!"); + } } ``` ## SOOO, I save the file and I name it Lemon.java well, it will error because our class is Thebest so that means our file name should be Thebest.java @@ -195,22 +201,22 @@ This error is raised when I try to write code outside of a method which is unint ```java public class Test { System.out.println("Hello!"); - - public static void main(String[] args) { - System.out.println("World!"); - } - } + + public static void main(String[] args) { + System.out.println("World!"); + } +} ``` - + To fix I just place the print Statement of hello inside of main ```java - public class Test { - public static void main(String[] args) { - System.out.println("Hello!"); - System.out.println("World!"); - } - } + public class Test { + public static void main(String[] args) { + System.out.println("Hello!"); + System.out.println("World!"); + } +} ``` ### 6- illegal start of expression @@ -218,29 +224,29 @@ To fix I just place the print Statement of hello inside of main An "illegal start of expression" error occurs when the compiler when we start a expression before closing the previous one. ```java public class Test { - public static void main(String[] args) { - my_method(); - - - public static void my_method() { - System.out.println("Hello, world!"); - } - } + public static void main(String[] args) { + my_method(); + + + public static void my_method() { + System.out.println("Hello, world!"); + } + } ``` To fix this piece of code, I simply add a closing curly brace for the main method. To know we are doing the right thing, just look at the lines of code before the error, there may be a missing closing paranthesis or a missing closing curly brace. This would give us what the error is. ```java public class Test { - public static void main(String[] args) - { - my_method(); - } - - public static void my_method() - { - System.out.println("Hello, EVERYONEEEE!"); - } + public static void main(String[] args) + { + my_method(); + } + + public static void my_method() + { + System.out.println("Hello, EVERYONEEEE!"); + } } ``` @@ -248,12 +254,12 @@ public class Test The incompatible types error is raised when we are facing with data type errors. We can overcome this, by converting say a char to an int. We can convert a double to an integer with typecasting. BUt WE CANNOT convert between primitive types and objects. A primitive type is say a: null, undefined, boolean, number, string or char. However objects can be: Arrays, Maps, Sets, Functions, Regular Expression or Date.. ```java -public class Test +public class Test { - public static void main(String[] args) - { - int num = "Hello, world!"; - } + public static void main(String[] args) + { + int num = "Hello, world!"; + } } ``` The above code is an error because we are assigning the string Hello World to the variable num of type int. @@ -262,24 +268,24 @@ Step 1: Change the String value from Hello, world! to 500 ```java public class Test { - public static void main(String[] args) - { - int num = "500"; - } + public static void main(String[] args) + { + int num = "500"; + } } ``` - + Step 2: Use parsing to convert the string to an integer ```java public class Test { - public static void main(String[] args) - { - int num = Integer.parseInt("500"); - } + public static void main(String[] args) + { + int num = Integer.parseInt("500"); + } } ``` - + ### 8- invalid method declaration; return type required @@ -289,16 +295,16 @@ When a method declaration does not contain a return type, this error will occur: ```java public class Test { - public static void main(String[] args) - { - int x = getValue(); - System.out.println(x); - } - - public static getValue() - { - return 10; - } + public static void main(String[] args) + { + int x = getValue(); + System.out.println(x); + } + + public static getValue() + { + return 10; + } } @@ -307,48 +313,48 @@ To fix this, simply insert the appropriate return type in the method signature a ```java -public class Test +public class Test { - public static void main(String[] args) - { - int x = getValue(); - System.out.println(x); - } - - public static int getValue() - { - return 10; - } + public static void main(String[] args) + { + int x = getValue(); + System.out.println(x); + } + + public static int getValue() + { + return 10; + } } ``` ### 9-java.lang.ArrayIndexOutOfBoundsException: -An ArrayIndexOutOfBoundsException is thrown when an attempt is made to access an index in an array that is not valid. This means that say an array has 8 elements and we know that the number of elements in index is 7. We start counting at 0. So, if I enter a value of 8 or greater to access, this will raise an error. +An ArrayIndexOutOfBoundsException is thrown when an attempt is made to access an index in an array that is not valid. This means that say an array has 8 elements and we know that the number of elements in index is 7. We start counting at 0. So, if I enter a value of 8 or greater to access, this will raise an error. ```java public class Test { - public static void main(String[] args) { - int[] arr = {1, 2, 3}; - for (int i = 0; i <= arr.length; i++) { - System.out.println(arr[i]); - } - } - } + public static void main(String[] args) { + int[] arr = {1, 2, 3}; + for (int i = 0; i <= arr.length; i++) { + System.out.println(arr[i]); + } + } +} ``` The code above errored due to the for loop iteration settings. The first element is index 0 which is fine however, the function's output of arr.length of our array named arr of type int is 3. However, we are using the comparison operator of <=. This means less than or equal to. If, we change it to < it will not error. The equal means it will try to access index 3 which is the 4th item in the array which we do not have. ```java public class Test { - public static void main(String[] args) { - int[] arr = {1, 2, 3}; - for (int i = 0; i < arr.length; i++) { - System.out.println(arr[i]); - } - } + public static void main(String[] args) { + int[] arr = {1, 2, 3}; + for (int i = 0; i < arr.length; i++) { + System.out.println(arr[i]); + } + } } ``` -### 10- StringIndexOutOfBoundsException -The exception StringIndexOutOfBoundsException is thrown to the console when an attempt is made to access an index in +### 10- StringIndexOutOfBoundsException +The exception StringIndexOutOfBoundsException is thrown to the console when an attempt is made to access an index in the String that is not valid. The only valid index of the String we can access is from 0 to the (length of the String-1). This means that if the array 8 elements. The biggest number I can access is 7 not 8. If we enter any number greater than 7 for access will throws an outofBoundsException. This is an error in runtime not compile-time. It is accepted by the compiler because it is a logical error ``` java @@ -370,16 +376,16 @@ To fix this I simply change the String a declaration in line 7 from index -1 to Therefore the bottom code is bug free ```java -public class Test +public class Test { - public static void main(String[] args) - { - String str = "Hello, world!"; + public static void main(String[] args) + { + String str = "Hello, world!"; - String a = str.substring(1, 3); - char b = str.charAt((str.length())-1); - String c = str.substring(0, 6); - } + String a = str.substring(1, 3); + char b = str.charAt((str.length())-1); + String c = str.substring(0, 6); + } } ``` @@ -401,178 +407,178 @@ public class Test This errors because I have called the methods with the specified data types in the wrong order. I must call it in the right order ```java -public class Omar -{ - public static void main(String[] args) { - omarMethod(1.0,"YOLO!", 2); - } - - public static void omarMethod(double a, String b, int c) { - System.out.println(a + " " + b + " " + c); - } +public class Omar +{ + public static void main(String[] args) { + omarMethod(1.0,"YOLO!", 2); + } + + public static void omarMethod(double a, String b, int c) { + System.out.println(a + " " + b + " " + c); + } } ``` ### 12- Left out return statement ```java - public class Omar + public class Omar { - public static void main(String[] args) - { - int x = doubleMyNum(5); - System.out.println(x); - } + public static void main(String[] args) + { + int x = doubleMyNum(5); + System.out.println(x); + } - public static int doubleMyNum(int m) - { - int value = 2 * m; - } - } + public static int doubleMyNum(int m) + { + int value = 2 * m; + } +} ``` -The above code errors because I have made the function behave like a void but my 3rd keyword indicates my return type should +The above code errors because I have made the function behave like a void but my 3rd keyword indicates my return type should be of type int. To fix this, after storing the computation in a variable. I use the return keyword to return to the console. The output of the computation performed by the method. ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int x = doubleMyNum(5); - System.out.println(x); - } + public static void main(String[] args) + { + int x = doubleMyNum(5); + System.out.println(x); + } - public static int doubleMyNum(int m) - { - int value = 2 * m; - return value; - } - } + public static int doubleMyNum(int m) + { + int value = 2 * m; + return value; + } +} ``` ### - Left out return statement in CASE#2 ```java - public class Omar + public class Omar { - public static void main(String[] args) - { - int x = myAwesomeAbsVal(-5); - System.out.println(x); - } - - public static int myAwesomeAbsVal(int m) - { - if(m<0) - { - return -m; - } + public static void main(String[] args) + { + int x = myAwesomeAbsVal(-5); + System.out.println(x); + } - if(m>0) - { - return m; - } - } - } + public static int myAwesomeAbsVal(int m) + { + if(m<0) + { + return -m; + } + + if(m>0) + { + return m; + } + } +} ``` The above lines of code have an error in logic. We should switch the code to this: ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int x = myAwesomeAbsVal(-5); - System.out.println(x); - } - - public static int myAwesomeAbsVal(int m) - { - if(m<0) - { - return -m; - } + public static void main(String[] args) + { + int x = myAwesomeAbsVal(-5); + System.out.println(x); + } - else - { - return m; - } - } + public static int myAwesomeAbsVal(int m) + { + if(m<0) + { + return -m; + } + + else + { + return m; + } + } } ``` ### 13 - possible loss of precision ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int theAwesomePi = 3.14159; - System.out.println("The value of pi is: " + theAwesomePi); - } - } + public static void main(String[] args) + { + int theAwesomePi = 3.14159; + System.out.println("The value of pi is: " + theAwesomePi); + } +} ``` There is an error above being raised being we are store double in an integer. An integer can only store 4 4 bytes in main memory. The value we are storing in it is a double which has a memory size of 8 bytes. The way to solve this issue. We will explictly cast the variable theAwesomePi to an int. ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int theAwesomePi = (int)3.14159; - System.out.println("The value of pi is: " + theAwesomePi); - } - } + public static void main(String[] args) + { + int theAwesomePi = (int)3.14159; + System.out.println("The value of pi is: " + theAwesomePi); + } +} ``` ### 14 - Reached end of file while parsing ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - myWonderfulMethod(); - } - - public static void myWonderfulMethod() - { - System.out.println("How Awesome do you think my Method is?"); - } + public static void main(String[] args) + { + myWonderfulMethod(); + } + + public static void myWonderfulMethod() + { + System.out.println("How Awesome do you think my Method is?"); + } ``` There is an error above being raised being we are not properly closing our class. To solve this issue we add a closing curly brace. After, the closing curly brace of my method. ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - myWonderfulMethod(); - } - - public static void myWonderfulMethod() - { - System.out.println("How Awesome do you think my Method is?"); - } + public static void main(String[] args) + { + myWonderfulMethod(); + } + + public static void myWonderfulMethod() + { + System.out.println("How Awesome do you think my Method is?"); + } } ``` ### 15 - unreachable statement -An "unreachable statement" error takes place when the compiler sees that it is impossible to reacha a certain statement. This is caused by the following code. +An "unreachable statement" error takes place when the compiler sees that it is impossible to reacha a certain statement. This is caused by the following code. ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int theAwesomeNum = doubleMe(5); - System.out.println(theAwesomeNum); - } - - public static int doubleMe(int a) - { - int doubleMe = 2 * a; - return doubleMe; - System.out.println("Returning " + doubleMe); - } + public static void main(String[] args) + { + int theAwesomeNum = doubleMe(5); + System.out.println(theAwesomeNum); + } + + public static int doubleMe(int a) + { + int doubleMe = 2 * a; + return doubleMe; + System.out.println("Returning " + doubleMe); + } } ``` @@ -580,47 +586,47 @@ The compiler will generate a number of errors. The first one to be listed is tha This is because whenever we create a method and use the keyword return the compiler says you are done with the method therefore, we can exit out of the method and execute the next line of code. To fix this error I simply reverse the order of the print statement and the return statement. ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int theAwesomeNum = doubleMe(5); - System.out.println(theAwesomeNum); - } + public static void main(String[] args) + { + int theAwesomeNum = doubleMe(5); + System.out.println(theAwesomeNum); + } - public static int doubleMe(int a) - { - int doubleMe = 2 * a; - System.out.println("Returning " + doubleMe); - return doubleMe; - } + public static int doubleMe(int a) + { + int doubleMe = 2 * a; + System.out.println("Returning " + doubleMe); + return doubleMe; + } } ``` -### 16 - Variable might not have been initialized +### 16 - Variable might not have been initialized An variable might not have been initialized error is triggered when we declare a variable and specify its type but never give it an initial value; ```java - public class Omar - { - public static void main(String[] args) { - int myNum = 16; - int myNum2; - System.out.println(myNum + myNum2); - } - } + public class Omar +{ + public static void main(String[] args) { + int myNum = 16; + int myNum2; + System.out.println(myNum + myNum2); + } +} ``` The compiler will generate the error variable myNum2 might not have been initialized because we declared it with the specified data type but never gave it an initial value. To solve this, I simply give it an initial value. ```java -public class Omar +public class Omar { - public static void main(String[] args) - { - int myNum = 16; - int myNum2=3; - System.out.println(myNum + myNum2); - } + public static void main(String[] args) + { + int myNum = 16; + int myNum2=3; + System.out.println(myNum + myNum2); + } } ``` ### 17 - constructor X in class X cannot be applied to given types @@ -630,34 +636,34 @@ super() ### 18 - Cannot make a static reference to the non-static method logLn(object) from the type Omar ```java -public class Omar +public class Omar { - public void logLn(object o){ - System.out.println(o); - } + public void logLn(object o){ + System.out.println(o); + } - public static void main(String[] args) - { - int myNum = 16; - int myNum2=3; - logLn(myNum + myNum2); - } + public static void main(String[] args) + { + int myNum = 16; + int myNum2=3; + logLn(myNum + myNum2); + } } ``` I am getting this error because logLn should me a static method ```java -public class Omar +public class Omar { - public static void logLn(object o){ - System.out.println(o); - } + public static void logLn(object o){ + System.out.println(o); + } - public static void main(String[] args) - { - int myNum = 16; - int myNum2=3; - logLn(myNum + myNum2); - } + public static void main(String[] args) + { + int myNum = 16; + int myNum2=3; + logLn(myNum + myNum2); + } } ``` @@ -698,8 +704,8 @@ public void setLuckyNum(int luckyNum) { this.luckyNum = luckyNum; } */ -@Getter -@Setter +@Getter +@Setter private int luckyNum = 3532; ``` @@ -713,7 +719,7 @@ public class Example ### Equals And Hash Code Annotation ```java @EqualsAndHashCode( - exclude={"id1", "id2"}) + exclude={"id1", "id2"}) public class Example { } ``` \ No newline at end of file diff --git a/STATIC/README.md b/STATIC/README.md new file mode 100644 index 0000000..dc38e49 --- /dev/null +++ b/STATIC/README.md @@ -0,0 +1,75 @@ +## Static Keyword In Java + + +- SUPER IMPORTANT +- Anything I label static means the class can access it directly + +- Instead of: + - Creating An Object + - THEN ACCESSING IT + +- I can: + - Create a variable to store data + - Create a static method + +```java +import java.util.*; + +public class User{ + private String _name; + private String _membership; + public static List administrators; +} +``` + +### Main Class + +```java +import java.util.*; + +public class Main{ + + public static void main(String [] args){ + User.administrators = new ArrayList(); + User.administrators.add(new User("Abraham")); + User.administrators.add(new User("DJ32")); + } +} +``` + + +
+ +### Static Methods + + + +- I access data members directly on the User class + +- System.out.println where **out** is a static data member of the System class + +- e.g. Whenever you want to read Data from a file You can associate it to a user + - Instead of creating a function I create a static method return a list + +- Example: + +```java +public class User{ + public static List administrators; + + public static void print_the_admins(){ + + /* + since List and print_the_admins are both static + I can omit User.administrators + + */ + //for(User j: User.administrators) + for(User j: administrators){ + + System.out.println(j.get_The_Names()) + } + } +} + +``` \ No newline at end of file