├── .gitignore ├── BasicJava.iml ├── README.md ├── images ├── 1 - Applying Computational Thinking and Techniques ก่อนเริ่มเขียนโปรแกรม.jpg ├── 21 - พาใช้งาน Java Stream API เบื้องต้น แต่ก็แนะนำให้ฝึกเองด้วยมันเยอะมาก.jpg ├── 9-1.jpg ├── 9-2.jpg ├── 9.jpg ├── Assigments │ ├── assigment-1.jpg │ ├── assignment-2.jpg │ └── assignment-3.jpg ├── Collections Framework │ ├── collections-framework.jpg │ ├── hashmap.jpg │ ├── hashset.jpg │ └── list.jpg ├── Multi-threading │ ├── concurrency-vs-parallelism.jpg │ ├── process-thread.jpg │ ├── race-condition.jpg │ ├── thread-life-cycle.jpg │ ├── thread-platform-thread.jpg │ └── thread-virtual-thread.jpg └── Object-Oriented Programming │ ├── 0-intro.jpg │ ├── 1-object.jpg │ ├── 2-class.jpg │ ├── 3-encapsulation.jpg │ ├── 4-abstraction.jpg │ ├── 5-inheritance.jpg │ ├── 6-polymorphism.jpg │ ├── 7-association.jpg │ ├── 8-aggregation.jpg │ └── 9-composition.jpg └── src ├── Main.java ├── codingquestion └── assignment │ ├── array │ ├── IsTheArraySorted.java │ ├── MedianOfArray.java │ ├── PalindromeNumberChecker.java │ ├── PrimeNumberGivenArray.java │ ├── PrimeNumberInRange.java │ └── PrimeNumberUtil.java │ ├── gettingstarted │ ├── AverageOfTenNum.java │ ├── Factorial.java │ ├── LargestOnStreamInput.java │ ├── OddEven.java │ └── TriangleOrSquare.java │ └── string │ ├── HowManyDigit.java │ ├── ILoveEveryone.java │ ├── ILoveU.java │ ├── ILoveVowel.java │ └── ReverseEachWord.java ├── fundamentals ├── ArrayFocus.java ├── DataType.java ├── DealingWithTime.java ├── GettingStarted.java ├── Iteration.java ├── MathExample.java ├── Operator.java ├── ReadInput.java ├── ReadInputAlternative.java ├── Selection.java ├── StringExample.java ├── UnnamedClassInstanceMain.java └── WrapperClass.java ├── hardmode └── socket │ ├── Message.java │ ├── MyClient.java │ ├── MyServer.java │ ├── MyServerVirtualThread.java │ └── SocketExample.java ├── intermediate ├── collections │ ├── list │ │ ├── ArrayDequeExample.java │ │ ├── ArrayListExample.java │ │ ├── LinkedListExample.java │ │ ├── PriorityQueueExample.java │ │ └── StackExample.java │ ├── map │ │ ├── HashMapExample.java │ │ ├── LinkedHashMapExample.java │ │ └── TreeMapExample.java │ ├── model │ │ ├── Account.java │ │ ├── Person.java │ │ ├── Product.java │ │ └── User.java │ ├── other │ │ ├── CollectionFactoryExample.java │ │ └── CollectionSortExample.java │ └── set │ │ ├── HashSetExample.java │ │ ├── LinkedHashSetExample.java │ │ └── TreeSetExample.java ├── generic │ ├── basic │ │ ├── GenericExample.java │ │ ├── Product.java │ │ ├── generic │ │ │ └── PrintWriter.java │ │ └── nongeneric │ │ │ ├── DoublePrintWriter.java │ │ │ └── IntPrintWriter.java │ └── zoo │ │ ├── Animal.java │ │ ├── Enclosure.java │ │ ├── Penguin.java │ │ ├── Redpanda.java │ │ └── ZooMgmt.java ├── handleerror │ ├── Example1.java │ ├── Example2.java │ ├── ExampleError.java │ └── stockmgt │ │ ├── DeductAmountException.java │ │ ├── OutOfStockException.java │ │ ├── Product.java │ │ └── StockManagementApp.java ├── lambdaexpr │ ├── FuncInterfaceExample.java │ ├── LambdaExprExample.java │ ├── MyFuncInterface.java │ └── SpeakApp.java ├── stream │ └── StreamExample.java └── thread │ ├── basic │ ├── Constant.java │ ├── CustomRunnable.java │ ├── CustomThread.java │ └── ThreadExample.java │ ├── concurrency │ ├── ConcurrencyExample.java │ ├── Consumer.java │ ├── GrilledParkShop.java │ ├── GrilledPorkModifiable.java │ └── Merchant.java │ ├── executor │ └── ExecutorExample.java │ └── virtualthread │ ├── PlatformThreadExample.java │ └── VirtualThreadExample.java ├── mostusedinterview ├── ArrayForInterview.java ├── ListForInterview.java ├── MapForInterview.java ├── PriorityQueueForInterview.java ├── QueueForInterview.java ├── SetForInterview.java ├── StackForInterview.java └── StringForInterview.java ├── oop ├── abstractioninterface │ ├── abstraction │ │ ├── Car.java │ │ ├── ElectricCar.java │ │ ├── Main.java │ │ └── PetrolCar.java │ └── interfaceexample │ │ ├── Car.java │ │ ├── ChangeSpeed.java │ │ ├── ElectricCar.java │ │ ├── Main.java │ │ ├── PetrolCar.java │ │ └── Turn.java ├── aggregation │ ├── Main.java │ ├── Racket.java │ └── TennisPlayer.java ├── association │ ├── Address.java │ ├── Main.java │ └── Person.java ├── basicclass │ ├── Car.java │ ├── ColorOfCar.java │ └── Main.java ├── composition │ ├── Car.java │ ├── Engine.java │ └── Main.java ├── inheritance │ ├── Animal.java │ ├── BusinessMan.java │ ├── Cat.java │ ├── Developer.java │ ├── Dog.java │ ├── Human.java │ └── Main.java ├── polymorphism │ ├── overloading │ │ ├── Car.java │ │ └── Main.java │ └── overriding │ │ ├── Animal.java │ │ ├── Cat.java │ │ ├── Dog.java │ │ ├── Human.java │ │ └── Main.java ├── record │ ├── Product.java │ ├── ProductRecord.java │ └── RecordExample.java └── solid │ ├── d │ ├── Main.java │ ├── bad │ │ ├── Car.java │ │ └── Engine.java │ └── good │ │ ├── Car.java │ │ └── Engine.java │ ├── i │ ├── Main.java │ ├── bad │ │ ├── Human.java │ │ ├── Robot.java │ │ └── Worker.java │ └── good │ │ ├── Eatable.java │ │ ├── Human.java │ │ ├── Robot.java │ │ ├── Sleepable.java │ │ └── Workable.java │ ├── l │ ├── Main.java │ ├── bad │ │ ├── BattlePassPlayer.java │ │ ├── FreePlayer.java │ │ ├── Player.java │ │ └── VipPlayer.java │ └── good │ │ ├── BattlePassPlayer.java │ │ ├── CreateBattleRoyal.java │ │ ├── FreePlayer.java │ │ ├── JoinBattleRoyal.java │ │ ├── Player.java │ │ ├── ViewBattleRoyal.java │ │ └── VipPlayer.java │ ├── o │ ├── Main.java │ ├── bad │ │ ├── AreaCalculator.java │ │ ├── Circle.java │ │ ├── Rectangle.java │ │ ├── Shape.java │ │ └── Square.java │ └── good │ │ ├── AreaCalculator.java │ │ ├── Circle.java │ │ ├── Rectangle.java │ │ ├── Shape.java │ │ └── Square.java │ └── s │ ├── Main.java │ ├── bad │ └── TriangleAreaCalculator.java │ └── good │ ├── LengthConverter.java │ └── TriangleAreaCalculator.java └── util └── TutorialUtil.java /.gitignore: -------------------------------------------------------------------------------- 1 | ### IntelliJ IDEA ### 2 | out/ 3 | !**/src/main/**/out/ 4 | !**/src/test/**/out/ 5 | 6 | ### Eclipse ### 7 | .apt_generated 8 | .classpath 9 | .factorypath 10 | .project 11 | .settings 12 | .springBeans 13 | .sts4-cache 14 | bin/ 15 | !**/src/main/**/bin/ 16 | !**/src/test/**/bin/ 17 | 18 | ### NetBeans ### 19 | /nbproject/private/ 20 | /nbbuild/ 21 | /dist/ 22 | /nbdist/ 23 | /.nb-gradle/ 24 | 25 | ### VS Code ### 26 | .vscode/ 27 | 28 | ### Mac OS ### 29 | .DS_Store 30 | 31 | .idea/ -------------------------------------------------------------------------------- /BasicJava.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 20240605-java-dev-bootcamp-example 2 | This repository will contain the code for Java backend developer bootcamp 3 | -------------------------------------------------------------------------------- /images/1 - Applying Computational Thinking and Techniques ก่อนเริ่มเขียนโปรแกรม.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/1 - Applying Computational Thinking and Techniques ก่อนเริ่มเขียนโปรแกรม.jpg -------------------------------------------------------------------------------- /images/21 - พาใช้งาน Java Stream API เบื้องต้น แต่ก็แนะนำให้ฝึกเองด้วยมันเยอะมาก.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/21 - พาใช้งาน Java Stream API เบื้องต้น แต่ก็แนะนำให้ฝึกเองด้วยมันเยอะมาก.jpg -------------------------------------------------------------------------------- /images/9-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/9-1.jpg -------------------------------------------------------------------------------- /images/9-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/9-2.jpg -------------------------------------------------------------------------------- /images/9.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/9.jpg -------------------------------------------------------------------------------- /images/Assigments/assigment-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Assigments/assigment-1.jpg -------------------------------------------------------------------------------- /images/Assigments/assignment-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Assigments/assignment-2.jpg -------------------------------------------------------------------------------- /images/Assigments/assignment-3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Assigments/assignment-3.jpg -------------------------------------------------------------------------------- /images/Collections Framework/collections-framework.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Collections Framework/collections-framework.jpg -------------------------------------------------------------------------------- /images/Collections Framework/hashmap.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Collections Framework/hashmap.jpg -------------------------------------------------------------------------------- /images/Collections Framework/hashset.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Collections Framework/hashset.jpg -------------------------------------------------------------------------------- /images/Collections Framework/list.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Collections Framework/list.jpg -------------------------------------------------------------------------------- /images/Multi-threading/concurrency-vs-parallelism.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Multi-threading/concurrency-vs-parallelism.jpg -------------------------------------------------------------------------------- /images/Multi-threading/process-thread.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Multi-threading/process-thread.jpg -------------------------------------------------------------------------------- /images/Multi-threading/race-condition.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Multi-threading/race-condition.jpg -------------------------------------------------------------------------------- /images/Multi-threading/thread-life-cycle.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Multi-threading/thread-life-cycle.jpg -------------------------------------------------------------------------------- /images/Multi-threading/thread-platform-thread.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Multi-threading/thread-platform-thread.jpg -------------------------------------------------------------------------------- /images/Multi-threading/thread-virtual-thread.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Multi-threading/thread-virtual-thread.jpg -------------------------------------------------------------------------------- /images/Object-Oriented Programming/0-intro.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Object-Oriented Programming/0-intro.jpg -------------------------------------------------------------------------------- /images/Object-Oriented Programming/1-object.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Object-Oriented Programming/1-object.jpg -------------------------------------------------------------------------------- /images/Object-Oriented Programming/2-class.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Object-Oriented Programming/2-class.jpg -------------------------------------------------------------------------------- /images/Object-Oriented Programming/3-encapsulation.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Object-Oriented Programming/3-encapsulation.jpg -------------------------------------------------------------------------------- /images/Object-Oriented Programming/4-abstraction.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Object-Oriented Programming/4-abstraction.jpg -------------------------------------------------------------------------------- /images/Object-Oriented Programming/5-inheritance.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Object-Oriented Programming/5-inheritance.jpg -------------------------------------------------------------------------------- /images/Object-Oriented Programming/6-polymorphism.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Object-Oriented Programming/6-polymorphism.jpg -------------------------------------------------------------------------------- /images/Object-Oriented Programming/7-association.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Object-Oriented Programming/7-association.jpg -------------------------------------------------------------------------------- /images/Object-Oriented Programming/8-aggregation.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Object-Oriented Programming/8-aggregation.jpg -------------------------------------------------------------------------------- /images/Object-Oriented Programming/9-composition.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marttp/20240605-java-dev-bootcamp-example/1d0f02b5f3ca0a05fba2efead5269565409f6f53/images/Object-Oriented Programming/9-composition.jpg -------------------------------------------------------------------------------- /src/Main.java: -------------------------------------------------------------------------------- 1 | void main() { 2 | System.out.println("Welcome to example!"); 3 | } -------------------------------------------------------------------------------- /src/codingquestion/assignment/array/IsTheArraySorted.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.array; 2 | 3 | public class IsTheArraySorted { 4 | 5 | void main() { 6 | // Assume every element is unique 7 | int[] expectedTrue = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 8 | System.out.println(STR."Result: \{isAscSorted(expectedTrue)}"); 9 | int[] expectedFalse = {1, 2, 3, 4, 6, 5, 7, 8, 9}; 10 | // next > previous 11 | System.out.println(STR."Result: \{isAscSorted(expectedFalse)}"); 12 | } 13 | 14 | private static boolean isAscSorted(int[] arr) { 15 | if (arr.length == 0 || arr.length == 1) { 16 | return true; 17 | } 18 | // Assume right now we have more than 2 elements 19 | // index - [0,1,...,n] 20 | for (int i = 1; i < arr.length; i++) { 21 | int current = arr[i]; 22 | int previous = arr[i - 1]; 23 | if (current < previous) { 24 | return false; 25 | } 26 | } 27 | return true; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/array/MedianOfArray.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.array; 2 | 3 | import java.util.Arrays; 4 | 5 | public class MedianOfArray { 6 | 7 | void main() { 8 | int[] example1 = {5, 7, 8, 6, 3}; // Expect: 6 9 | System.out.println(STR."Result: \{findMedian(example1)}"); 10 | int[] example2 = {5, 7, 8, 6, 3, 1}; // Expect: 5.5 11 | System.out.println(STR."Result: \{findMedian(example2)}"); 12 | int[] example3 = {5};// Expect: 5 13 | System.out.println(STR."Result: \{findMedian(example3)}"); 14 | int[] example4 = new int[]{}; // Expect: 0 15 | System.out.println(STR."Result: \{findMedian(example4)}"); 16 | } 17 | 18 | private static double findMedian(int[] arr) { 19 | int length = arr.length; 20 | if (length == 0) { 21 | return 0; 22 | } 23 | if (length == 1) { 24 | return arr[0]; 25 | } 26 | Arrays.sort(arr); 27 | boolean isEven = length % 2 == 0; 28 | if (isEven) { 29 | return (arr[length / 2] * 0.5) + (arr[(length / 2) - 1] * 0.5); 30 | } 31 | return arr[length / 2]; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/array/PalindromeNumberChecker.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.array; 2 | 3 | public class PalindromeNumberChecker { 4 | 5 | void main() { 6 | // Concept - Read backward & forward same 7 | int[] expectedTrue1 = {1, 2, 3, 3, 2, 1}; 8 | System.out.println(STR."expectedTrue1: \{isPalindrome(expectedTrue1)}"); 9 | int[] expectedTrue2 = {1, 2, 3, 2, 1}; 10 | System.out.println(STR."expectedTrue2: \{isPalindrome(expectedTrue2)}"); 11 | int[] expectedFalse = {1, 2, 3, 8, 7, 3, 2, 1}; 12 | System.out.println(STR."expectedFalse: \{isPalindrome(expectedFalse)}"); 13 | } 14 | 15 | private static boolean isPalindrome(int[] arr) { 16 | for (int left = 0, right = arr.length - 1; left <= right; left++, right--) { 17 | if (arr[left] != arr[right]) { 18 | return false; 19 | } 20 | } 21 | return true; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/array/PrimeNumberGivenArray.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.array; 2 | 3 | import static codingquestion.assignment.array.PrimeNumberUtil.isPrime; 4 | 5 | public class PrimeNumberGivenArray { 6 | 7 | void main() { 8 | int[] example = {22, 58, 53, 7, 100, 11, 106, 67, 88}; 9 | for (int n : example) { 10 | boolean isCurrentNumberPrime = isPrime(n); 11 | if (isCurrentNumberPrime) { 12 | System.out.println(STR."\{n} is prime ✅"); 13 | } else { 14 | System.out.println(STR."\{n} is not prime ❌"); 15 | } 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/array/PrimeNumberInRange.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.array; 2 | 3 | import java.util.Scanner; 4 | 5 | import static codingquestion.assignment.array.PrimeNumberUtil.isPrime; 6 | 7 | public class PrimeNumberInRange { 8 | 9 | void main() { 10 | Scanner scanner = new Scanner(System.in); 11 | System.out.print("Enter range number to find prime number: "); 12 | int endRange = Integer.parseInt(scanner.nextLine()); 13 | for (int n = 2; n <= endRange; n++) { 14 | boolean isCurrentNumberPrime = isPrime(n); 15 | if (isCurrentNumberPrime) { 16 | System.out.println(STR."\{n} is prime ✅"); 17 | } else { 18 | System.out.println(STR."\{n} is not prime ❌"); 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/array/PrimeNumberUtil.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.array; 2 | 3 | public class PrimeNumberUtil { 4 | 5 | public static boolean isPrime(int n) { 6 | int maxPossible = (int) Math.sqrt(n); 7 | for (int current = 2; current <= maxPossible; current++) { 8 | if (n % current == 0) { 9 | return false; 10 | } 11 | } 12 | return true; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/gettingstarted/AverageOfTenNum.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.gettingstarted; 2 | 3 | import java.util.Scanner; 4 | 5 | public class AverageOfTenNum { 6 | /* 7 | Write a program that takes 10 numbers as input from the user 8 | - Condition - Input one at a time. 9 | Calculate and display the average of these numbers. 10 | * */ 11 | void main() { 12 | Scanner scanner = new Scanner(System.in); 13 | double sum = 0.0; 14 | int n = 10; 15 | for (int i = 0; i < n; i++) { 16 | System.out.print("Enter number: "); 17 | double input = Double.parseDouble(scanner.nextLine()); 18 | sum += input; 19 | } 20 | System.out.println(STR."Average: \{sum / n}"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/gettingstarted/Factorial.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.gettingstarted; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Factorial { 6 | 7 | void main() { 8 | Scanner scanner = new Scanner(System.in); 9 | System.out.print("Enter number: "); 10 | String input = scanner.nextLine(); 11 | // Assume input positive integer 12 | int n = Integer.parseInt(input); 13 | // 5! = 5 * 4 * 3 * 2 * 1 14 | // 1! = 1, 0! = 1 15 | 16 | // int result = iterative1(n); 17 | // int result = iterative2(n); 18 | int result = recursive(n); 19 | System.out.println(STR."Result: \{result}"); 20 | } 21 | 22 | private static int iterative1(int n) { 23 | if (n <= 1) { 24 | return 1; 25 | } 26 | int result = 1; 27 | for (int multiplier = 2; multiplier <= n; multiplier++) { 28 | result *= multiplier; 29 | } 30 | return result; 31 | } 32 | 33 | private static int iterative2(int n) { 34 | if (n <= 1) { 35 | return 1; 36 | } 37 | int result = 1; 38 | int multiplier = 2; 39 | while (multiplier <= n) { 40 | result *= multiplier; 41 | multiplier++; 42 | } 43 | return result; 44 | } 45 | 46 | private static int recursive(int n) { 47 | if (n <= 1) { 48 | return 1; 49 | } 50 | return recursive(n - 1) * n; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/gettingstarted/LargestOnStreamInput.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.gettingstarted; 2 | 3 | import java.util.Scanner; 4 | 5 | public class LargestOnStreamInput { 6 | /* 7 | Continuously prompt the user to enter integers. 8 | Keep track of the largest number entered so far. 9 | When the user enters a negative number or zero, stop taking input and display the largest number. 10 | * */ 11 | void main() { 12 | Scanner scanner = new Scanner(System.in); 13 | System.out.println(""" 14 | Largest number from stream of input 15 | Please type any integer to find largest value 16 | Note: Type 0 or negative to stop stream 17 | """); 18 | String userInput; 19 | int largest = 0; 20 | while (true) { 21 | System.out.print("Number: "); 22 | userInput = scanner.nextLine(); 23 | // If input cannot parse, let them error 24 | int n = Integer.parseInt(userInput); 25 | if (n <= 0) { 26 | break; 27 | } 28 | if (n > largest) { 29 | largest = n; 30 | System.out.println(STR."Largest number has changed to \{largest}"); 31 | } 32 | } 33 | System.out.println(STR."Largest number from valid stream: \{largest}"); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/gettingstarted/OddEven.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.gettingstarted; 2 | 3 | import java.util.Scanner; 4 | 5 | public class OddEven { 6 | 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | System.out.print("Enter number: "); 10 | String input = scanner.nextLine(); 11 | // Assume input can type only number system 12 | int n = Integer.parseInt(input); 13 | // % 2 => 0 / 1 14 | solution1(n); 15 | solution2(n); 16 | } 17 | 18 | private static void solution1(int n) { 19 | if (n % 2 == 0) { 20 | System.out.println(STR."\{n} is even"); 21 | } else { 22 | System.out.println(STR."\{n} is odd"); 23 | } 24 | } 25 | 26 | private static void solution2(int n) { 27 | String result = switch (n % 2) { 28 | case 0 -> "Even"; 29 | case 1 -> "Odd"; 30 | default -> "N/A"; 31 | }; 32 | System.out.println(STR."\{n} is \{result}"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/gettingstarted/TriangleOrSquare.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.gettingstarted; 2 | 3 | import java.util.Scanner; 4 | 5 | public class TriangleOrSquare { 6 | 7 | /* 8 | Ask the user if they want to calculate the area of a triangle or a square. 9 | Based on their choice: 10 | Triangle: Prompt for the base and height, then calculate and display the area. 11 | Square: Prompt for the side length, then calculate and display the area. 12 | * */ 13 | void main() { 14 | Scanner scanner = new Scanner(System.in); 15 | System.out.println(""" 16 | Area calculate program 17 | 'T' => Triangle 18 | 'S' => Square 19 | """); 20 | System.out.print("Enter choice: "); 21 | String choice = scanner.nextLine(); 22 | // Assume all number from input will positive 23 | if (choice.equals("T")) { 24 | System.out.print("Enter base: "); 25 | double base = Double.parseDouble(scanner.nextLine()); 26 | System.out.print("Enter height: "); 27 | double height = Double.parseDouble(scanner.nextLine()); 28 | double area = 0.5 * base * height; 29 | System.out.println(STR."Triangle area: \{area}"); 30 | } else if (choice.equals("S")) { 31 | System.out.print("Enter side length: "); 32 | double length = Double.parseDouble(scanner.nextLine()); 33 | double area = length * 4; 34 | System.out.println(STR."Square area: \{area}"); 35 | } else { 36 | System.out.println("Invalid choice!"); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/string/HowManyDigit.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.string; 2 | 3 | public class HowManyDigit { 4 | 5 | public static void main(String[] args) { 6 | String paragraph = "zx6cvzx81c56as1 sdx8ssa"; // Expected: 7 7 | int count = 0; 8 | for (char c : paragraph.toCharArray()) { 9 | if (Character.isDigit(c)) { 10 | count++; 11 | } 12 | } 13 | System.out.println(STR."Digit in paragraph: \{count}"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/string/ILoveEveryone.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.string; 2 | 3 | public class ILoveEveryone { 4 | 5 | public static void main(String[] args) { 6 | String example = "aeioutestz"; 7 | int[] amounts = new int[26]; 8 | for (char c : example.toCharArray()) { 9 | amounts[c - 'a']++; 10 | } 11 | for (int i = 0; i < amounts.length; i++) { 12 | char c = (char) ('a' + i); 13 | System.out.println(STR."\{c}: \{amounts[i]}"); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/string/ILoveU.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.string; 2 | 3 | public class ILoveU { 4 | 5 | public static void main(String[] args) { 6 | String paragraph = "Hello, you are so beautiful"; // Expected: 3 7 | int count = 0; 8 | for (char c : paragraph.toCharArray()) { 9 | if (c == 'u' || c == 'U') { 10 | count++; 11 | } 12 | } 13 | System.out.println(STR."u/U in paragraph: \{count}"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/string/ILoveVowel.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.string; 2 | 3 | public class ILoveVowel { 4 | 5 | public static void main(String[] args) { 6 | String paragraph = "Hello, you are so beautiful"; // Expected: 12 7 | int count = 0; 8 | char[] vowels = {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'}; 9 | for (char c : paragraph.toCharArray()) { 10 | for (char v : vowels) { 11 | if (c == v) { 12 | count++; 13 | } 14 | } 15 | } 16 | System.out.println(STR."Vowel in paragraph: \{count}"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/codingquestion/assignment/string/ReverseEachWord.java: -------------------------------------------------------------------------------- 1 | package codingquestion.assignment.string; 2 | 3 | public class ReverseEachWord { 4 | 5 | public static void main(String[] args) { 6 | // Assume input by paragraph - " " as a delimiter 7 | String input = "hello world test"; // Expect output: olleh dlrow tset 8 | String[] splitted = input.split(" "); 9 | String[] result = new String[splitted.length]; 10 | for (int i = 0; i < result.length; i++) { 11 | String reversed = reverse(splitted[i]); 12 | result[i] = reversed; 13 | } 14 | System.out.println(String.join(" ", result)); 15 | } 16 | 17 | private static String reverse(String word) { 18 | char[] arr = word.toCharArray(); 19 | int left = 0; 20 | int right = arr.length -1; 21 | while (left <= right) { 22 | char tmp = arr[left]; 23 | arr[left] = arr[right]; 24 | arr[right] = tmp; 25 | left++; 26 | right--; 27 | } 28 | return String.valueOf(arr); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/fundamentals/ArrayFocus.java: -------------------------------------------------------------------------------- 1 | package fundamentals; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | 6 | public class ArrayFocus { 7 | 8 | /* 9 | * Array 10 | - Group of same type of element 11 | - Reserve memory in sequence 12 | - Store element on same use-case 13 | together 14 | - Array in Java is reference 15 | * */ 16 | public static void main(String[] args) { 17 | // If you want to declare like below example - Reserve number of slots 18 | // Initialized with size 19 | // 0 - 9 = size 10 20 | int[] numbers = new int[10]; 21 | numbers[5] = 10; // Assign value to index 22 | System.out.println(numbers[5]); // Access value by index 23 | 24 | // Combined old array initialization with assign value 25 | int[] exampleArray1 = new int[]{5, 2, 3, 4}; // size = 4 26 | System.out.println(exampleArray1[2]); 27 | 28 | // Declare array with value 29 | String[] names = {"Mart", "Caroll", "James", "Peter"}; 30 | for (var name : names) { 31 | System.out.println(name); 32 | } 33 | 34 | System.out.println("======"); 35 | int[] exampleToShowUtility = {4, 7, 5, 8, 9, 6, 3, 2, 1}; 36 | Arrays.sort(exampleToShowUtility); // Ascending order 37 | System.out.println(Arrays.toString(exampleToShowUtility)); 38 | // Descending order - primitive array 39 | reverse(exampleToShowUtility); 40 | System.out.println(Arrays.toString(exampleToShowUtility)); 41 | // Use stream API 42 | exampleToShowUtility = new int[]{4, 7, 5, 8, 9, 6, 3, 2, 1}; 43 | int[] descResult = Arrays.stream(exampleToShowUtility) 44 | .boxed() 45 | .sorted(Collections.reverseOrder()) 46 | .mapToInt(Integer::intValue) 47 | .toArray(); 48 | System.out.println(Arrays.toString(descResult)); 49 | } 50 | 51 | private static void reverse(int[] arr) { 52 | int left = 0; 53 | int right = arr.length - 1; 54 | while (left <= right) { 55 | int tmp = arr[left]; 56 | arr[left] = arr[right]; 57 | arr[right] = tmp; 58 | left++; 59 | right--; 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/fundamentals/DataType.java: -------------------------------------------------------------------------------- 1 | package fundamentals; 2 | 3 | public class DataType { 4 | 5 | /* 6 | Numeric Types - จำนวนเต็ม 7 | byte (8-bit signed integer) 8 | short (16-bit signed integer) 9 | int (32-bit signed integer, most commonly used) 10 | long (64-bit signed integer) 11 | 12 | Numeric Types Floating-Point (เลขทศนิยม) 13 | float (32-bit single-precision floating-point number) 14 | double (64-bit double-precision floating-point number, more commonly used) 15 | 16 | Character Type: 17 | char (16-bit Unicode character) 18 | 19 | Boolean Type: 20 | boolean (represents true or false) 21 | * */ 22 | public static void main(String[] args) { 23 | // variables use camelCase 24 | byte exampleOfByte = 127; 25 | short exampleOfShort = 100; 26 | int exampleOfInteger = 100; 27 | long exampleOfLong = 100L; 28 | 29 | double exampleOfDouble = 25.00; 30 | float exampleOfFloat = 25.00f; 31 | 32 | char grade = 'D'; 33 | boolean isEnabled = true; // disable mean isEnabled = false 34 | 35 | System.out.println(STR."exampleOfByte: \{exampleOfByte}"); 36 | System.out.println(STR."exampleOfShort: \{exampleOfShort}"); 37 | System.out.println(STR."exampleOfInteger: \{exampleOfInteger}"); 38 | System.out.println(STR."exampleOfLong: \{exampleOfLong}"); 39 | System.out.println(STR."exampleOfDouble: \{exampleOfDouble}"); 40 | System.out.println(STR."exampleOfFloat: \{exampleOfFloat}"); 41 | System.out.println(STR."grade: \{grade}"); 42 | System.out.println(STR."isEnabled: \{isEnabled}"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/fundamentals/DealingWithTime.java: -------------------------------------------------------------------------------- 1 | package fundamentals; 2 | 3 | import util.TutorialUtil; 4 | 5 | import java.time.*; 6 | 7 | public class DealingWithTime { 8 | 9 | public static void main(String[] args) { 10 | Instant instant = Instant.now(); 11 | System.out.println(instant); 12 | // 1718066969000 13 | Instant customTimestamp = Instant.ofEpochMilli(1718066969000L); 14 | System.out.println(customTimestamp); 15 | 16 | TutorialUtil.line(); 17 | 18 | // now() -> Read from server timezone 19 | OffsetDateTime nowUtc = OffsetDateTime.now(ZoneId.of("UTC")); 20 | System.out.println(nowUtc); 21 | OffsetDateTime nowTokyo = OffsetDateTime.now(ZoneId.of("Asia/Tokyo")); 22 | System.out.println(nowTokyo); 23 | OffsetDateTime customFromInstant = OffsetDateTime.ofInstant( 24 | Instant.ofEpochMilli(1718066969000L), ZoneId.of("Asia/Tokyo") 25 | ); 26 | System.out.println(customFromInstant); 27 | 28 | TutorialUtil.line(); 29 | 30 | ZonedDateTime nowUtcZonedDateTime = ZonedDateTime.now(ZoneId.of("UTC")); 31 | System.out.println(nowUtcZonedDateTime); 32 | ZonedDateTime nowTokyoZonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Tokyo")); 33 | System.out.println(nowTokyoZonedDateTime); 34 | ZonedDateTime customFromInstantZonedDateTime = ZonedDateTime.ofInstant( 35 | Instant.ofEpochMilli(1718066969000L), ZoneId.of("Asia/Tokyo") 36 | ); 37 | System.out.println(customFromInstantZonedDateTime); 38 | 39 | TutorialUtil.line(); 40 | 41 | LocalDateTime localDateTime = LocalDateTime.now(); 42 | // It can split to date or time 43 | System.out.println(localDateTime); 44 | System.out.println(localDateTime.toLocalDate()); 45 | System.out.println(localDateTime.toLocalTime()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/fundamentals/GettingStarted.java: -------------------------------------------------------------------------------- 1 | package fundamentals; 2 | 3 | import java.util.Scanner; 4 | 5 | public class GettingStarted { 6 | 7 | 8 | /* 9 | * This the example multiple comment 10 | * The purpose of this multiline is sometime, you need to give more detail about what you have written 11 | * */ 12 | public static void main(String[] args) { 13 | // This is the example of the single line comment 14 | // Your scanner is using for getting user input via your keyboard or from the other datasource 15 | // depending on what you provide 16 | Scanner scanner = new Scanner(System.in); 17 | System.out.println("Hello, My name is Thanaphoom Babparn"); 18 | System.out.println("I'm living in Tokyo, Japan"); 19 | 20 | System.out.print("Please provide any input 1: "); 21 | String input1 = scanner.nextLine(); 22 | System.out.println("User Input 1: " + input1); 23 | 24 | System.out.print("Please provide any input 2: "); 25 | String input2 = scanner.nextLine(); 26 | System.out.println("User Input 2: " + input2); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/fundamentals/Iteration.java: -------------------------------------------------------------------------------- 1 | package fundamentals; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | 6 | import static util.TutorialUtil.line; 7 | 8 | public class Iteration { 9 | 10 | public static void main(String[] args) { 11 | plainForLoop(); 12 | line(); 13 | whileLoop(); 14 | line(); 15 | doWhileLoop(); 16 | line(); 17 | int recursiveValue = recursiveExample(5); 18 | System.out.println("recursiveValue: " + recursiveValue); 19 | line(); 20 | forEachExample(); 21 | } 22 | 23 | // String concat - counting 24 | public static void plainForLoop() { 25 | String message = ""; 26 | // Building block - Initialization, Condition, Updating 27 | for (int n = 1; n <= 10; n++) { 28 | message += STR."\{n} "; 29 | } 30 | System.out.println(STR."plainForLoop: \{message}"); 31 | } 32 | 33 | // Example Dice - 4 34 | public static void whileLoop() { 35 | Random rnd = new Random(); 36 | int dice = 1; 37 | int counter = 0; 38 | // Check before do something 39 | while (dice != 4) { 40 | dice = rnd.nextInt(6) + 1; 41 | System.out.println("Dice: " + dice); 42 | counter++; 43 | } 44 | System.out.println("whileLoop dice amount until 4: " + counter); 45 | } 46 | 47 | // Example Dice - 4 48 | public static void doWhileLoop() { 49 | Random rnd = new Random(); 50 | int dice = 1; 51 | int counter = 0; 52 | // Do something then start checking 53 | do { 54 | dice = rnd.nextInt(6) + 1; 55 | System.out.println("Dice: " + dice); 56 | counter++; 57 | } while (dice != 4); 58 | System.out.println("whileLoop dice amount until 4: " + counter); 59 | } 60 | 61 | public static int recursiveExample(int count) { 62 | if (count < 0) { 63 | return 0; 64 | } 65 | // Store the function/method itself to JVM's Stack and then resolve (pop) once base case complete 66 | if (count == 0) { 67 | return 0; 68 | } 69 | var recursiveValue = recursiveExample(count - 1); 70 | System.out.println("recursiveValue: " + recursiveValue); 71 | return recursiveValue + 1; 72 | } 73 | 74 | // Summation - 14 75 | public static void forEachExample() { 76 | // Use on Array/List with expectation to do on every element 77 | int sum1 = 0; 78 | int[] exampleArray = new int[]{5,2,3,4}; 79 | for (int n : exampleArray) { 80 | sum1 += n; 81 | } 82 | System.out.println(STR."sum1: \{sum1}"); 83 | int sum2 = 0; 84 | List exampleList = List.of(5,2,3,4); 85 | for (int n : exampleList) { 86 | sum2 += n; 87 | } 88 | System.out.println(STR."sum2: \{sum2}"); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/fundamentals/MathExample.java: -------------------------------------------------------------------------------- 1 | package fundamentals; 2 | 3 | public class MathExample { 4 | 5 | public static void main(String[] args) { 6 | // ⭐️ Absolute - different from 0 7 | System.out.println(Math.abs(-5)); 8 | 9 | // Trigonometric - sin,cos,tan,cosec,sec,cot 10 | System.out.println(Math.sin(Math.toRadians(45))); 11 | 12 | // ⭐️ Power 13 | System.out.println(Math.pow(2.0, 10.0)); 14 | // Square root 15 | System.out.println(Math.sqrt(25)); 16 | 17 | // ⭐️ Compare 18 | var min = Math.min(5,9); 19 | System.out.println(min); 20 | var max = Math.max(5,9); 21 | System.out.println(max); 22 | // Integer.min(), Integer.max(), Double.min() and so on 23 | 24 | // ⭐️ round, floor, ceil 25 | System.out.println(Math.round(2.4)); // 2 26 | System.out.println(Math.round(2.5)); // 3 27 | System.out.println(Math.floor(2.4)); // 2 28 | System.out.println(Math.floor(2.5)); // 2 29 | System.out.println(Math.ceil(2.4)); // 3 30 | System.out.println(Math.ceil(2.5)); // 3 31 | 32 | // PI, E, TAU constant 33 | System.out.println(Math.PI); 34 | System.out.println(Math.E); 35 | System.out.println(Math.TAU); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/fundamentals/Operator.java: -------------------------------------------------------------------------------- 1 | package fundamentals; 2 | 3 | public class Operator { 4 | 5 | /* 6 | Type of operator in Java 7 | - Arithmetic 8 | - Relational 9 | - Logical 10 | - Bitwise 11 | - Assignment operators 12 | - Unary operators 13 | - Ternary 14 | */ 15 | public static void main(String[] args) { 16 | // Execute method 17 | arithmetic(); 18 | relational(); 19 | logical(); 20 | bitwise(); 21 | assignment(); 22 | unary(); 23 | ternary(); 24 | } 25 | 26 | public static void arithmetic() { 27 | var add = 10 + 10; 28 | var minus = 10 - 10; 29 | var multiply = 10 * 10; 30 | var divide = 10 / 10; 31 | var modulo = 89 % 10; // 9 32 | } 33 | 34 | public static void relational() { 35 | // relation or comparison 36 | var isEqual = 10 == 10; 37 | var isNotEqual = 10 != 10; 38 | var isGreaterThan = 25 > 10; 39 | var isGreaterThanEqual = 25 >= 25; 40 | var isLessThan = 25 < 10; 41 | var isLessThanEqual = 25 <= 25; 42 | } 43 | 44 | public static void logical() { 45 | // AND, OR, NOT 46 | // AND - both of them true = true 47 | var score = 85; 48 | var isScoreGreaterThanEqualZero = score >= 0; 49 | var isScoreLessThanHundred = score <= 100; 50 | var isInGradeScore = isScoreGreaterThanEqualZero && isScoreLessThanHundred; 51 | // OR - Either of them true = true 52 | var day = 23; 53 | var isGoToMall = (day >= 5 && day <= 10) || (day >= 20 && day <= 25); 54 | 55 | // Java Short circuit 56 | // AND - Left is FALSE => FALSE 57 | // OR - Left is TRUE => TRUE 58 | 59 | // NOT 60 | var isEnabled = !true; // false 61 | } 62 | 63 | public static void bitwise() { 64 | // Example assume unsigned 4 bits = 0 - 15 65 | var exampleValue1 = 7; // 111 66 | var exampleValue2 = 3; // 011 67 | // & bitwise AND 68 | System.out.println(STR."AND: \{exampleValue1 & exampleValue2}"); // 3 69 | // | bitwise OR 70 | System.out.println(STR."OR: \{exampleValue1 | exampleValue2}"); // 7 71 | // ^ bitwise XOR 72 | System.out.println(STR."XOR: \{exampleValue1 ^ exampleValue2}"); // 4 73 | 74 | // ~ bitwise complement 75 | // 0 - positive, 1 - negative 76 | // 7 => 0_111, -7 => 1_001 (2's complement) 77 | // 1 => 0_001, -1 => 1_111 (0_001 => 1_110 + 1 => 1_111) 78 | // ~ => 1's complement 79 | // 7 => 0_111 => 1_000 => -8 80 | System.out.println("Complement: " + ~exampleValue1); 81 | // -7 => 1_001 => 0_110 => 6 82 | System.out.println("Complement: " + ~(-7)); 83 | 84 | // << left shift 85 | // 0b111 << 2 => 0b11100 86 | System.out.println("7 Left shift 2: " + (7 << 2)); 87 | 88 | // >> right shift (signed) 89 | // -8 >> 2, 1_000 >> 2 => 1_110 = -2 90 | System.out.println("-8 Right shift (signed) 2: " + (-8 >> 2)); 91 | // >>> right shift (unsigned) 92 | // Positive: 8 >>> 2 => 0010 = 2 93 | System.out.println("8 Right shift (unsigned) 2: " + (8 >>> 2)); 94 | // Negative: -8 >>> 2 (32 bits) => 11 1111111111 1111111111 1111111000 95 | // 00111111111111111111111111111110 => 1073741822 96 | System.out.println("-8 Right shift (unsigned) 2: " + (-8 >>> 2)); 97 | } 98 | 99 | public static void assignment() { 100 | // assign value to variable 101 | var day = 25; 102 | // Combination arithmetic + assignment 103 | var amount = 20; 104 | amount += 10; // amount = amount + 10; 105 | System.out.println(STR."Current amount = \{amount}"); 106 | } 107 | 108 | public static void unary() { 109 | // Incremental / Decremental 110 | // ++, -- 111 | // in front - do operation before execution of variable 112 | // in back - do operation after execution of variable 113 | var day = 10; 114 | day++; 115 | System.out.println(STR."Incremental: \{day}"); // day = 11 116 | day--; 117 | System.out.println(STR."Decremental: \{day}"); // day = 10 118 | 119 | var score = 100; 120 | // System.out.println(STR."Incremental: \{++score}"); // score = 101 121 | System.out.println(STR."Incremental: \{score++}"); // score = 100 122 | // score = 101 starting from this line 123 | System.out.println(STR."Incremental: \{score}"); 124 | } 125 | 126 | public static void ternary() { 127 | // If-Else 128 | var score = 85; 129 | // Consider PASS / NOT_PASS 130 | // if (score >= 80) { 131 | // PASS 132 | // } else { 133 | // NOT_PASS 134 | // } 135 | var grade = score >= 80 ? "PASS" : "NOT_PASS"; 136 | System.out.println(STR."Grade: \{grade}"); 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/fundamentals/ReadInput.java: -------------------------------------------------------------------------------- 1 | package fundamentals; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ReadInput { 6 | 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | System.out.print("Please provide your input: "); 10 | String text = scanner.nextLine(); 11 | System.out.println("This is what you have typed: " + text); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/fundamentals/ReadInputAlternative.java: -------------------------------------------------------------------------------- 1 | package fundamentals; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | public class ReadInputAlternative { 8 | 9 | /* 10 | * Alternative of read line - InputStreamReader + BufferedReader 11 | * This approach in terms of performance, it's a bit faster than scanner. 12 | * Normally, it's not quite used except competitive programming. 13 | * Anyway, The faster approach are existing but since contain too much word. 14 | * I want to introduce only InputStreamReader + BufferedReader 15 | * */ 16 | public static void main(String[] args) throws IOException { 17 | InputStreamReader input = new InputStreamReader(System.in); 18 | BufferedReader bufferedReader = new BufferedReader(input); 19 | System.out.print("Please provide your input: "); 20 | String text = bufferedReader.readLine(); 21 | System.out.println("This is what you have typed: " + text); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/fundamentals/Selection.java: -------------------------------------------------------------------------------- 1 | package fundamentals; 2 | 3 | public class Selection { 4 | 5 | public static void main(String[] args) { 6 | simpleIfExample(); 7 | line(); 8 | validationByGuardClause(-3); 9 | line(); 10 | ifElseExample(true); 11 | line(); 12 | ifElseIfExample(); 13 | switchExample("Sunday"); 14 | line(); 15 | nestedIf(-100, true); 16 | System.out.println("-"); 17 | nestedIf(-100, false); 18 | } 19 | 20 | private static void line() { 21 | System.out.println("========="); 22 | } 23 | 24 | private static void simpleIfExample() { 25 | int amount = 20; 26 | System.out.println("Step 1"); 27 | if (amount > 10) { 28 | System.out.println("Wow! Amount more than 10"); 29 | } 30 | System.out.println("Step 2"); 31 | System.out.println("Step 3"); 32 | } 33 | 34 | private static void validationByGuardClause(int amount) { 35 | if (amount < 0) { 36 | System.out.println("This is negative number cannot proceed"); 37 | return; 38 | } 39 | System.out.println("Accept amount: " + amount); 40 | } 41 | 42 | // Take a walk condition 43 | private static void ifElseExample(boolean isColdOutside) { 44 | // Tank Top - Hot, Sweater - Cold 45 | String shirt; 46 | if (isColdOutside) { 47 | shirt = "Sweater"; 48 | } else { 49 | shirt = "Tank Top"; 50 | } 51 | System.out.println(STR."I need to wear \{shirt} to go outside"); 52 | } 53 | 54 | // Traffic light example - RED, YELLOW, GREEN, BLANK 55 | private static void ifElseIfExample() { 56 | int speed = 40; 57 | String light = "BLANK"; 58 | if (light.equals("RED")) { 59 | speed = 0; 60 | System.out.println(STR."Current speed: \{speed}"); 61 | } else if (light.equals("YELLOW")) { 62 | speed = 20; 63 | System.out.println(STR."Current speed: \{speed}"); 64 | } else if (light.equals("GREEN")) { 65 | speed += 2; 66 | System.out.println(STR."Current speed: \{speed}"); 67 | } 68 | // BLANK will do nothing here 69 | // We will end with "else" condition if and only if we have another computation to do separate 70 | } 71 | 72 | // Weekday or Weekend or N/A 73 | private static void switchExample(String day) { 74 | oldSwitch1(day); 75 | oldSwitch2(day); 76 | newSwitchExpression1(day); 77 | newSwitchExpression2(day); 78 | newSwitchYieldStatement(day); 79 | } 80 | 81 | private static void oldSwitch1(String day) { 82 | String result; 83 | // Put value that you need to check 84 | switch (day) { 85 | case "Monday": 86 | result = "Weekday"; 87 | break; 88 | case "Tuesday": 89 | result = "Weekday"; 90 | break; 91 | case "Wednesday": 92 | result = "Weekday"; 93 | break; 94 | case "Thursday": 95 | result = "Weekday"; 96 | break; 97 | case "Friday": 98 | result = "Weekday"; 99 | break; 100 | case "Saturday": 101 | result = "Weekend"; 102 | break; 103 | case "Sunday": 104 | result = "Weekend"; 105 | break; 106 | default: 107 | result = "N/A"; 108 | break; 109 | } 110 | System.out.println(STR."[oldSwitch1] Result: \{result}"); 111 | } 112 | 113 | private static void oldSwitch2(String day) { 114 | String result; 115 | switch (day) { 116 | case "Monday": 117 | case "Tuesday": 118 | case "Wednesday": 119 | case "Thursday": 120 | case "Friday": 121 | result = "Weekday"; 122 | break; 123 | case "Saturday": 124 | case "Sunday": 125 | result = "Weekend"; 126 | break; 127 | default: 128 | result = "N/A"; 129 | break; 130 | } 131 | System.out.println(STR."[oldSwitch2] Result: \{result}"); 132 | } 133 | 134 | private static void newSwitchExpression1(String day) { 135 | String result; 136 | switch (day) { 137 | case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday": 138 | result = "Weekday"; 139 | break; 140 | case "Saturday", "Sunday": 141 | result = "Weekend"; 142 | break; 143 | default: 144 | result = "N/A"; 145 | break; 146 | } 147 | System.out.println(STR."[newSwitchExpression1] Result: \{result}"); 148 | } 149 | 150 | private static void newSwitchExpression2(String day) { 151 | String result = switch (day) { 152 | case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Weekday"; 153 | case "Saturday", "Sunday" -> "Weekend"; 154 | default -> "N/A"; 155 | }; 156 | System.out.println(STR."[newSwitchExpression2] Result: \{result}"); 157 | } 158 | 159 | // Yield - providing more computation block 160 | private static void newSwitchYieldStatement(String day) { 161 | String result = switch (day) { 162 | case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> { 163 | System.out.println("Oh! we got weekday"); 164 | yield "Weekday"; 165 | } 166 | case "Saturday", "Sunday" -> { 167 | System.out.println("Oh! we can sleep on weekend"); 168 | yield "Weekend"; 169 | } 170 | default -> { 171 | System.out.println("What kind of day?!"); 172 | yield "N/A"; 173 | } 174 | }; 175 | System.out.println(STR."[newSwitchYieldStatement] Result: \{result}"); 176 | } 177 | 178 | // Validate Input - log example 179 | private static void nestedIf(int amount, boolean isEnabledEmergency) { 180 | if (amount < 0) { 181 | System.out.println(STR."We received negative amount: \{amount}"); 182 | // If emergency enable - we will contact support 183 | if (isEnabledEmergency) { 184 | System.out.println("Contact to support with topic: Received negative amount on system"); 185 | } 186 | } 187 | System.out.println("Success on nestedIf"); 188 | } 189 | 190 | } 191 | -------------------------------------------------------------------------------- /src/fundamentals/StringExample.java: -------------------------------------------------------------------------------- 1 | package fundamentals; 2 | 3 | import java.util.Arrays; 4 | 5 | public class StringExample { 6 | 7 | // String - data type for text on Java (almost every programming languages) 8 | // String - immutable, reference type -> Store on heap 9 | // String variableName = "ตัวอย่างข้อมูล"; 10 | void main() { 11 | stringExample(); 12 | System.out.println("======"); 13 | stringBuilderExample(); 14 | System.out.println("======"); 15 | // "name:exp:nationality" 16 | String name = "Mart"; 17 | int exp = 5; 18 | String nationality = "Thai"; 19 | // New Java 20 | String introduction = STR."\{name}:\{exp}:\{nationality}"; // Know exactly pattern 21 | System.out.println(introduction); 22 | String multilineString = """ 23 | Hello, everyone. 24 | I'm Thanaphoom Babparn. TP Coder, YT + FB 25 | """; 26 | System.out.println(multilineString); 27 | // Other utilities 28 | String[] strArray = {name, String.valueOf(exp), nationality}; 29 | String joinWithCustomDelimeter = String.join("-", strArray); // Unknown how long of incoming data 30 | System.out.println(joinWithCustomDelimeter); 31 | } 32 | 33 | private static void stringExample() { 34 | String name = "TP Coder"; 35 | // name = "TP Coder, exp 5 years"; // Reassign 36 | // name = name + ", exp 5 years"; // Concat 1 37 | name = name.concat(", exp 5 years"); // Concat 2 38 | System.out.println(name); 39 | // String - array of character 40 | char[] nameCharArray = name.toCharArray(); 41 | System.out.println(nameCharArray); 42 | System.out.println(Arrays.toString(nameCharArray)); 43 | // String - has many utility methods 44 | System.out.println(name.toUpperCase()); 45 | System.out.println(name.toLowerCase()); 46 | // Compare string - use equals 47 | var ex1 = "TP"; 48 | var ex2 = "tp"; 49 | System.out.println(ex1.equals(ex2)); // false 50 | System.out.println(ex1.equalsIgnoreCase(ex2)); // true 51 | } 52 | 53 | private static void stringBuilderExample() { 54 | // "name:exp:nationality" 55 | String name = "Mart"; 56 | int exp = 5; 57 | String nationality = "Thai"; 58 | 59 | // String key = name + exp + nationality; // Concat 2 times, generate in background 2 times 60 | String key = name + ":" + exp + ":" + nationality; // Concat 4 times 61 | 62 | StringBuilder sb = new StringBuilder(); 63 | sb.append(name); 64 | sb.append(":"); 65 | sb.append(exp); 66 | sb.append(":"); 67 | sb.append(nationality); 68 | String keyBySb = sb.toString(); // Generate 1 time 69 | 70 | System.out.println(key); 71 | System.out.println(keyBySb); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/fundamentals/UnnamedClassInstanceMain.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.IOException; 3 | import java.io.InputStreamReader; 4 | 5 | void main() throws IOException { 6 | InputStreamReader inputStreamReader = new InputStreamReader(System.in); 7 | BufferedReader br = new BufferedReader(inputStreamReader); 8 | System.out.print("Please provide any input 1: "); 9 | String input1 = br.readLine(); 10 | System.out.println(STR."User Input 1: \{input1}"); 11 | } 12 | -------------------------------------------------------------------------------- /src/fundamentals/WrapperClass.java: -------------------------------------------------------------------------------- 1 | package fundamentals; 2 | 3 | public class WrapperClass { 4 | 5 | public static void main(String[] args) { 6 | basicWrapper(); 7 | parseTechnique(); 8 | } 9 | 10 | public static void basicWrapper() { 11 | byte exampleOfByte = 127; 12 | Byte exampleOfByteBoxing = Byte.valueOf(exampleOfByte); // Boxing 13 | System.out.println(exampleOfByteBoxing.byteValue()); // Unboxing 14 | // Example of auto boxing 15 | Byte autoBoxing = exampleOfByte; 16 | // Example of auto unboxing 17 | System.out.println(exampleOfByteBoxing); 18 | 19 | Short shortData = 100; 20 | Integer integerData = 100; 21 | Long longData = 100L; 22 | 23 | Double doubleData = 25.00; 24 | Float floatData = 25.00f; 25 | 26 | Character grade = 'D'; 27 | System.out.println("isLetterOrDigit: " + Character.isLetterOrDigit(grade)); 28 | 29 | Boolean isEnabled = true; 30 | } 31 | 32 | public static void parseTechnique() { 33 | // Auto unboxing -> Integer (wrapper) => int (primitive) 34 | int operand1 = Integer.parseInt("500"); 35 | int operand2 = Integer.parseInt("100"); 36 | System.out.println("Add: " + operand1 + operand2); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/hardmode/socket/Message.java: -------------------------------------------------------------------------------- 1 | package hardmode.socket; 2 | 3 | public record Message(int id, String data) { 4 | } 5 | -------------------------------------------------------------------------------- /src/hardmode/socket/MyClient.java: -------------------------------------------------------------------------------- 1 | package hardmode.socket; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | import java.io.PrintWriter; 6 | import java.net.Socket; 7 | import java.util.Scanner; 8 | 9 | public class MyClient { 10 | 11 | public void connect(final String host, final int port, final Scanner scanner) { 12 | try (var socket = new Socket(host, port); 13 | var writer = new PrintWriter(socket.getOutputStream(), true); 14 | var reader = new BufferedReader(new InputStreamReader(socket.getInputStream())) 15 | ) { 16 | System.out.println("Established connection"); 17 | String userInput; 18 | while (true) { 19 | System.out.print("Input: "); 20 | userInput = scanner.nextLine(); 21 | if (userInput.isEmpty()) { 22 | break; 23 | } 24 | writer.println(userInput); 25 | var serverResponse = reader.readLine(); 26 | System.out.println(STR."Response: \{serverResponse}"); 27 | } 28 | } catch (Exception e) { 29 | System.out.println("Connection closed..."); 30 | throw new RuntimeException(e); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/hardmode/socket/MyServer.java: -------------------------------------------------------------------------------- 1 | package hardmode.socket; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.io.PrintWriter; 7 | import java.net.ServerSocket; 8 | import java.util.concurrent.atomic.AtomicInteger; 9 | 10 | public class MyServer { 11 | 12 | private static final AtomicInteger ID_GENERATOR = new AtomicInteger(1); 13 | 14 | public void start(final int port) { 15 | try (var serverSocket = new ServerSocket(port)) { 16 | System.out.println(STR."Server started on port: \{port}"); 17 | while (true) { 18 | // Established connection 19 | var client = serverSocket.accept(); 20 | var clientIp = client.getInetAddress().getHostAddress(); 21 | var clientPort = client.getPort(); 22 | try (var clientInput = new BufferedReader(new InputStreamReader(client.getInputStream())); 23 | var output = new PrintWriter(client.getOutputStream(), true) 24 | ) { 25 | for (String input; !(input = clientInput.readLine()).isEmpty(); ) { 26 | System.out.println(STR."\{clientIp}:\{clientPort}:\{input}"); 27 | var message = new Message(ID_GENERATOR.getAndIncrement(), input); 28 | output.println(message); 29 | } 30 | } catch (Exception e) { 31 | client.close(); 32 | System.out.println(STR."Connection closed for \{client}"); 33 | } 34 | } 35 | } catch (IOException e) { 36 | System.out.println("Socket server is shutdown..."); 37 | throw new RuntimeException(e); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/hardmode/socket/MyServerVirtualThread.java: -------------------------------------------------------------------------------- 1 | package hardmode.socket; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.io.PrintWriter; 7 | import java.net.ServerSocket; 8 | import java.util.concurrent.Executors; 9 | import java.util.concurrent.atomic.AtomicInteger; 10 | 11 | public class MyServerVirtualThread { 12 | 13 | private static final AtomicInteger ID_GENERATOR = new AtomicInteger(1); 14 | 15 | public void start(final int port) { 16 | try (var serverSocket = new ServerSocket(port)) { 17 | System.out.println(STR."Server started on port: \{port}"); 18 | try (var executorService = Executors.newVirtualThreadPerTaskExecutor()) { 19 | while (true) { 20 | // Established connection 21 | var client = serverSocket.accept(); 22 | executorService.submit(() -> { 23 | var clientIp = client.getInetAddress().getHostAddress(); 24 | var clientPort = client.getPort(); 25 | try (var clientInput = new BufferedReader(new InputStreamReader(client.getInputStream())); 26 | var output = new PrintWriter(client.getOutputStream(), true) 27 | ) { 28 | for (String input; !(input = clientInput.readLine()).isEmpty(); ) { 29 | System.out.println(STR."\{clientIp}:\{clientPort}:\{input}"); 30 | var message = new Message(ID_GENERATOR.getAndIncrement(), input); 31 | output.println(message); 32 | } 33 | } catch (Exception e) { 34 | try { 35 | client.close(); 36 | System.out.println(STR."Connection closed for \{client}"); 37 | } catch (IOException ex) { 38 | throw new RuntimeException(ex); 39 | } 40 | } 41 | }); 42 | } 43 | } 44 | } catch (IOException e) { 45 | System.out.println("Socket server is shutdown..."); 46 | throw new RuntimeException(e); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/hardmode/socket/SocketExample.java: -------------------------------------------------------------------------------- 1 | package hardmode.socket; 2 | 3 | import java.util.Scanner; 4 | 5 | public class SocketExample { 6 | 7 | private static final int PORT = 8080; 8 | private static final String HOST = "localhost"; 9 | 10 | public static void main(String[] args) { 11 | System.out.println(""" 12 | Server: 1 13 | Server (VT): 11 14 | Client: 2 15 | """); 16 | System.out.print("Your choice: "); 17 | Scanner scanner = new Scanner(System.in); 18 | int choice = Integer.parseInt(scanner.nextLine()); 19 | switch (choice) { 20 | case 1 -> new MyServer().start(PORT); 21 | case 11 -> new MyServerVirtualThread().start(PORT); 22 | case 2 -> new MyClient().connect(HOST, PORT, scanner); 23 | default -> throw new IllegalArgumentException("Unknown choice!"); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/intermediate/collections/list/ArrayDequeExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.list; 2 | 3 | import intermediate.collections.model.Person; 4 | import util.TutorialUtil; 5 | 6 | import java.util.ArrayDeque; 7 | import java.util.Deque; 8 | 9 | public class ArrayDequeExample { 10 | 11 | public static void main(String[] args) { 12 | var mart = new Person("Mart"); 13 | var peter = new Person("Peter"); 14 | var silva = new Person("Silva"); 15 | 16 | // Queue - FIFO (First-In-First-Out) 17 | Deque queue = new ArrayDeque<>(); 18 | queue.add(mart); 19 | queue.add(peter); 20 | queue.add(silva); 21 | // Who is at front? 22 | System.out.println(STR."\{queue.peek()} is at front"); 23 | for (var p : queue) { 24 | System.out.println(STR."\{p} is on queue"); 25 | } 26 | TutorialUtil.line(); 27 | while (!queue.isEmpty()) { 28 | // Walk out from queue 29 | var person = queue.poll(); 30 | System.out.println(STR."\{person} is walking out"); 31 | System.out.println(STR."Number on queue: \{queue.size()}"); 32 | } 33 | 34 | // ArrayDeque can implement as stack 35 | Deque stack = new ArrayDeque<>(); 36 | // Remove from same direction which you added 37 | // [] <- push on tail 38 | stack.offerLast(mart); 39 | stack.offerLast(peter); 40 | stack.offerLast(silva); 41 | // Example of pop stack 42 | System.out.println(stack.pollLast()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/intermediate/collections/list/ArrayListExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.list; 2 | 3 | import intermediate.collections.model.Product; 4 | import util.TutorialUtil; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | public class ArrayListExample { 10 | 11 | public static void main(String[] args) { 12 | 13 | var iPhone = new Product("iPhone", 35000.0, 20); 14 | var linuxLaptop = new Product("Laptop Linux", 13000.0, 35); 15 | var bookProduct = new Product("Book", 230.0, 10); 16 | 17 | List products = new ArrayList<>(); 18 | products.add(iPhone); 19 | products.add(linuxLaptop); 20 | products.add(bookProduct); 21 | 22 | for (var p : products) { 23 | System.out.println(p); 24 | } 25 | 26 | TutorialUtil.line(); 27 | 28 | // Example of add all 29 | List newListOfProducts = new ArrayList<>(); 30 | var microphone = new Product("Microphone", 2500.0, 16); 31 | newListOfProducts.add(microphone); 32 | newListOfProducts.addAll(products); 33 | for (var p : newListOfProducts) { 34 | System.out.println(p); 35 | } 36 | 37 | TutorialUtil.line(); 38 | 39 | // Get first 40 | System.out.println(newListOfProducts.getFirst()); 41 | // Get last 42 | System.out.println(newListOfProducts.getLast()); 43 | // Access element by index 44 | System.out.println(newListOfProducts.get(2)); 45 | 46 | var searchCriteria = new Product("Laptop Linux", 13000.0, 35); 47 | if (newListOfProducts.contains(searchCriteria)) { 48 | System.out.println("Contain Linux Laptop with prices 13000.0 amount 35"); 49 | } 50 | 51 | TutorialUtil.line(); 52 | 53 | // Modify data within array list - Normal class, cannot use record 54 | // Replace data on the index 55 | var index2 = newListOfProducts.get(2); 56 | System.out.println(index2); 57 | var doll = new Product("Doll", 150.0, 5); 58 | newListOfProducts.set(2, doll); 59 | System.out.println(newListOfProducts.get(2)); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/intermediate/collections/list/LinkedListExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.list; 2 | 3 | import intermediate.collections.model.Person; 4 | import util.TutorialUtil; 5 | 6 | import java.util.LinkedList; 7 | 8 | public class LinkedListExample { 9 | 10 | public static void main(String[] args) { 11 | var mart = new Person("Mart"); 12 | var peter = new Person("Peter"); 13 | var silva = new Person("Silva"); 14 | 15 | LinkedList queue = new LinkedList<>(); 16 | queue.add(mart); 17 | queue.add(peter); 18 | queue.add(silva); 19 | 20 | System.out.println(STR."\{queue.peek()} is at front"); 21 | for (var p : queue) { 22 | System.out.println(STR."\{p} is on queue"); 23 | } 24 | TutorialUtil.line(); 25 | while (!queue.isEmpty()) { 26 | // Walk out from queue 27 | var person = queue.poll(); 28 | System.out.println(STR."\{person} is walking out"); 29 | System.out.println(STR."Number on queue: \{queue.size()}"); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/intermediate/collections/list/PriorityQueueExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.list; 2 | 3 | import intermediate.collections.model.Product; 4 | import util.TutorialUtil; 5 | 6 | import java.util.Collections; 7 | import java.util.Comparator; 8 | import java.util.PriorityQueue; 9 | 10 | public class PriorityQueueExample { 11 | 12 | public static void main(String[] args) { 13 | pqPrimitiveWrapper(); 14 | pqDataObject(); 15 | } 16 | 17 | private static void pqPrimitiveWrapper() { 18 | // Default is Min heap 19 | PriorityQueue minHeap = new PriorityQueue<>(); 20 | minHeap.add(5); 21 | minHeap.add(3); 22 | minHeap.add(7); 23 | minHeap.add(9); 24 | minHeap.add(2); 25 | minHeap.add(1); 26 | while (!minHeap.isEmpty()) { 27 | System.out.println(minHeap.poll()); 28 | } 29 | TutorialUtil.line(); 30 | // Turn to Max heap 31 | PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); 32 | maxHeap.add(5); 33 | maxHeap.add(3); 34 | maxHeap.add(7); 35 | maxHeap.add(9); 36 | maxHeap.add(2); 37 | maxHeap.add(1); 38 | while (!maxHeap.isEmpty()) { 39 | System.out.println(maxHeap.poll()); 40 | } 41 | } 42 | 43 | private static void pqDataObject() { 44 | var iPhone = new Product("iPhone", 35000.0, 20); 45 | var linuxLaptop = new Product("Laptop Linux", 13000.0, 35); 46 | var bookProduct = new Product("Book", 230.0, 10); 47 | // Min Heap of Products prices 48 | PriorityQueue minHeap = new PriorityQueue<>( 49 | Comparator.comparingDouble(Product::prices) 50 | ); 51 | minHeap.add(iPhone); 52 | minHeap.add(linuxLaptop); 53 | minHeap.add(bookProduct); 54 | while (!minHeap.isEmpty()) { 55 | System.out.println(minHeap.poll()); 56 | } 57 | TutorialUtil.line(); 58 | // Max Heap of Products amount 59 | PriorityQueue maxHeap = new PriorityQueue<>( 60 | (e1, e2) -> Integer.compare(e2.amount(), e1.amount()) 61 | ); 62 | maxHeap.add(iPhone); 63 | maxHeap.add(linuxLaptop); 64 | maxHeap.add(bookProduct); 65 | while (!maxHeap.isEmpty()) { 66 | System.out.println(maxHeap.poll()); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/intermediate/collections/list/StackExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.list; 2 | 3 | import java.util.Stack; 4 | 5 | public class StackExample { 6 | 7 | public static void main(String[] args) { 8 | // Stack - LIFO (Last-In-First-Out) 9 | Stack stack = new Stack<>(); 10 | stack.push(5); 11 | System.out.println(stack.peek()); // 5 12 | stack.push(2); 13 | System.out.println(stack.peek()); // 2 14 | var previousValue = stack.pop(); // 2 15 | System.out.println(previousValue); 16 | stack.push(3); 17 | System.out.println(stack.peek()); // 3 18 | if (stack.empty()) { 19 | System.out.println("Stack empty"); 20 | } else { 21 | System.out.println("Stack contains element"); 22 | } 23 | // Check current size 24 | System.out.println(STR."Current size: \{stack.size()}"); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/intermediate/collections/map/HashMapExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.map; 2 | 3 | import intermediate.collections.model.Account; 4 | import intermediate.collections.model.User; 5 | 6 | import java.util.ArrayList; 7 | import java.util.HashMap; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | public class HashMapExample { 12 | 13 | private static final String ODD = "ODD"; 14 | private static final String EVEN = "EVEN"; 15 | 16 | public static void main(String[] args) { 17 | hashMapBasic(); 18 | hashMapAdapt(); 19 | } 20 | 21 | private static void hashMapBasic() { 22 | // 1 - 20 -> Grouping odd, even 23 | // => What type of key & value? 24 | // Example design => { "ODD": [1,3,5,7,...], "EVEN": [2,4,6,8,...]} 25 | Map> grouping = new HashMap<>(); 26 | // Initial value 27 | grouping.put(ODD, new ArrayList<>()); 28 | grouping.put(EVEN, new ArrayList<>()); 29 | 30 | for (int n = 1; n <= 20; n++) { 31 | if (n % 2 == 0) { 32 | grouping.get(EVEN).add(n); 33 | } else { 34 | grouping.get(ODD).add(n); 35 | } 36 | } 37 | 38 | System.out.println(grouping); 39 | } 40 | 41 | private static void hashMapAdapt() { 42 | // UserId -> Account? 43 | Map userIdMapAccount = new HashMap<>(); 44 | List users = List.of( 45 | new User(1, "Mart", new Account(1001)), 46 | new User(2, "Silva", new Account(1002)), 47 | new User(5, "Peter", new Account(1003)), 48 | new User(9, "Jame", new Account(1004)), 49 | new User(8, "Poppy", new Account(1005)) 50 | ); 51 | for (var u : users) { 52 | userIdMapAccount.put(u.id(), u.account()); 53 | } 54 | System.out.println(userIdMapAccount); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/intermediate/collections/map/LinkedHashMapExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.map; 2 | 3 | import intermediate.collections.model.Account; 4 | import intermediate.collections.model.User; 5 | 6 | import java.util.LinkedHashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | public class LinkedHashMapExample { 11 | 12 | public static void main(String[] args) { 13 | // Key will maintain order based on add event 14 | Map userIdMapAccount = new LinkedHashMap<>(); 15 | List users = List.of( 16 | new User(1, "Mart", new Account(1001)), 17 | new User(2, "Silva", new Account(1002)), 18 | new User(5, "Peter", new Account(1003)), 19 | new User(9, "Jame", new Account(1004)), 20 | new User(8, "Poppy", new Account(1005)) 21 | ); 22 | for (var u : users) { 23 | userIdMapAccount.put(u.id(), u.account()); 24 | } 25 | System.out.println(userIdMapAccount); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/intermediate/collections/map/TreeMapExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.map; 2 | 3 | import intermediate.collections.model.Account; 4 | import intermediate.collections.model.User; 5 | 6 | import java.util.List; 7 | import java.util.TreeMap; 8 | 9 | public class TreeMapExample { 10 | 11 | public static void main(String[] args) { 12 | // Key wil sorted 13 | TreeMap userIdMapAccount = new TreeMap<>(); 14 | List users = List.of( 15 | new User(1, "Mart", new Account(1001)), 16 | new User(5, "Peter", new Account(1003)), 17 | new User(9, "Jame", new Account(1004)), 18 | new User(2, "Silva", new Account(1002)), 19 | new User(8, "Poppy", new Account(1005)) 20 | ); 21 | for (var u : users) { 22 | userIdMapAccount.put(u.id(), u.account()); 23 | } 24 | System.out.println(userIdMapAccount); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/intermediate/collections/model/Account.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.model; 2 | 3 | public record Account(long id) { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/intermediate/collections/model/Person.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.model; 2 | 3 | public record Person(String name) { 4 | } 5 | -------------------------------------------------------------------------------- /src/intermediate/collections/model/Product.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.model; 2 | 3 | public record Product( 4 | String name, 5 | double prices, 6 | int amount 7 | ) { 8 | } 9 | -------------------------------------------------------------------------------- /src/intermediate/collections/model/User.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.model; 2 | 3 | public record User(long id, String name, Account account) { 4 | } 5 | -------------------------------------------------------------------------------- /src/intermediate/collections/other/CollectionFactoryExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.other; 2 | 3 | import intermediate.collections.model.Account; 4 | import intermediate.collections.model.User; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.Set; 9 | 10 | public class CollectionFactoryExample { 11 | 12 | public static void main(String[] args) { 13 | // Collection Factory - You can declare collection frameworks without new keyword 14 | // Tradeoff, all of them is immutable 15 | List colors = List.of( 16 | Color.RED, 17 | Color.BLACK, 18 | Color.GREEN, 19 | Color.YELLOW 20 | ); 21 | System.out.println(colors); 22 | // Can apply to Set.of(), Map.of() 23 | Set immutableIntegerSet = Set.of(1, 2, 5, 8, 6); 24 | System.out.println(immutableIntegerSet); 25 | Map userAssociateMap = Map.of( 26 | 1, new User(1, "Mart", new Account(1001)), 27 | 2, new User(2, "Silva", new Account(1002)), 28 | 3, new User(5, "Peter", new Account(1003)), 29 | 4, new User(9, "Jame", new Account(1004)), 30 | 5, new User(8, "Poppy", new Account(1005)) 31 | ); 32 | System.out.println(userAssociateMap); 33 | } 34 | 35 | private enum Color { 36 | RED, BLACK, GREEN, YELLOW 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/intermediate/collections/other/CollectionSortExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.other; 2 | 3 | import intermediate.collections.model.Product; 4 | 5 | import java.util.*; 6 | 7 | public class CollectionSortExample { 8 | 9 | public static void main(String[] args) { 10 | 11 | var iPhone = new Product("iPhone", 35000.0, 20); 12 | var linuxLaptop = new Product("Laptop Linux", 13000.0, 35); 13 | var bookProduct = new Product("Book", 230.0, 10); 14 | var androidPhone = new Product("Android", 30000.0, 38); 15 | 16 | List products = new ArrayList<>(); 17 | products.add(iPhone); 18 | products.add(linuxLaptop); 19 | products.add(bookProduct); 20 | products.add(androidPhone); 21 | 22 | // Sort by prices - ASC 23 | // products.sort(Comparator.comparingDouble(Product::prices)); 24 | products.sort((e1, e2) -> Double.compare(e1.prices(), e2.prices())); 25 | // Collections.sort(products, Comparator.comparingDouble(Product::prices)); 26 | System.out.println(products); 27 | 28 | // Sort by prices - DESC 29 | products.sort((e1, e2) -> Double.compare(e2.prices(), e1.prices())); 30 | System.out.println(products); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/intermediate/collections/set/HashSetExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.set; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class HashSetExample { 7 | 8 | public static void main(String[] args) { 9 | // Set - Unique value purpose 10 | Set setOfInteger = new HashSet<>(); 11 | setOfInteger.add(22); 12 | setOfInteger.add(82); 13 | setOfInteger.add(86); 14 | setOfInteger.add(1); 15 | setOfInteger.add(5); 16 | setOfInteger.add(82); 17 | setOfInteger.add(86); 18 | 19 | System.out.println(setOfInteger); // Example: [1, 82, 5, 22, 86] - Unorder 20 | 21 | // O(1) 22 | if (setOfInteger.contains(6)) { 23 | System.out.println("Set contain 6"); 24 | } else { 25 | System.err.println("Set not contain 6"); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/intermediate/collections/set/LinkedHashSetExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.set; 2 | 3 | import java.util.LinkedHashSet; 4 | import java.util.Set; 5 | 6 | public class LinkedHashSetExample { 7 | 8 | public static void main(String[] args) { 9 | // LinkedHashSet - maintained order of element based on add order 10 | Set setOfInteger = new LinkedHashSet<>(); 11 | setOfInteger.add(22); 12 | setOfInteger.add(82); 13 | setOfInteger.add(86); 14 | setOfInteger.add(1); 15 | setOfInteger.add(5); 16 | setOfInteger.add(82); 17 | setOfInteger.add(86); 18 | 19 | System.out.println(setOfInteger); // Example: [22, 82, 86, 1, 5] Ordered result 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/intermediate/collections/set/TreeSetExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.collections.set; 2 | 3 | import java.util.TreeSet; 4 | 5 | public class TreeSetExample { 6 | 7 | public static void main(String[] args) { 8 | // TreeSet - Set that enable to search lower/greater 9 | TreeSet setOfInteger = new TreeSet<>(); 10 | setOfInteger.add(22); 11 | setOfInteger.add(82); 12 | setOfInteger.add(86); 13 | setOfInteger.add(1); 14 | setOfInteger.add(5); 15 | 16 | System.out.println(setOfInteger); // Sorted result 17 | System.out.println(setOfInteger.ceiling(20)); // 22 18 | System.out.println(setOfInteger.floor(20)); // 5 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/intermediate/generic/basic/GenericExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.generic.basic; 2 | 3 | import intermediate.generic.basic.generic.PrintWriter; 4 | 5 | public class GenericExample { 6 | /* 7 | * Generics allows us to create 8 | * a single class, interface, and method 9 | * that can be used with different types of data (objects) 10 | * Note: Generics does not work with primitive types -> Work with reference type 11 | * 12 | * == Pros == 13 | * 1. Code Reusability 14 | * 2. Compile-time Type Checking 15 | * 3. Used with Collections (I already shared you on collections package) 16 | * 17 | * Approach 18 | * - Generic Class (Bounded Types optional) 19 | * - Generic Method 20 | * */ 21 | public static void main(String[] args) { 22 | // Declare example - Generic class 23 | PrintWriter intPrintWriter = new PrintWriter<>(); 24 | intPrintWriter.print(9); 25 | 26 | var doublePrintWriter = new PrintWriter(); 27 | doublePrintWriter.print(10.0); 28 | 29 | PrintWriter productPrintWriter = new PrintWriter<>(); 30 | var iPhone = new Product("iPhone", 35000.0); 31 | productPrintWriter.print(iPhone); 32 | 33 | genericMethod(9); 34 | genericMethod(10.0); 35 | genericMethod(iPhone); 36 | } 37 | 38 | private static void genericMethod(T data) { 39 | System.out.println("Generic method"); 40 | System.out.println(data); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/intermediate/generic/basic/Product.java: -------------------------------------------------------------------------------- 1 | package intermediate.generic.basic; 2 | 3 | record Product(String name, double prices) { 4 | } 5 | -------------------------------------------------------------------------------- /src/intermediate/generic/basic/generic/PrintWriter.java: -------------------------------------------------------------------------------- 1 | package intermediate.generic.basic.generic; 2 | 3 | public class PrintWriter { 4 | 5 | public void print(T data) { 6 | System.out.println(data); 7 | } 8 | 9 | public String concat(T data) { 10 | return STR."Concat: \{data}"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/intermediate/generic/basic/nongeneric/DoublePrintWriter.java: -------------------------------------------------------------------------------- 1 | package intermediate.generic.basic.nongeneric; 2 | 3 | public class DoublePrintWriter { 4 | 5 | public void print(double data) { 6 | System.out.println(data); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/intermediate/generic/basic/nongeneric/IntPrintWriter.java: -------------------------------------------------------------------------------- 1 | package intermediate.generic.basic.nongeneric; 2 | 3 | public class IntPrintWriter { 4 | 5 | public void print(int data) { 6 | System.out.println(data); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/intermediate/generic/zoo/Animal.java: -------------------------------------------------------------------------------- 1 | package intermediate.generic.zoo; 2 | 3 | public interface Animal { 4 | 5 | String getName(); 6 | 7 | void setName(String name); 8 | } 9 | -------------------------------------------------------------------------------- /src/intermediate/generic/zoo/Enclosure.java: -------------------------------------------------------------------------------- 1 | package intermediate.generic.zoo; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Enclosure { 7 | 8 | private List members; 9 | 10 | public Enclosure() { 11 | this.members = new ArrayList<>(10); 12 | } 13 | 14 | public void addMember(T member) { 15 | this.members.add(member); 16 | } 17 | 18 | public List getAllNameOfMembers() { 19 | List result = new ArrayList<>(); 20 | for (var m : members) { 21 | result.add(m.getName()); 22 | } 23 | return result; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/intermediate/generic/zoo/Penguin.java: -------------------------------------------------------------------------------- 1 | package intermediate.generic.zoo; 2 | 3 | public class Penguin implements Animal { 4 | 5 | private String name; 6 | 7 | public Penguin(String name) { 8 | this.name = name; 9 | } 10 | 11 | @Override 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | @Override 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/intermediate/generic/zoo/Redpanda.java: -------------------------------------------------------------------------------- 1 | package intermediate.generic.zoo; 2 | 3 | public class Redpanda implements Animal { 4 | 5 | private String name; 6 | 7 | public Redpanda(String name) { 8 | this.name = name; 9 | } 10 | 11 | @Override 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | @Override 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/intermediate/generic/zoo/ZooMgmt.java: -------------------------------------------------------------------------------- 1 | package intermediate.generic.zoo; 2 | 3 | public class ZooMgmt { 4 | 5 | public static void main(String[] args) { 6 | Enclosure penguinEnclosure = new Enclosure<>(); 7 | penguinEnclosure.addMember(new Penguin("p1")); 8 | penguinEnclosure.addMember(new Penguin("p2")); 9 | penguinEnclosure.addMember(new Penguin("p3")); 10 | penguinEnclosure.addMember(new Penguin("p4")); 11 | 12 | Enclosure redpandaEnclosure = new Enclosure<>(); 13 | redpandaEnclosure.addMember(new Redpanda("r1")); 14 | redpandaEnclosure.addMember(new Redpanda("r2")); 15 | 16 | System.out.println(); 17 | System.out.println("Penguin members"); 18 | for (var p : penguinEnclosure.getAllNameOfMembers()) { 19 | System.out.println(p); 20 | } 21 | System.out.println(); 22 | System.out.println("Redpanda members"); 23 | for (var r : redpandaEnclosure.getAllNameOfMembers()) { 24 | System.out.println(r); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/intermediate/handleerror/Example1.java: -------------------------------------------------------------------------------- 1 | package intermediate.handleerror; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Example1 { 6 | 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | try { 10 | int opr1 = Integer.parseInt(scanner.nextLine()); 11 | int opr2 = Integer.parseInt(scanner.nextLine()); 12 | int answer = opr1 / opr2; 13 | System.out.println(answer); 14 | } catch (ArithmeticException e) { 15 | System.err.println("We got unexceptable value"); 16 | } catch (NumberFormatException e) { 17 | System.err.println("Some number cannot parse to number"); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/intermediate/handleerror/Example2.java: -------------------------------------------------------------------------------- 1 | package intermediate.handleerror; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Example2 { 6 | 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | try { 10 | int opr1 = Integer.parseInt(scanner.nextLine()); 11 | int opr2 = Integer.parseInt(scanner.nextLine()); 12 | int answer = opr1 / opr2; 13 | System.out.println(answer); 14 | } catch (Exception e) { 15 | System.err.println("Internal server error"); 16 | // if stop immediately after this catch 17 | // but you want to do something at last, use finally 18 | } finally { 19 | // Success or Fail, finally is executed 20 | System.out.println("Complete divide program"); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/intermediate/handleerror/ExampleError.java: -------------------------------------------------------------------------------- 1 | package intermediate.handleerror; 2 | 3 | public class ExampleError { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(factorial(5)); 7 | } 8 | 9 | private static int factorial(int n) { 10 | if (n <= 1) { 11 | return 1; 12 | } 13 | // WARNING: This is for generate critical error - StackOverflowError 14 | // Oh, I forgot to update condition 15 | return factorial(n) * n; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/intermediate/handleerror/stockmgt/DeductAmountException.java: -------------------------------------------------------------------------------- 1 | package intermediate.handleerror.stockmgt; 2 | 3 | public class DeductAmountException extends Exception { 4 | 5 | private static final String MESSAGE = "Deduct amount error"; 6 | 7 | public DeductAmountException() { 8 | super(MESSAGE); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/intermediate/handleerror/stockmgt/OutOfStockException.java: -------------------------------------------------------------------------------- 1 | package intermediate.handleerror.stockmgt; 2 | 3 | public class OutOfStockException extends Exception { 4 | 5 | public OutOfStockException(String message) { 6 | super(message); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/intermediate/handleerror/stockmgt/Product.java: -------------------------------------------------------------------------------- 1 | package intermediate.handleerror.stockmgt; 2 | 3 | public class Product { 4 | private String name; 5 | private int stock; 6 | 7 | public Product(String name, int stock) { 8 | this.name = name; 9 | this.stock = stock; 10 | } 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public void setName(String name) { 17 | this.name = name; 18 | } 19 | 20 | public int getStock() { 21 | return stock; 22 | } 23 | 24 | public void setStock(int stock) { 25 | this.stock = stock; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/intermediate/handleerror/stockmgt/StockManagementApp.java: -------------------------------------------------------------------------------- 1 | package intermediate.handleerror.stockmgt; 2 | 3 | import java.util.Scanner; 4 | 5 | public class StockManagementApp { 6 | 7 | private static final Product PRODUCT = new Product("Smartphone", 10); 8 | 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | String input = scanner.nextLine(); 12 | try { 13 | int amount = parseDeductAmount(input); 14 | purchase(PRODUCT, amount); 15 | } catch (Exception e) { 16 | System.err.println(e.getMessage()); 17 | } finally { 18 | System.out.println("Processed incoming request!"); 19 | } 20 | } 21 | 22 | private static void purchase(Product product, int amount) throws OutOfStockException { 23 | int currentAmount = product.getStock(); 24 | // Business logic condition handling 25 | if (currentAmount < amount) { 26 | throw new OutOfStockException(STR."The stock of \{product.getName()} is insufficient"); 27 | // Stop immediately 28 | } 29 | // Continue program 30 | var remain = product.getStock() - amount; 31 | product.setStock(remain); 32 | System.out.println(STR."Current stock for \{product.getName()}: \{product.getStock()}"); 33 | } 34 | 35 | private static int parseDeductAmount(String input) throws DeductAmountException { 36 | try { 37 | return Integer.parseInt(input); 38 | } catch (RuntimeException e) { 39 | // Custom exception from Java to another exception which we created by ourselves 40 | throw new DeductAmountException(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/intermediate/lambdaexpr/FuncInterfaceExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.lambdaexpr; 2 | 3 | public class FuncInterfaceExample { 4 | 5 | public static void main(String[] args) { 6 | // Declare anonymous class 7 | // new via interface and implement 8 | var declaredAnonymousClass = new MyFuncInterface() { 9 | @Override 10 | public double doubleValue(int n) { 11 | return n * 2; 12 | } 13 | }; 14 | System.out.println(declaredAnonymousClass.doubleValue(5)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/intermediate/lambdaexpr/LambdaExprExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.lambdaexpr; 2 | 3 | public class LambdaExprExample { 4 | 5 | public static void main(String[] args) { 6 | // (parameter list) example (a, b) 7 | // -> create function/method 8 | // {} Lambda/Method body 9 | 10 | // () -> {} // 0 argument 11 | // (a) -> {} // 1 argument 12 | // (a,b) -> {} // 2 arguments 13 | MyFuncInterface declaredLambdaExpression = (n) -> { 14 | System.out.println(STR."Received: \{n}"); 15 | return n * 2; 16 | }; 17 | System.out.println(declaredLambdaExpression.doubleValue(5)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/intermediate/lambdaexpr/MyFuncInterface.java: -------------------------------------------------------------------------------- 1 | package intermediate.lambdaexpr; 2 | 3 | @FunctionalInterface 4 | public interface MyFuncInterface { 5 | 6 | // Java Interface contains one and only one abstract method 7 | double doubleValue(int n); 8 | } 9 | -------------------------------------------------------------------------------- /src/intermediate/lambdaexpr/SpeakApp.java: -------------------------------------------------------------------------------- 1 | package intermediate.lambdaexpr; 2 | 3 | public class SpeakApp { 4 | 5 | public static void main(String[] args) { 6 | var mart = new Person("Mart"); 7 | // shout(mart, (person) -> { 8 | // System.out.println(STR."Hello! My name is \{person.name()}"); 9 | // }); 10 | Speakable methodBody = (person) -> { 11 | System.out.println(STR."Hello! My name is \{person.name()}"); 12 | }; 13 | shout(mart, methodBody); 14 | } 15 | 16 | private static void shout(Person person, Speakable speakable) { 17 | speakable.speak(person); 18 | } 19 | 20 | private record Person(String name) { 21 | } 22 | 23 | @FunctionalInterface 24 | private interface Speakable { 25 | void speak(Person person); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/intermediate/stream/StreamExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.stream; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | import java.util.function.Function; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.IntStream; 8 | import java.util.stream.Stream; 9 | 10 | public class StreamExample { 11 | 12 | public static void main(String[] args) { 13 | // Wrapper class of primitive type stream 14 | List integerList = List.of(1, 4, 5, 7, 8, 9, 3, 2, 6, 0); 15 | Stream integerStream = integerList.stream(); 16 | var multiply2Stream = integerStream.map(n -> n * 2) 17 | .filter(n -> n % 10 == 0) // [10,0] 18 | .toList(); 19 | System.out.println(multiply2Stream); 20 | 21 | // Alternative 22 | var intStream = IntStream.of(1, 4, 5, 7, 8, 9, 3, 2, 6, 0); 23 | var avg = intStream.average() 24 | .orElseThrow(() -> new RuntimeException("Error")); 25 | System.out.println(avg); 26 | 27 | var fruitStream = Stream.of( 28 | "apple", 29 | "banana", 30 | "melon", 31 | "apple", 32 | "banana", 33 | "apple" 34 | ); 35 | var countFrequency = fruitStream.collect( 36 | Collectors.groupingBy(Function.identity(), Collectors.counting()) 37 | ); 38 | System.out.println(countFrequency); 39 | 40 | 41 | List students = List.of( 42 | new Student("Mart", 'D'), 43 | new Student("Peter", 'A'), 44 | new Student("Taylor", 'B'), 45 | new Student("Jose", 'C'), 46 | new Student("Brook", 'B'), 47 | new Student("Kathy", 'A') 48 | ); 49 | 50 | // Filter only A - B => Show as HashMap 51 | var interestGrade = Set.of('A', 'B'); 52 | var result = students.stream() 53 | .filter(s -> interestGrade.contains(s.grade)) 54 | .collect(Collectors.groupingBy(s -> s.grade)); 55 | System.out.println(result); 56 | } 57 | 58 | private record Student(String name, char grade) { 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/intermediate/thread/basic/Constant.java: -------------------------------------------------------------------------------- 1 | package intermediate.thread.basic; 2 | 3 | public class Constant { 4 | 5 | private static final String PREFIX = "custom"; 6 | 7 | public static String getThreadId(String id) { 8 | return STR."\{PREFIX}-\{id}"; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/intermediate/thread/basic/CustomRunnable.java: -------------------------------------------------------------------------------- 1 | package intermediate.thread.basic; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class CustomRunnable implements Runnable { 6 | 7 | private final String id; 8 | 9 | public CustomRunnable(String id) { 10 | this.id = id; 11 | } 12 | 13 | @Override 14 | public void run() { 15 | IntStream.range(0, 10) 16 | .forEach((_) -> { 17 | try { 18 | Thread.sleep(500); 19 | } catch (InterruptedException e) { 20 | throw new RuntimeException(e); 21 | } 22 | System.out.print(id); 23 | }); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/intermediate/thread/basic/CustomThread.java: -------------------------------------------------------------------------------- 1 | package intermediate.thread.basic; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class CustomThread extends Thread { 6 | 7 | private final String id; 8 | 9 | public CustomThread(String id) { 10 | super(Constant.getThreadId(id)); 11 | this.id = id; 12 | } 13 | 14 | @Override 15 | public void run() { 16 | IntStream.range(0, 10) 17 | .forEach((_) -> { 18 | try { 19 | Thread.sleep(500); 20 | } catch (InterruptedException e) { 21 | throw new RuntimeException(e); 22 | } 23 | System.out.print(id); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/intermediate/thread/basic/ThreadExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.thread.basic; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class ThreadExample { 6 | 7 | // Main thread 8 | public static void main(String[] args) { 9 | // New - extend class 10 | var customThread = new CustomThread(String.valueOf(1)); 11 | // New - implement from Runnable 12 | var customRunnableForThread = 13 | new CustomRunnable(String.valueOf(2)); 14 | var customThreadFromRunnable = new Thread(customRunnableForThread); 15 | // customThreadFromLambdaExpression 16 | Runnable lambda = () -> { 17 | IntStream.range(0, 10) 18 | .forEach((_) -> { 19 | try { 20 | Thread.sleep(1000); 21 | } catch (InterruptedException e) { 22 | throw new RuntimeException(e); 23 | } 24 | System.out.print(3); 25 | }); 26 | }; 27 | var customThreadFromLambdaExpr = new Thread(lambda); 28 | 29 | // Start 30 | customThread.start(); 31 | customThreadFromRunnable.start(); 32 | 33 | customThreadFromLambdaExpr.setDaemon(true); 34 | customThreadFromLambdaExpr.start(); 35 | 36 | System.out.println(customThread.isDaemon()); 37 | System.out.println(customThreadFromRunnable.isDaemon()); 38 | System.out.println(customThreadFromLambdaExpr.isDaemon()); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/intermediate/thread/concurrency/ConcurrencyExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.thread.concurrency; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | import java.util.concurrent.Executors; 6 | 7 | public class ConcurrencyExample { 8 | 9 | private static final Random random = new Random(); 10 | 11 | public static void main(String[] args) { 12 | var shop = new GrilledParkShop(10); 13 | var es = Executors.newFixedThreadPool(3); 14 | List porkModifiableList = List.of( 15 | new Consumer("c1"), 16 | new Consumer("c2"), 17 | new Merchant(), 18 | new Consumer("c3") 19 | ); 20 | for (var gpm : porkModifiableList) { 21 | es.submit(() -> { 22 | try { 23 | gpm.modify(shop, randomAmount()); 24 | } catch (InterruptedException e) { 25 | throw new RuntimeException(e); 26 | } 27 | }); 28 | } 29 | es.shutdown(); 30 | } 31 | 32 | private static int randomAmount() { 33 | return random.nextInt(3) + 1; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/intermediate/thread/concurrency/Consumer.java: -------------------------------------------------------------------------------- 1 | package intermediate.thread.concurrency; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | public class Consumer implements GrilledPorkModifiable { 6 | 7 | private final String name; 8 | 9 | public Consumer(String name) { 10 | this.name = name; 11 | } 12 | 13 | @Override 14 | public void modify(GrilledParkShop shop, int n) throws InterruptedException { 15 | synchronized (shop.getLock()) { 16 | var amount = shop.getGrilledPorkAmount(); 17 | if (n > amount) { 18 | throw new RuntimeException("Out of stock!"); 19 | } 20 | TimeUnit.SECONDS.sleep(1); 21 | shop.setGrilledPorkAmount(amount - n); 22 | System.out.println(STR."[C] Current pork: \{shop.getGrilledPorkAmount()}"); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/intermediate/thread/concurrency/GrilledParkShop.java: -------------------------------------------------------------------------------- 1 | package intermediate.thread.concurrency; 2 | 3 | public class GrilledParkShop { 4 | 5 | private final Lock lock; 6 | private int grilledPorkAmount; 7 | 8 | public GrilledParkShop(int grilledPorkAmount) { 9 | this.grilledPorkAmount = grilledPorkAmount; 10 | this.lock = new Lock(); 11 | } 12 | 13 | public Lock getLock() { 14 | return lock; 15 | } 16 | 17 | public int getGrilledPorkAmount() { 18 | synchronized(lock) { 19 | return grilledPorkAmount; 20 | } 21 | } 22 | 23 | public void setGrilledPorkAmount(int grilledPorkAmount) { 24 | synchronized (lock) { 25 | this.grilledPorkAmount = grilledPorkAmount; 26 | } 27 | } 28 | 29 | private static class Lock {} 30 | } 31 | -------------------------------------------------------------------------------- /src/intermediate/thread/concurrency/GrilledPorkModifiable.java: -------------------------------------------------------------------------------- 1 | package intermediate.thread.concurrency; 2 | 3 | public interface GrilledPorkModifiable { 4 | 5 | void modify(GrilledParkShop shop, int n) throws InterruptedException; 6 | } 7 | -------------------------------------------------------------------------------- /src/intermediate/thread/concurrency/Merchant.java: -------------------------------------------------------------------------------- 1 | package intermediate.thread.concurrency; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | public class Merchant implements GrilledPorkModifiable { 6 | 7 | @Override 8 | public void modify(GrilledParkShop shop, int n) throws InterruptedException { 9 | synchronized (shop.getLock()) { 10 | var amount = shop.getGrilledPorkAmount(); 11 | TimeUnit.SECONDS.sleep(2); 12 | shop.setGrilledPorkAmount(amount + n); 13 | System.out.println(STR."[M] Current pork: \{shop.getGrilledPorkAmount()}"); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/intermediate/thread/executor/ExecutorExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.thread.executor; 2 | 3 | import java.util.concurrent.*; 4 | import java.util.stream.IntStream; 5 | 6 | public class ExecutorExample { 7 | 8 | public static void main(String[] args) { 9 | try (ExecutorService es = Executors.newSingleThreadExecutor()) { 10 | es.submit(() -> IntStream.range(0, 10) 11 | .forEach((_) -> { 12 | try { 13 | Thread.sleep(500); 14 | } catch (InterruptedException e) { 15 | throw new RuntimeException(e); 16 | } 17 | System.out.print(1); 18 | })); 19 | } 20 | // Thread Pool 21 | var poolSize = 10; 22 | try (var es = Executors.newFixedThreadPool(poolSize)) { 23 | IntStream.range(0, 20) 24 | .forEach(n -> { 25 | es.submit(() -> { 26 | try { 27 | Thread.sleep(2000); 28 | } catch (InterruptedException e) { 29 | throw new RuntimeException(e); 30 | } 31 | System.out.print(STR." \{n} "); 32 | }); 33 | }); 34 | } 35 | 36 | try (var es = Executors.newVirtualThreadPerTaskExecutor()) { 37 | IntStream.range(0, 20) 38 | .forEach(n -> { 39 | es.submit(() -> { 40 | try { 41 | Thread.sleep(2000); 42 | } catch (InterruptedException e) { 43 | throw new RuntimeException(e); 44 | } 45 | System.out.print(STR." \{n} "); 46 | }); 47 | }); 48 | } 49 | 50 | Callable callableTask = () -> { 51 | // Thread.sleep(3000); 52 | TimeUnit.SECONDS.sleep(3); 53 | return new Person(1, "Mart"); 54 | }; 55 | 56 | try (var es = Executors.newVirtualThreadPerTaskExecutor()) { 57 | Future result = es.submit(callableTask); 58 | var person = result.get(); 59 | System.out.println(person); 60 | } catch (ExecutionException | InterruptedException e) { 61 | throw new RuntimeException(e); 62 | } 63 | 64 | } 65 | 66 | private record Person(int id, String name) { 67 | 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/intermediate/thread/virtualthread/PlatformThreadExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.thread.virtualthread; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class PlatformThreadExample { 6 | 7 | public static void main(String[] args) { 8 | Thread.ofPlatform().start(() -> { 9 | IntStream.range(0, 10) 10 | .forEach((_) -> { 11 | try { 12 | Thread.sleep(500); 13 | } catch (InterruptedException e) { 14 | throw new RuntimeException(e); 15 | } 16 | System.out.print(3); 17 | }); 18 | }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/intermediate/thread/virtualthread/VirtualThreadExample.java: -------------------------------------------------------------------------------- 1 | package intermediate.thread.virtualthread; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class VirtualThreadExample { 6 | 7 | public static void main(String[] args) throws InterruptedException { 8 | var thread = Thread.ofVirtual().start(() -> { 9 | IntStream.range(0, 10) 10 | .forEach((_) -> { 11 | try { 12 | Thread.sleep(500); 13 | } catch (InterruptedException e) { 14 | throw new RuntimeException(e); 15 | } 16 | System.out.print(3); 17 | }); 18 | }); 19 | var alternativeStartVirtualThread = Thread.startVirtualThread(() -> { 20 | IntStream.range(0, 10) 21 | .forEach((_) -> { 22 | try { 23 | Thread.sleep(800); 24 | } catch (InterruptedException e) { 25 | throw new RuntimeException(e); 26 | } 27 | System.out.print(4); 28 | }); 29 | }); 30 | 31 | thread.join(); 32 | alternativeStartVirtualThread.join(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/mostusedinterview/ArrayForInterview.java: -------------------------------------------------------------------------------- 1 | package mostusedinterview; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class ArrayForInterview { 7 | 8 | public static void main(String[] args) { 9 | // T[] variableName = new T[N] // T: data type, N: static size 10 | // array of primitive -> value is default 11 | // array of reference type -> value initial by null 12 | int[] data = new int[20]; 13 | System.out.println(Arrays.toString(data)); 14 | // Manipulate -> index 15 | int index = 0; 16 | data[index] = 5; // O(1) 17 | System.out.println(Arrays.toString(data)); 18 | 19 | String[] names = {"Mart", "TP", "Coder"}; 20 | System.out.println(names.length); 21 | 22 | int[] data2 = new int[20]; 23 | Arrays.fill(data2, 1); 24 | System.out.println(Arrays.toString(data2)); 25 | 26 | int[] numbers = new int[8]; 27 | numbers[0] = 5; 28 | numbers[1] = 9; 29 | numbers[2] = 4; 30 | numbers[3] = 2; 31 | numbers[4] = 1; 32 | numbers[5] = 0; 33 | numbers[6] = 7; 34 | numbers[7] = 8; 35 | System.out.println("==Before Sort=="); 36 | System.out.println(Arrays.toString(numbers)); 37 | Arrays.sort(numbers); // O(n log(n)) 38 | System.out.println("==After Sort=="); 39 | System.out.println(Arrays.toString(numbers)); 40 | // DESC -> Primitive -> reverse by ourselves 41 | var numbersBoxType = Arrays.stream(numbers) 42 | .boxed() 43 | .toList() 44 | .toArray(new Integer[0]); 45 | Arrays.sort(numbersBoxType, (a, b) -> Integer.compare(b, a)); 46 | System.out.println(Arrays.toString(numbersBoxType)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/mostusedinterview/ListForInterview.java: -------------------------------------------------------------------------------- 1 | package mostusedinterview; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class ListForInterview { 8 | 9 | public static void main(String[] args) { 10 | // Definition 11 | List names = new ArrayList<>(); 12 | List personList = new ArrayList<>(); 13 | var mart = new Person("Mart"); 14 | // Insertion - 1 15 | names.add("Mart"); 16 | personList.add(mart); 17 | System.out.println(names); 18 | System.out.println(personList); 19 | 20 | System.out.println(); 21 | 22 | List newUsers = List.of( 23 | "Toby", 24 | "Poppy", 25 | "Elf" 26 | ); 27 | // Insertion many (all) 28 | names.addAll(newUsers); 29 | // Insertion on the index 30 | names.add(3, "Amily"); 31 | personList.add(new Person("Amily")); 32 | System.out.println(names); 33 | 34 | // Insertion .add() - TC: O(1) 35 | // Insertion many/index - TC: O(n) 36 | 37 | // Remove - TC: O(n) 38 | names.remove("Toby"); 39 | System.out.println(names); 40 | personList.remove(mart); 41 | System.out.println(personList); 42 | // Remove multiple 43 | personList.removeAll(List.of(new Person("Amily"))); 44 | // Clear 45 | personList.clear(); // TC: O(1) 46 | 47 | System.out.println(); 48 | 49 | System.out.println(names); 50 | System.out.println(personList); 51 | 52 | var isPoppyInList = names.contains("Poppy"); 53 | System.out.println(STR."isPoppyInList: \{isPoppyInList}"); 54 | 55 | System.out.println(); 56 | // Copy from immutable to mutable format 57 | var numberList = new ArrayList<>(List.of(84, 7, 5, 8, 867, 54, 68, 51, 54)); 58 | // Sorting -> TC: O(n log n) 59 | numberList.sort((e1, e2) -> Integer.compare(e1, e2)); // ASC 60 | System.out.println(numberList); 61 | // What if DESC? 62 | // numberList.sort((e1, e2) -> Integer.compare(e2, e1)); 63 | numberList.sort(Collections.reverseOrder()); 64 | System.out.println(numberList); 65 | 66 | List statList = new ArrayList<>( 67 | List.of( 68 | new Stat(1, 8), 69 | new Stat(2, 5), 70 | new Stat(3, 10), 71 | new Stat(4, 9) 72 | ) 73 | ); 74 | System.out.println(statList); 75 | System.out.println(); 76 | statList.sort((e1, e2) -> Integer.compare(e2.overall, e1.overall)); 77 | System.out.println(statList); 78 | 79 | // Stream API Example 80 | // Event time - Overall stat * 3 81 | // Expectation -> Hire only 2 with overall base stat over 5 82 | var result = statList.stream() 83 | .filter(s -> s.overall > 5) 84 | .map(s -> new Stat(s.playerId, s.overall * 3)) 85 | // Hire only 2 -> Pick best 2 86 | .sorted((e1, e2) -> Integer.compare(e2.overall, e1.overall)) // DESC 87 | .limit(2) 88 | .toList(); 89 | var iterator = result.iterator(); 90 | while (iterator.hasNext()) { 91 | System.out.println(iterator.next()); 92 | } 93 | } 94 | 95 | private record Person(String name) { 96 | 97 | } 98 | 99 | private record Stat(int playerId, int overall) { 100 | 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/mostusedinterview/MapForInterview.java: -------------------------------------------------------------------------------- 1 | package mostusedinterview; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.PriorityQueue; 6 | import java.util.Set; 7 | 8 | public class MapForInterview { 9 | 10 | // HashTable -> Key, Value mapping 11 | // Purpose: Fast retrieve data 12 | // Technique: In-Memory database for your question 13 | 14 | public static void main(String[] args) { 15 | // Student Table 16 | // Id -> Student 17 | Map studentTable = new HashMap<>(); 18 | var mart = new Student(1, "Mart"); 19 | studentTable.put(mart.id, mart); 20 | System.out.println(studentTable.get(1)); // TC: O(1) 21 | // Check if key exists then access 22 | if (studentTable.containsKey(4)) { 23 | System.out.println(studentTable.get(4)); 24 | } 25 | 26 | // PriorityQueue + HashMap -> Character Frequency 27 | // Find the most frequency of character on message 28 | String message = "A&^C9AD9y(*^&(*$@&*()@uU8uAU09ud09asudl"; 29 | Map freqMap = new HashMap<>(); 30 | for (char c : message.toCharArray()) { 31 | // if (!freqMap.containsKey(c)) { 32 | // // If not exists default 33 | // freqMap.put(c, 0); 34 | // } 35 | freqMap.putIfAbsent(c, 0); 36 | freqMap.put(c, freqMap.get(c) + 1); 37 | } 38 | Set> entrySet = freqMap.entrySet(); 39 | // Max Heap 40 | PriorityQueue> pq = new PriorityQueue<>( 41 | (e1, e2) -> Integer.compare(e2.getValue(), e1.getValue()) 42 | ); 43 | pq.addAll(entrySet); 44 | 45 | while (!pq.isEmpty()) { 46 | var entry = pq.poll(); 47 | System.out.println(STR."\{entry.getKey()} -> \{entry.getValue()}"); 48 | } 49 | } 50 | 51 | private record Student(int id, String name) { 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/mostusedinterview/PriorityQueueForInterview.java: -------------------------------------------------------------------------------- 1 | package mostusedinterview; 2 | 3 | import java.util.Comparator; 4 | import java.util.PriorityQueue; 5 | 6 | public class PriorityQueueForInterview { 7 | 8 | // PriorityQueue -> Queue with condition 9 | // -> expectation element meet most condition -> Dequeue first 10 | 11 | // Example - Member - Rank Bronze, Silver, Gold, Platinum 12 | // -> Platinum, Gold, Silver, Bronze 13 | // -> Bronze, Silver, Gold, Platinum 14 | 15 | // Offer -> TC: O(log (n)) (Enqueue) 16 | // Poll -> TC: O(log (n)) (Dequeue) 17 | // Peek (see front element) -> TC: O(1) 18 | 19 | // PriorityQueue can implement Min Heap & Max Heap 20 | public static void main(String[] args) { 21 | // Design example with Max Heap 22 | PriorityQueue maxHeap = new PriorityQueue<>( 23 | (e1, e2) -> Integer.compare(e2.type.ranking, e1.type.ranking) 24 | ); 25 | maxHeap.offer(new Member("Mart", Type.SILVER)); 26 | maxHeap.offer(new Member("Molly", Type.GOLD)); 27 | maxHeap.offer(new Member("Joshua", Type.BRONZE)); 28 | maxHeap.offer(new Member("Peter", Type.GOLD)); 29 | 30 | while (!maxHeap.isEmpty()) { 31 | var current = maxHeap.poll(); 32 | System.out.println(current); 33 | } 34 | 35 | PriorityQueue minHeap = new PriorityQueue<>( 36 | Comparator.comparingInt(e -> e.type.ranking) 37 | ); 38 | minHeap.offer(new Member("Mart", Type.SILVER)); 39 | minHeap.offer(new Member("Molly", Type.GOLD)); 40 | minHeap.offer(new Member("Joshua", Type.BRONZE)); 41 | minHeap.offer(new Member("Peter", Type.GOLD)); 42 | 43 | while (!minHeap.isEmpty()) { 44 | var current = minHeap.poll(); 45 | System.out.println(current); 46 | } 47 | } 48 | 49 | private record Member(String name, Type type) { 50 | } 51 | 52 | private enum Type { 53 | BRONZE(1), 54 | SILVER(2), 55 | GOLD(3), 56 | PLATINUM(4); 57 | 58 | private final int ranking; 59 | 60 | Type(int ranking) { 61 | this.ranking = ranking; 62 | } 63 | 64 | public int getRanking() { 65 | return this.ranking; 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/mostusedinterview/QueueForInterview.java: -------------------------------------------------------------------------------- 1 | package mostusedinterview; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | public class QueueForInterview { 7 | 8 | /* 9 | Queue - First-In-First-Out (FIFO) 10 | 11 | Offer (insertion from tail) -> TC: O(1) (Enqueue) 12 | Poll (remove front element) -> TC: O(1) (Dequeue) 13 | Peek (see front element) -> TC: O(1) 14 | * */ 15 | public static void main(String[] args) { 16 | Queue queue = new LinkedList<>(); 17 | // LinkedList queue = new LinkedList<>(); 18 | queue.offer(new Person("Mart")); 19 | queue.offer(new Person("Jame")); 20 | queue.offer(new Person("Torres")); 21 | queue.offer(new Person("Steven")); 22 | System.out.println(queue); 23 | System.out.println(queue.peek()); 24 | var frontOfQueue = queue.poll(); 25 | System.out.println(frontOfQueue); 26 | System.out.println(queue); 27 | 28 | while (!queue.isEmpty()) { 29 | var person = queue.poll(); 30 | System.out.println(person); 31 | } 32 | } 33 | 34 | private record Person(String name) { 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/mostusedinterview/SetForInterview.java: -------------------------------------------------------------------------------- 1 | package mostusedinterview; 2 | 3 | import java.util.HashSet; 4 | import java.util.List; 5 | import java.util.Set; 6 | 7 | public class SetForInterview { 8 | 9 | // HashSet -> Handling case of unique or duplicate detection 10 | // Most operation from HashSet -> O(1) 11 | public static void main(String[] args) { 12 | var input = List.of(7, 3, 4, 8, 1, 2, 7, 3, 4, 5, 7, 1, 3, 8); 13 | Set integerSet = new HashSet<>(input); 14 | // Remaining unique element 15 | System.out.println(integerSet); 16 | 17 | System.out.println(STR."isContainDuplicate: \{isContainDuplicate(input)}"); 18 | } 19 | 20 | private static boolean isContainDuplicate(List input) { 21 | boolean isDuplicate = false; 22 | Set seen = new HashSet<>(); 23 | for (var n : input) { 24 | if (seen.contains(n)) { 25 | return true; 26 | } 27 | seen.add(n); 28 | } 29 | return isDuplicate; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/mostusedinterview/StackForInterview.java: -------------------------------------------------------------------------------- 1 | package mostusedinterview; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | 6 | public class StackForInterview { 7 | 8 | /* Stack - Last-In-First-Out (LIFO) 9 | Push (insertion) -> TC: O(1) 10 | Pop (remove top element) -> TC: O(1) 11 | Peek (see top element) -> TC: O(1) 12 | 13 | [Book4] <- Access top - PEEK 14 | [Book3] 15 | [Book2] 16 | [Book1] [Book5] < POP 17 | * */ 18 | 19 | public static void main(String[] args) { 20 | Deque stack = new ArrayDeque<>(); 21 | var book1 = new Book("Book1"); 22 | var book2 = new Book("Book2"); 23 | var book3 = new Book("Book3"); 24 | var book4 = new Book("Book4"); 25 | var book5 = new Book("Book5"); 26 | 27 | System.out.println(); 28 | stack.push(book1); // Example push 29 | System.out.println(stack); 30 | stack.push(book2); 31 | System.out.println(stack); 32 | var book2Pop = stack.pollFirst(); 33 | System.out.println(book2Pop); 34 | System.out.println(stack); 35 | stack.push(book3); 36 | stack.push(book4); 37 | stack.push(book5); 38 | System.out.println(stack); 39 | 40 | while (!stack.isEmpty()) { 41 | var book = stack.pollFirst(); 42 | System.out.println(book); 43 | } 44 | System.out.println(STR."Stack is empty: \{stack.isEmpty()}"); 45 | } 46 | 47 | private record Book(String title) { 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/mostusedinterview/StringForInterview.java: -------------------------------------------------------------------------------- 1 | package mostusedinterview; 2 | 3 | import java.util.Arrays; 4 | 5 | public class StringForInterview { 6 | 7 | public static void main(String[] args) { 8 | // Definition 9 | String bookName = "Platform Engineering on Kubernetes with Java"; 10 | // String.valueOf -> Primitive to String 11 | String alternativeBookName1 = new String(String.valueOf(5)); 12 | String alternativeBookName2 = String.valueOf(5); 13 | 14 | // How long of the text? 15 | int sizeOfMessage = bookName.length(); // TC: O(1) 16 | System.out.println(sizeOfMessage); 17 | 18 | // Convert to char array 19 | char[] bookNameChars = bookName.toCharArray(); // TC: O(n) 20 | System.out.println(bookNameChars); 21 | 22 | // Lowercase, Uppercase 23 | String uppercaseName = bookName.toUpperCase(); // TC: O(n) 24 | String lowercaseName = bookName.toLowerCase(); // TC: O(n) 25 | System.out.println(uppercaseName); 26 | System.out.println(lowercaseName); 27 | 28 | // Access on specific index 29 | // If you give index to large -> it can throw IndexOutOfBoundException 30 | char selectedChar = bookName.charAt(4); // TC: O(1) 31 | System.out.println(selectedChar); 32 | 33 | // Substring 34 | System.out.println(bookName.substring(15)); // TC: O(n) 35 | System.out.println(bookName.substring(15, 18)); // TC: O(n) 36 | 37 | // Replace 38 | String newTitle = bookName.replace("Java", "Rust"); 39 | System.out.println(newTitle); 40 | 41 | String exampleData = "YWFz4ZG15FzZG565FzZGF4zZ4G5FkYX3NkCg=="; 42 | for (var c : exampleData.toCharArray()) { 43 | System.out.println(); 44 | System.out.println(c); 45 | System.out.println(Character.isLetter(c)); 46 | System.out.println(Character.isUpperCase(c)); 47 | System.out.println(Character.isDigit(c)); 48 | System.out.println(Character.isLetterOrDigit(c)); 49 | } 50 | 51 | String exampleMessage = "asjkdfhjkashdjkladf"; 52 | int[] counter = new int[26]; 53 | // Play with character index 54 | // 'a' = 0 55 | // 'a' - 'a' = 0 56 | // 'c' - 'a' = 2 57 | for (char c : exampleMessage.toCharArray()) { 58 | int distant = c - 'a'; 59 | counter[distant]++; 60 | } 61 | System.out.println(Arrays.toString(counter)); 62 | // Convert index back to character 63 | for (int i = 0; i < counter.length; i++) { 64 | char c = (char) ('a' + i); 65 | System.out.println(c + ":" + counter[i]); 66 | } 67 | 68 | // String - Immutable 69 | // If you want to make it mutable, Organize with StringBuilder 70 | // and then create String 71 | String firstName = "Thanaphoom"; 72 | String lastName = "Babparn"; 73 | String fullNameWithPlusConcat = firstName + " " + lastName; // Concatenation -> O(n) 74 | 75 | StringBuilder sb = new StringBuilder(); 76 | sb.append(firstName); // O(1) 77 | sb.append(" "); 78 | sb.append(lastName); 79 | String fullNameWithStringBuilder = sb.toString(); 80 | 81 | // Preview -> JDK 21 82 | System.out.println(STR."\{firstName} \{lastName}"); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/oop/abstractioninterface/abstraction/Car.java: -------------------------------------------------------------------------------- 1 | package oop.abstractioninterface.abstraction; 2 | 3 | abstract class Car { 4 | 5 | private String color; 6 | private int speed; 7 | 8 | public String getColor() { 9 | return this.color; 10 | } 11 | 12 | // declare default to abstract 13 | public void spray(String color) { 14 | this.color = color; 15 | } 16 | 17 | public int getSpeed() { 18 | return speed; 19 | } 20 | 21 | public void setSpeed(int speed) { 22 | this.speed = speed; 23 | } 24 | 25 | abstract void speedUp(int speed); 26 | abstract void slowDown(int speed); 27 | abstract void turnLeft(); 28 | abstract void turnRight(); 29 | } 30 | -------------------------------------------------------------------------------- /src/oop/abstractioninterface/abstraction/ElectricCar.java: -------------------------------------------------------------------------------- 1 | package oop.abstractioninterface.abstraction; 2 | 3 | class ElectricCar extends Car { 4 | 5 | @Override 6 | void speedUp(int speed) { 7 | this.setSpeed(this.getSpeed() + speed); 8 | } 9 | 10 | @Override 11 | void slowDown(int speed) { 12 | this.setSpeed(this.getSpeed() - speed); 13 | } 14 | 15 | @Override 16 | void turnLeft() { 17 | System.out.println("ElectricCar turn left"); 18 | } 19 | 20 | @Override 21 | void turnRight() { 22 | System.out.println("ElectricCar turn right"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/oop/abstractioninterface/abstraction/Main.java: -------------------------------------------------------------------------------- 1 | package oop.abstractioninterface.abstraction; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | Car petrolCar = new PetrolCar(); 7 | petrolCar.spray("RED"); 8 | petrolCar.turnLeft(); 9 | 10 | Car electricCar = new ElectricCar(); 11 | electricCar.spray("BLACK"); 12 | electricCar.turnRight(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/oop/abstractioninterface/abstraction/PetrolCar.java: -------------------------------------------------------------------------------- 1 | package oop.abstractioninterface.abstraction; 2 | 3 | class PetrolCar extends Car { 4 | 5 | @Override 6 | void speedUp(int speed) { 7 | this.setSpeed(this.getSpeed() + speed); 8 | } 9 | 10 | @Override 11 | void slowDown(int speed) { 12 | this.setSpeed(this.getSpeed() - speed); 13 | } 14 | 15 | @Override 16 | void turnLeft() { 17 | System.out.println("PetrolCar turn left"); 18 | } 19 | 20 | @Override 21 | void turnRight() { 22 | System.out.println("PetrolCar turn right"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/oop/abstractioninterface/interfaceexample/Car.java: -------------------------------------------------------------------------------- 1 | package oop.abstractioninterface.interfaceexample; 2 | 3 | abstract class Car implements ChangeSpeed, Turn { 4 | 5 | private String color; 6 | private int speed; 7 | 8 | public String getColor() { 9 | return this.color; 10 | } 11 | 12 | // declare default to abstract 13 | public void spray(String color) { 14 | this.color = color; 15 | } 16 | 17 | public int getSpeed() { 18 | return speed; 19 | } 20 | 21 | public void setSpeed(int speed) { 22 | this.speed = speed; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/oop/abstractioninterface/interfaceexample/ChangeSpeed.java: -------------------------------------------------------------------------------- 1 | package oop.abstractioninterface.interfaceexample; 2 | 3 | interface ChangeSpeed { 4 | void speedUp(int speed); 5 | void slowDown(int speed); 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/abstractioninterface/interfaceexample/ElectricCar.java: -------------------------------------------------------------------------------- 1 | package oop.abstractioninterface.interfaceexample; 2 | 3 | class ElectricCar extends Car { 4 | 5 | @Override 6 | public void speedUp(int speed) { 7 | this.setSpeed(this.getSpeed() + speed); 8 | } 9 | 10 | @Override 11 | public void slowDown(int speed) { 12 | this.setSpeed(this.getSpeed() - speed); 13 | } 14 | 15 | @Override 16 | public void turnLeft() { 17 | System.out.println("ElectricCar turn left"); 18 | } 19 | 20 | @Override 21 | public void turnRight() { 22 | System.out.println("ElectricCar turn right"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/oop/abstractioninterface/interfaceexample/Main.java: -------------------------------------------------------------------------------- 1 | package oop.abstractioninterface.interfaceexample; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | Car petrolCar = new PetrolCar(); 7 | petrolCar.spray("RED"); 8 | petrolCar.turnLeft(); 9 | 10 | Car electricCar = new ElectricCar(); 11 | electricCar.spray("BLACK"); 12 | electricCar.turnRight(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/oop/abstractioninterface/interfaceexample/PetrolCar.java: -------------------------------------------------------------------------------- 1 | package oop.abstractioninterface.interfaceexample; 2 | 3 | class PetrolCar extends Car { 4 | 5 | @Override 6 | public void speedUp(int speed) { 7 | this.setSpeed(this.getSpeed() + speed); 8 | } 9 | 10 | @Override 11 | public void slowDown(int speed) { 12 | this.setSpeed(this.getSpeed() - speed); 13 | } 14 | 15 | @Override 16 | public void turnLeft() { 17 | System.out.println("PetrolCar turn left"); 18 | } 19 | 20 | @Override 21 | public void turnRight() { 22 | System.out.println("PetrolCar turn right"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/oop/abstractioninterface/interfaceexample/Turn.java: -------------------------------------------------------------------------------- 1 | package oop.abstractioninterface.interfaceexample; 2 | 3 | interface Turn { 4 | void turnLeft(); 5 | void turnRight(); 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/aggregation/Main.java: -------------------------------------------------------------------------------- 1 | package oop.aggregation; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | Racket racket = new Racket("DDD", 3.2); 7 | TennisPlayer player = new TennisPlayer("Mart", racket); 8 | System.out.println(STR."\{player.getName()} has a \{racket}"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/oop/aggregation/Racket.java: -------------------------------------------------------------------------------- 1 | package oop.aggregation; 2 | 3 | public class Racket { 4 | 5 | private String brand; 6 | private double weight; 7 | 8 | public Racket(String brand, double weight) { 9 | this.brand = brand; 10 | this.weight = weight; 11 | } 12 | 13 | public String getBrand() { 14 | return brand; 15 | } 16 | 17 | public void setBrand(String brand) { 18 | this.brand = brand; 19 | } 20 | 21 | public double getWeight() { 22 | return weight; 23 | } 24 | 25 | public void setWeight(double weight) { 26 | this.weight = weight; 27 | } 28 | 29 | @Override 30 | public String toString() { 31 | return STR."Racket{brand='\{brand}\{'\''}, weight=\{weight}\{'}'}"; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/oop/aggregation/TennisPlayer.java: -------------------------------------------------------------------------------- 1 | package oop.aggregation; 2 | 3 | public class TennisPlayer { 4 | 5 | private String name; 6 | private Racket racket; 7 | 8 | public TennisPlayer(String name, Racket racket) { 9 | this.name = name; 10 | this.racket = racket; 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | 21 | public Racket getRacket() { 22 | return racket; 23 | } 24 | 25 | public void setRacket(Racket racket) { 26 | this.racket = racket; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/oop/association/Address.java: -------------------------------------------------------------------------------- 1 | package oop.association; 2 | 3 | public class Address { 4 | private String city; 5 | private String postalCode; 6 | 7 | public Address(String postalCode, String city) { 8 | this.postalCode = postalCode; 9 | this.city = city; 10 | } 11 | 12 | public String getCity() { 13 | return city; 14 | } 15 | 16 | public void setCity(String city) { 17 | this.city = city; 18 | } 19 | 20 | public String getPostalCode() { 21 | return postalCode; 22 | } 23 | 24 | public void setPostalCode(String postalCode) { 25 | this.postalCode = postalCode; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/oop/association/Main.java: -------------------------------------------------------------------------------- 1 | package oop.association; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | Person p1 = new Person("Mart1", 27); 7 | Person p2 = new Person("Mart2", 27); 8 | 9 | Address a1 = new Address("1", "Tokyo"); 10 | Address a2 = new Address("2", "Saitama"); 11 | 12 | p1.addAddress(a1); 13 | p2.addAddress(a2); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/oop/association/Person.java: -------------------------------------------------------------------------------- 1 | package oop.association; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Person { 7 | private String name; 8 | private int age; 9 | 10 | private List
address; 11 | 12 | public Person(String name, int age) { 13 | this.name = name; 14 | this.age = age; 15 | this.address = new ArrayList<>(); 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public void setName(String name) { 23 | this.name = name; 24 | } 25 | 26 | public int getAge() { 27 | return age; 28 | } 29 | 30 | public void setAge(int age) { 31 | this.age = age; 32 | } 33 | 34 | public void addAddress(Address address) { 35 | this.address.add(address); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/oop/basicclass/Car.java: -------------------------------------------------------------------------------- 1 | package oop.basicclass; 2 | 3 | public class Car { 4 | private ColorOfCar color; 5 | private String brand; 6 | private int tires; 7 | 8 | public Car() { 9 | // Return the reserved memory address of the instance 10 | } 11 | 12 | public ColorOfCar getColor() { 13 | return this.color; 14 | } 15 | 16 | public void spray(ColorOfCar color) { 17 | this.color = color; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/oop/basicclass/ColorOfCar.java: -------------------------------------------------------------------------------- 1 | package oop.basicclass; 2 | 3 | public enum ColorOfCar { 4 | RED, BLACK, WHITE 5 | } 6 | -------------------------------------------------------------------------------- /src/oop/basicclass/Main.java: -------------------------------------------------------------------------------- 1 | package oop.basicclass; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | Car carA = new Car(); // Instantiation 7 | Car carB = new Car(); 8 | Car carC = new Car(); 9 | 10 | carA.spray(ColorOfCar.RED); 11 | System.out.println(STR."Color of car: \{carA.getColor()}"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/oop/composition/Car.java: -------------------------------------------------------------------------------- 1 | package oop.composition; 2 | 3 | public class Car { 4 | 5 | private final String brand; 6 | private final Engine engine; 7 | 8 | public Car(String brand) { 9 | this.brand = brand; 10 | this.engine = new Engine("E", 2000); 11 | } 12 | 13 | public String getBrand() { 14 | return brand; 15 | } 16 | 17 | public Engine getEngine() { 18 | return engine; 19 | } 20 | 21 | @Override 22 | public String toString() { 23 | return STR."Car{brand='\{brand}\{'\''}, engine=\{engine}\{'}'}"; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/oop/composition/Engine.java: -------------------------------------------------------------------------------- 1 | package oop.composition; 2 | 3 | public class Engine { 4 | 5 | private String brand; 6 | private int horsepower; 7 | 8 | public Engine(String brand, int horsepower) { 9 | this.brand = brand; 10 | this.horsepower = horsepower; 11 | } 12 | 13 | public String getBrand() { 14 | return brand; 15 | } 16 | 17 | public void setBrand(String brand) { 18 | this.brand = brand; 19 | } 20 | 21 | public int getHorsepower() { 22 | return horsepower; 23 | } 24 | 25 | public void setHorsepower(int horsepower) { 26 | this.horsepower = horsepower; 27 | } 28 | 29 | @Override 30 | public String toString() { 31 | return STR."Engine{brand='\{brand}\{'\''}, horsepower=\{horsepower}\{'}'}"; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/oop/composition/Main.java: -------------------------------------------------------------------------------- 1 | package oop.composition; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | Car car = new Car("TTT"); 7 | System.out.println(car); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/oop/inheritance/Animal.java: -------------------------------------------------------------------------------- 1 | package oop.inheritance; 2 | 3 | public class Animal { 4 | 5 | private String name; 6 | 7 | public String getName() { 8 | return name; 9 | } 10 | 11 | public void setName(String name) { 12 | this.name = name; 13 | } 14 | 15 | public void speak() { 16 | System.out.println(name); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/oop/inheritance/BusinessMan.java: -------------------------------------------------------------------------------- 1 | package oop.inheritance; 2 | 3 | public class BusinessMan extends Human { 4 | } 5 | -------------------------------------------------------------------------------- /src/oop/inheritance/Cat.java: -------------------------------------------------------------------------------- 1 | package oop.inheritance; 2 | 3 | public class Cat extends Animal { 4 | } 5 | -------------------------------------------------------------------------------- /src/oop/inheritance/Developer.java: -------------------------------------------------------------------------------- 1 | package oop.inheritance; 2 | 3 | public class Developer extends Human { 4 | } 5 | -------------------------------------------------------------------------------- /src/oop/inheritance/Dog.java: -------------------------------------------------------------------------------- 1 | package oop.inheritance; 2 | 3 | public class Dog extends Animal { 4 | } 5 | -------------------------------------------------------------------------------- /src/oop/inheritance/Human.java: -------------------------------------------------------------------------------- 1 | package oop.inheritance; 2 | 3 | public class Human extends Animal { 4 | 5 | public void walk(int steps) { 6 | System.out.println(STR."\{this.getName()} walk \{steps} steps"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/oop/inheritance/Main.java: -------------------------------------------------------------------------------- 1 | package oop.inheritance; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | Human human = new Human(); 7 | human.setName("Mart"); 8 | human.speak(); 9 | Cat cat = new Cat(); 10 | cat.setName("cat"); 11 | cat.speak(); 12 | Dog dog = new Dog(); 13 | dog.setName("dog"); 14 | dog.speak(); 15 | 16 | human.walk(5); 17 | 18 | Human developer = new Developer(); 19 | developer.setName("Developer"); 20 | developer.walk(10); 21 | 22 | Human businessMan = new BusinessMan(); 23 | businessMan.setName("BusinessMan"); 24 | businessMan.walk(9); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/oop/polymorphism/overloading/Car.java: -------------------------------------------------------------------------------- 1 | package oop.polymorphism.overloading; 2 | 3 | import oop.basicclass.ColorOfCar; 4 | 5 | public class Car { 6 | private ColorOfCar color; 7 | private String brand; 8 | private int tires; 9 | 10 | public Car() { 11 | // Return the reserved memory address of the instance 12 | } 13 | 14 | public Car(ColorOfCar color, String brand) { 15 | this(color, brand, 4); 16 | } 17 | 18 | public Car(ColorOfCar color, String brand, int tires) { 19 | this.color = color; 20 | this.brand = brand; 21 | this.tires = tires; 22 | } 23 | 24 | public ColorOfCar getColor() { 25 | return this.color; 26 | } 27 | 28 | public void spray(ColorOfCar color) { 29 | this.color = color; 30 | } 31 | 32 | public void spray(String color) { 33 | this.color = ColorOfCar.valueOf(color); 34 | } 35 | 36 | public void setColor(ColorOfCar color) { 37 | this.color = color; 38 | } 39 | 40 | public String getBrand() { 41 | return brand; 42 | } 43 | 44 | public void setBrand(String brand) { 45 | this.brand = brand; 46 | } 47 | 48 | public int getTires() { 49 | return tires; 50 | } 51 | 52 | public void setTires(int tires) { 53 | this.tires = tires; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/oop/polymorphism/overloading/Main.java: -------------------------------------------------------------------------------- 1 | package oop.polymorphism.overloading; 2 | 3 | import oop.basicclass.ColorOfCar; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) { 8 | Car car = new Car(ColorOfCar.BLACK, "NS"); // Use overload constructor 9 | System.out.println(car.getColor()); // BLACK 10 | car.spray("WHITE"); // Use overload method 11 | System.out.println(car.getColor()); // WHITE 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/oop/polymorphism/overriding/Animal.java: -------------------------------------------------------------------------------- 1 | package oop.polymorphism.overriding; 2 | 3 | abstract class Animal { 4 | 5 | abstract void makeSound(); 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/polymorphism/overriding/Cat.java: -------------------------------------------------------------------------------- 1 | package oop.polymorphism.overriding; 2 | 3 | public class Cat extends Animal { 4 | 5 | @Override 6 | void makeSound() { 7 | System.out.println("Meowwww"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/oop/polymorphism/overriding/Dog.java: -------------------------------------------------------------------------------- 1 | package oop.polymorphism.overriding; 2 | 3 | public class Dog extends Animal { 4 | 5 | @Override 6 | void makeSound() { 7 | System.out.println("Booooo"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/oop/polymorphism/overriding/Human.java: -------------------------------------------------------------------------------- 1 | package oop.polymorphism.overriding; 2 | 3 | public class Human extends Animal { 4 | 5 | @Override 6 | void makeSound() { 7 | System.out.println("GG Mid"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/oop/polymorphism/overriding/Main.java: -------------------------------------------------------------------------------- 1 | package oop.polymorphism.overriding; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | Animal animal; // Parent class wait for child class to perform 7 | animal = new Human(); // Point to Human 8 | animal.makeSound(); 9 | animal = new Dog(); // Point to Dog 10 | animal.makeSound(); 11 | animal = new Cat(); // Point to Cat 12 | animal.makeSound(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/oop/record/Product.java: -------------------------------------------------------------------------------- 1 | package oop.record; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.Objects; 5 | 6 | // POJO - Plain Old Java Object 7 | public class Product { 8 | private String name; 9 | private String type; 10 | private BigDecimal prices; 11 | private String brand; 12 | 13 | public Product(String name, String type, BigDecimal prices, String brand) { 14 | this.name = name; 15 | this.type = type; 16 | this.prices = prices; 17 | this.brand = brand; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public void setName(String name) { 25 | this.name = name; 26 | } 27 | 28 | public String getType() { 29 | return type; 30 | } 31 | 32 | public void setType(String type) { 33 | this.type = type; 34 | } 35 | 36 | public BigDecimal getPrices() { 37 | return prices; 38 | } 39 | 40 | public void setPrices(BigDecimal prices) { 41 | this.prices = prices; 42 | } 43 | 44 | public String getBrand() { 45 | return brand; 46 | } 47 | 48 | public void setBrand(String brand) { 49 | this.brand = brand; 50 | } 51 | 52 | @Override 53 | public boolean equals(Object o) { 54 | if (this == o) return true; 55 | if (o == null || getClass() != o.getClass()) return false; 56 | Product product = (Product) o; 57 | return Objects.equals(name, product.name) && Objects.equals(type, product.type) && Objects.equals(prices, product.prices) && Objects.equals(brand, product.brand); 58 | } 59 | 60 | @Override 61 | public int hashCode() { 62 | return Objects.hash(name, type, prices, brand); 63 | } 64 | 65 | @Override 66 | public String toString() { 67 | return "Product{" + 68 | "name='" + name + '\'' + 69 | ", type='" + type + '\'' + 70 | ", prices=" + prices + 71 | ", brand='" + brand + '\'' + 72 | '}'; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/oop/record/ProductRecord.java: -------------------------------------------------------------------------------- 1 | package oop.record; 2 | 3 | import java.math.BigDecimal; 4 | 5 | // record - special class to storing data as immutable 6 | // Backend Java (modern) - Use record to represent data communication schema 7 | public record ProductRecord( 8 | String name, 9 | String type, 10 | BigDecimal prices, 11 | String brand 12 | ) { 13 | 14 | // Custom encapsulation behavior 15 | @Override 16 | public String name() { 17 | return STR."[TPC] \{name}"; 18 | } 19 | 20 | public static String giveMeStoreName() { 21 | return "[TPC]"; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/oop/record/RecordExample.java: -------------------------------------------------------------------------------- 1 | package oop.record; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class RecordExample { 6 | 7 | public static void main(String[] args) { 8 | // Old 9 | Product p1 = new Product("macbook", "electronic", new BigDecimal("1000.00"), "a"); 10 | // record 11 | ProductRecord productRecord = new ProductRecord("laptop", "electronic", new BigDecimal("100.00"), "l"); 12 | System.out.println(productRecord); // Implemented toString already 13 | System.out.println(productRecord.type()); // Access state/field/property 14 | System.out.println(productRecord.name()); // name() customized 15 | System.out.println(ProductRecord.giveMeStoreName()); // Use static on record class 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/oop/solid/d/Main.java: -------------------------------------------------------------------------------- 1 | package oop.solid.d; 2 | 3 | import oop.solid.d.good.Car; 4 | import oop.solid.d.good.Engine; 5 | 6 | public class Main { 7 | 8 | public static void main(String[] args) { 9 | /* 10 | * Dependency Inversion Principle (DIP) 11 | * Depend on abstractions, not on concretions. 12 | * High-level modules should not depend on low-level modules. Both should depend on abstractions. 13 | * */ 14 | // Car car = new Car("TTT"); 15 | // car.getEngine().start(); // What Engine? 16 | // car.start(); // Cannot control engine outside, we cannot replace engine 17 | 18 | // They have own lifecycle 19 | Engine engine = new Engine("E", 2000); 20 | Car car = new Car("TTT", engine); 21 | car.start(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/oop/solid/d/bad/Car.java: -------------------------------------------------------------------------------- 1 | package oop.solid.d.bad; 2 | 3 | public class Car { 4 | 5 | private final String brand; 6 | private final Engine engine; 7 | 8 | public Car(String brand) { 9 | this.brand = brand; 10 | this.engine = new Engine("E", 2000); // High Coupling 11 | } 12 | 13 | public String getBrand() { 14 | return brand; 15 | } 16 | 17 | public Engine getEngine() { 18 | return engine; 19 | } 20 | 21 | public void start() { 22 | this.engine.start(); 23 | System.out.println("Car started"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/oop/solid/d/bad/Engine.java: -------------------------------------------------------------------------------- 1 | package oop.solid.d.bad; 2 | 3 | public class Engine { 4 | 5 | private String brand; 6 | private int horsepower; 7 | 8 | public Engine(String brand, int horsepower) { 9 | this.brand = brand; 10 | this.horsepower = horsepower; 11 | } 12 | 13 | public String getBrand() { 14 | return brand; 15 | } 16 | 17 | public void setBrand(String brand) { 18 | this.brand = brand; 19 | } 20 | 21 | public int getHorsepower() { 22 | return horsepower; 23 | } 24 | 25 | public void setHorsepower(int horsepower) { 26 | this.horsepower = horsepower; 27 | } 28 | 29 | public void start() { 30 | System.out.println("Start Engine!!!!!"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/oop/solid/d/good/Car.java: -------------------------------------------------------------------------------- 1 | package oop.solid.d.good; 2 | 3 | public class Car { 4 | 5 | private final String brand; 6 | private final Engine engine; 7 | 8 | public Car(String brand, Engine engine) { 9 | this.brand = brand; 10 | this.engine = engine; 11 | } 12 | 13 | public String getBrand() { 14 | return brand; 15 | } 16 | 17 | public Engine getEngine() { 18 | return engine; 19 | } 20 | 21 | public void start() { 22 | this.engine.start(); 23 | System.out.println("Car started"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/oop/solid/d/good/Engine.java: -------------------------------------------------------------------------------- 1 | package oop.solid.d.good; 2 | 3 | public class Engine { 4 | 5 | private String brand; 6 | private int horsepower; 7 | 8 | public Engine(String brand, int horsepower) { 9 | this.brand = brand; 10 | this.horsepower = horsepower; 11 | } 12 | 13 | public String getBrand() { 14 | return brand; 15 | } 16 | 17 | public void setBrand(String brand) { 18 | this.brand = brand; 19 | } 20 | 21 | public int getHorsepower() { 22 | return horsepower; 23 | } 24 | 25 | public void setHorsepower(int horsepower) { 26 | this.horsepower = horsepower; 27 | } 28 | 29 | public void start() { 30 | System.out.println("Start Engine!!!!!"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/oop/solid/i/Main.java: -------------------------------------------------------------------------------- 1 | package oop.solid.i; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | /* 7 | * Interface Segregation Principle (ISP) 8 | * Clients should not be forced to implement unnecessary methods that they will not use. 9 | * Many client-specific interfaces are better than one general-purpose interface. 10 | * */ 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/oop/solid/i/bad/Human.java: -------------------------------------------------------------------------------- 1 | package oop.solid.i.bad; 2 | 3 | public class Human implements Worker { 4 | 5 | @Override 6 | public void work() { 7 | System.out.println("Human work"); 8 | } 9 | 10 | @Override 11 | public void eat() { 12 | System.out.println("Human eat"); 13 | } 14 | 15 | @Override 16 | public void sleep() { 17 | System.out.println("Human sleep"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/oop/solid/i/bad/Robot.java: -------------------------------------------------------------------------------- 1 | package oop.solid.i.bad; 2 | 3 | public class Robot implements Worker { 4 | 5 | @Override 6 | public void work() { 7 | System.out.println("Robot work"); 8 | } 9 | 10 | // Robot no need to eat and sleep 11 | // but need to implement worker because they want to perform how worker doing thing 12 | @Override 13 | public void eat() { 14 | throw new RuntimeException("Robot no need to eat"); 15 | } 16 | 17 | @Override 18 | public void sleep() { 19 | throw new RuntimeException("Robot no need to sleep"); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/oop/solid/i/bad/Worker.java: -------------------------------------------------------------------------------- 1 | package oop.solid.i.bad; 2 | 3 | public interface Worker { 4 | 5 | void work(); 6 | void eat(); 7 | void sleep(); 8 | } 9 | -------------------------------------------------------------------------------- /src/oop/solid/i/good/Eatable.java: -------------------------------------------------------------------------------- 1 | package oop.solid.i.good; 2 | 3 | public interface Eatable { 4 | 5 | void eat(); 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/solid/i/good/Human.java: -------------------------------------------------------------------------------- 1 | package oop.solid.i.good; 2 | 3 | public class Human implements Workable, Eatable, Sleepable { 4 | 5 | @Override 6 | public void work() { 7 | System.out.println("Human work"); 8 | } 9 | 10 | @Override 11 | public void eat() { 12 | System.out.println("Human eat"); 13 | } 14 | 15 | @Override 16 | public void sleep() { 17 | System.out.println("Human sleep"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/oop/solid/i/good/Robot.java: -------------------------------------------------------------------------------- 1 | package oop.solid.i.good; 2 | 3 | public class Robot implements Workable { 4 | 5 | @Override 6 | public void work() { 7 | System.out.println("Robot work"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/oop/solid/i/good/Sleepable.java: -------------------------------------------------------------------------------- 1 | package oop.solid.i.good; 2 | 3 | public interface Sleepable { 4 | 5 | void sleep(); 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/solid/i/good/Workable.java: -------------------------------------------------------------------------------- 1 | package oop.solid.i.good; 2 | 3 | public interface Workable { 4 | 5 | void work(); 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/solid/l/Main.java: -------------------------------------------------------------------------------- 1 | package oop.solid.l; 2 | 3 | import java.util.List; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) { 8 | /* 9 | * Liskov's Substitution Principle (LSP) 10 | * Derived types must be completely substitutable for their base types. 11 | * Objects of subclasses must behave in the same way as the objects of superclasses. 12 | * */ 13 | 14 | // BAD 15 | 16 | // List players = List.of( 17 | // new oop.solid.l.bad.FreePlayer("Mart Free"), 18 | // new oop.solid.l.bad.BattlePassPlayer("Mart BattlePass"), 19 | // new oop.solid.l.bad.VipPlayer("Mart VIP") 20 | // ); 21 | // 22 | // for (oop.solid.l.bad.Player p : players) { 23 | // p.joinBattleRoyal(); 24 | // } 25 | 26 | // GOOD 27 | List playersWhoCanView = List.of( 28 | new oop.solid.l.good.FreePlayer("Mart Free"), 29 | new oop.solid.l.good.BattlePassPlayer("Mart BattlePass"), 30 | new oop.solid.l.good.VipPlayer("Mart VIP") 31 | ); 32 | // Only accept view behavior elements 33 | for (oop.solid.l.good.ViewBattleRoyal p : playersWhoCanView) { 34 | p.viewBattleRoyal(); 35 | } 36 | 37 | List playersWhoCanJoin = List.of( 38 | new oop.solid.l.good.BattlePassPlayer("Mart BattlePass"), 39 | new oop.solid.l.good.VipPlayer("Mart VIP") 40 | ); 41 | // Only accept join behavior elements 42 | for (oop.solid.l.good.JoinBattleRoyal p : playersWhoCanJoin) { 43 | p.joinBattleRoyal(); 44 | } 45 | 46 | List playersWhoCanCreate = List.of( 47 | new oop.solid.l.good.VipPlayer("Mart VIP") 48 | ); 49 | // Only accept create behavior elements 50 | for (oop.solid.l.good.CreateBattleRoyal p : playersWhoCanCreate) { 51 | p.createBattleRoyal(); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/oop/solid/l/bad/BattlePassPlayer.java: -------------------------------------------------------------------------------- 1 | package oop.solid.l.bad; 2 | 3 | public class BattlePassPlayer extends Player { 4 | 5 | public BattlePassPlayer(String name) { 6 | super(name); 7 | } 8 | 9 | @Override 10 | public void viewBattleRoyal() { 11 | System.out.println("BattlePassPlayer can view battle royal"); 12 | } 13 | 14 | @Override 15 | public void joinBattleRoyal() { 16 | System.out.println("BattlePassPlayer can join battle royal"); 17 | } 18 | 19 | @Override 20 | public void createBattleRoyal() { 21 | System.out.println("BattlePassPlayer can not create battle royal"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/oop/solid/l/bad/FreePlayer.java: -------------------------------------------------------------------------------- 1 | package oop.solid.l.bad; 2 | 3 | public class FreePlayer extends Player { 4 | 5 | public FreePlayer(String name) { 6 | super(name); 7 | } 8 | 9 | @Override 10 | public void viewBattleRoyal() { 11 | System.out.println("FreePlayer can view battle royal"); 12 | } 13 | 14 | @Override 15 | public void joinBattleRoyal() { 16 | System.out.println("FreePlayer can not join battle royal"); 17 | } 18 | 19 | @Override 20 | public void createBattleRoyal() { 21 | System.out.println("FreePlayer can not create battle royal"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/oop/solid/l/bad/Player.java: -------------------------------------------------------------------------------- 1 | package oop.solid.l.bad; 2 | 3 | public abstract class Player { 4 | 5 | private final String name; 6 | 7 | protected Player(String name) { 8 | this.name = name; 9 | } 10 | 11 | // Based on this declaration 12 | // You expect all player can do all of these behaviors 13 | public abstract void viewBattleRoyal(); 14 | public abstract void joinBattleRoyal(); 15 | public abstract void createBattleRoyal(); 16 | } 17 | -------------------------------------------------------------------------------- /src/oop/solid/l/bad/VipPlayer.java: -------------------------------------------------------------------------------- 1 | package oop.solid.l.bad; 2 | 3 | public class VipPlayer extends Player { 4 | 5 | public VipPlayer(String name) { 6 | super(name); 7 | } 8 | 9 | @Override 10 | public void viewBattleRoyal() { 11 | System.out.println("VipPlayer can view battle royal"); 12 | } 13 | 14 | @Override 15 | public void joinBattleRoyal() { 16 | System.out.println("VipPlayer can join battle royal"); 17 | } 18 | 19 | @Override 20 | public void createBattleRoyal() { 21 | System.out.println("VipPlayer can create battle royal"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/oop/solid/l/good/BattlePassPlayer.java: -------------------------------------------------------------------------------- 1 | package oop.solid.l.good; 2 | 3 | public class BattlePassPlayer extends Player implements JoinBattleRoyal { 4 | 5 | public BattlePassPlayer(String name) { 6 | super(name); 7 | } 8 | 9 | @Override 10 | public void viewBattleRoyal() { 11 | System.out.println("BattlePassPlayer can view battle royal"); 12 | } 13 | 14 | @Override 15 | public void joinBattleRoyal() { 16 | System.out.println("BattlePassPlayer can join battle royal"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/oop/solid/l/good/CreateBattleRoyal.java: -------------------------------------------------------------------------------- 1 | package oop.solid.l.good; 2 | 3 | public interface CreateBattleRoyal { 4 | 5 | void createBattleRoyal(); 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/solid/l/good/FreePlayer.java: -------------------------------------------------------------------------------- 1 | package oop.solid.l.good; 2 | 3 | public class FreePlayer extends Player { 4 | 5 | public FreePlayer(String name) { 6 | super(name); 7 | } 8 | 9 | @Override 10 | public void viewBattleRoyal() { 11 | System.out.println("FreePlayer can view battle royal"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/oop/solid/l/good/JoinBattleRoyal.java: -------------------------------------------------------------------------------- 1 | package oop.solid.l.good; 2 | 3 | public interface JoinBattleRoyal { 4 | 5 | void joinBattleRoyal(); 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/solid/l/good/Player.java: -------------------------------------------------------------------------------- 1 | package oop.solid.l.good; 2 | 3 | public abstract class Player implements ViewBattleRoyal { 4 | 5 | private final String name; 6 | 7 | protected Player(String name) { 8 | this.name = name; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/oop/solid/l/good/ViewBattleRoyal.java: -------------------------------------------------------------------------------- 1 | package oop.solid.l.good; 2 | 3 | public interface ViewBattleRoyal { 4 | 5 | void viewBattleRoyal(); 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/solid/l/good/VipPlayer.java: -------------------------------------------------------------------------------- 1 | package oop.solid.l.good; 2 | 3 | public class VipPlayer extends Player implements JoinBattleRoyal, CreateBattleRoyal { 4 | 5 | public VipPlayer(String name) { 6 | super(name); 7 | } 8 | 9 | @Override 10 | public void viewBattleRoyal() { 11 | System.out.println("VipPlayer can view battle royal"); 12 | } 13 | 14 | @Override 15 | public void joinBattleRoyal() { 16 | System.out.println("VipPlayer can join battle royal"); 17 | } 18 | 19 | @Override 20 | public void createBattleRoyal() { 21 | System.out.println("VipPlayer can create battle royal"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/oop/solid/o/Main.java: -------------------------------------------------------------------------------- 1 | package oop.solid.o; 2 | 3 | 4 | import oop.solid.o.good.AreaCalculator; 5 | import oop.solid.o.good.Circle; 6 | import oop.solid.o.good.Rectangle; 7 | import oop.solid.o.good.Shape; 8 | 9 | import java.util.List; 10 | 11 | public class Main { 12 | 13 | public static void main(String[] args) { 14 | /* 15 | * Open Closed Principle (OCP) 16 | * Software components should be open for extension, but closed for modification. 17 | * */ 18 | List shapes = List.of( 19 | new Circle(3), 20 | new Rectangle(2,3) 21 | // New requirement - Handle square 22 | ); 23 | AreaCalculator areaCalculator = new AreaCalculator(shapes); 24 | System.out.println(areaCalculator.sumArea()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/oop/solid/o/bad/AreaCalculator.java: -------------------------------------------------------------------------------- 1 | package oop.solid.o.bad; 2 | 3 | import java.util.List; 4 | 5 | public class AreaCalculator { 6 | 7 | private final List shapes; 8 | 9 | public AreaCalculator(List shapes) { 10 | this.shapes = shapes; 11 | } 12 | 13 | public double sumArea() { 14 | // Sum from area formula depending on shape 15 | double sum = 0; 16 | for (var shape : shapes) { 17 | if (shape instanceof Circle c) { 18 | // Area of circle 19 | System.out.println("Area of circle"); 20 | sum += Math.PI * Math.pow(c.getRadius(), 2.0); 21 | } else if (shape instanceof Rectangle r) { 22 | // Area of rectangle 23 | System.out.println("Area of rectangle"); 24 | sum += r.getHeight() * r.getWidth(); 25 | } 26 | // Oh shoot!, I need to create another condition (for Square) 27 | // Here where we break OCP rule 28 | } 29 | return sum; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/oop/solid/o/bad/Circle.java: -------------------------------------------------------------------------------- 1 | package oop.solid.o.bad; 2 | 3 | public class Circle implements Shape { 4 | 5 | private final int radius; 6 | 7 | public Circle(int radius) { 8 | this.radius = radius; 9 | } 10 | 11 | public int getRadius() { 12 | return radius; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/oop/solid/o/bad/Rectangle.java: -------------------------------------------------------------------------------- 1 | package oop.solid.o.bad; 2 | 3 | public class Rectangle implements Shape { 4 | 5 | private final int width; 6 | private final int height; 7 | 8 | public Rectangle(int width, int height) { 9 | this.width = width; 10 | this.height = height; 11 | } 12 | 13 | public int getWidth() { 14 | return width; 15 | } 16 | 17 | public int getHeight() { 18 | return height; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/oop/solid/o/bad/Shape.java: -------------------------------------------------------------------------------- 1 | package oop.solid.o.bad; 2 | 3 | public interface Shape { 4 | } 5 | -------------------------------------------------------------------------------- /src/oop/solid/o/bad/Square.java: -------------------------------------------------------------------------------- 1 | package oop.solid.o.bad; 2 | 3 | public class Square implements Shape { 4 | 5 | private final int length; 6 | 7 | public Square(int length) { 8 | this.length = length; 9 | } 10 | 11 | public int getLength() { 12 | return length; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/oop/solid/o/good/AreaCalculator.java: -------------------------------------------------------------------------------- 1 | package oop.solid.o.good; 2 | 3 | import java.util.List; 4 | 5 | public class AreaCalculator { 6 | 7 | private final List shapes; 8 | 9 | public AreaCalculator(List shapes) { 10 | this.shapes = shapes; 11 | } 12 | 13 | public double sumArea() { 14 | // Sum from area formula depending on shape 15 | double sum = 0; 16 | for (var shape : shapes) { 17 | sum += shape.area(); 18 | } 19 | return sum; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/oop/solid/o/good/Circle.java: -------------------------------------------------------------------------------- 1 | package oop.solid.o.good; 2 | 3 | public class Circle implements Shape { 4 | 5 | private final int radius; 6 | 7 | public Circle(int radius) { 8 | this.radius = radius; 9 | } 10 | 11 | public int getRadius() { 12 | return radius; 13 | } 14 | 15 | @Override 16 | public double area() { 17 | return Math.PI * Math.pow(radius, 2.0); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/oop/solid/o/good/Rectangle.java: -------------------------------------------------------------------------------- 1 | package oop.solid.o.good; 2 | 3 | public class Rectangle implements Shape { 4 | 5 | private final int width; 6 | private final int height; 7 | 8 | public Rectangle(int width, int height) { 9 | this.width = width; 10 | this.height = height; 11 | } 12 | 13 | public int getWidth() { 14 | return width; 15 | } 16 | 17 | public int getHeight() { 18 | return height; 19 | } 20 | 21 | @Override 22 | public double area() { 23 | return height * width; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/oop/solid/o/good/Shape.java: -------------------------------------------------------------------------------- 1 | package oop.solid.o.good; 2 | 3 | public interface Shape { 4 | 5 | double area(); 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/solid/o/good/Square.java: -------------------------------------------------------------------------------- 1 | package oop.solid.o.good; 2 | 3 | public class Square implements Shape { 4 | 5 | private final int length; 6 | 7 | public Square(int length) { 8 | this.length = length; 9 | } 10 | 11 | public int getLength() { 12 | return length; 13 | } 14 | 15 | @Override 16 | public double area() { 17 | return length * 4; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/oop/solid/s/Main.java: -------------------------------------------------------------------------------- 1 | package oop.solid.s; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | /* 7 | * Single Responsibility Principle (SRP) 8 | * One class should have one, and only one, responsibility. 9 | * */ 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/oop/solid/s/bad/TriangleAreaCalculator.java: -------------------------------------------------------------------------------- 1 | package oop.solid.s.bad; 2 | 3 | public class TriangleAreaCalculator { 4 | 5 | private static final double TRIANGLE_CONSTANT = 0.5; 6 | private static final double METER_TO_FEET = 3.28084; 7 | 8 | private final int base; // assume meter 9 | private final int height; 10 | 11 | public TriangleAreaCalculator(int base, int height) { 12 | this.base = base; 13 | this.height = height; 14 | } 15 | 16 | public double area() { 17 | return TRIANGLE_CONSTANT * this.base * this.height; 18 | } 19 | 20 | // Break SRP rule 21 | public double meterToFeet(int length) { 22 | return length * METER_TO_FEET; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/oop/solid/s/good/LengthConverter.java: -------------------------------------------------------------------------------- 1 | package oop.solid.s.good; 2 | 3 | public class LengthConverter { 4 | 5 | private static final double METER_TO_FEET = 3.28084; 6 | 7 | public double meterToFeet(int length) { 8 | return length * METER_TO_FEET; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/oop/solid/s/good/TriangleAreaCalculator.java: -------------------------------------------------------------------------------- 1 | package oop.solid.s.good; 2 | 3 | public class TriangleAreaCalculator { 4 | 5 | private static final double TRIANGLE_CONSTANT = 0.5; 6 | 7 | private final int base; 8 | private final int height; 9 | 10 | public TriangleAreaCalculator(int base, int height) { 11 | this.base = base; 12 | this.height = height; 13 | } 14 | 15 | public double area() { 16 | return TRIANGLE_CONSTANT * this.base * this.height; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/util/TutorialUtil.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | public class TutorialUtil { 4 | 5 | public static void line() { 6 | System.out.println("========="); 7 | } 8 | } 9 | --------------------------------------------------------------------------------