diff --git a/pom.xml b/pom.xml
index 8b83d02..64f8fce 100644
--- a/pom.xml
+++ b/pom.xml
@@ -62,6 +62,13 @@
org.apache.maven.pluginsmaven-surefire-plugin3.5.3
+
+
+ -Dnet.bytebuddy.experimental=true
+ --add-opens java.base/java.lang=ALL-UNNAMED
+ --add-opens java.base/java.lang.reflect=ALL-UNNAMED
+
+
diff --git a/src/main/java/com/amigoscode/beginners/thebasics/ArrayExercises.java b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/ArrayExercises.java
similarity index 65%
rename from src/main/java/com/amigoscode/beginners/thebasics/ArrayExercises.java
rename to src/main/java/com/amigoscode/_1_beginners/_1_thebasics/ArrayExercises.java
index bcbc5d2..79964df 100644
--- a/src/main/java/com/amigoscode/beginners/thebasics/ArrayExercises.java
+++ b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/ArrayExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.beginners.thebasics;
+package com.amigoscode._1_beginners._1_thebasics;
/**
* Exercise: Arrays
@@ -12,31 +12,42 @@ public static void main(String[] args) {
// TODO: 1 - Declare and initialize an int array called 'numbers' with 5 values
// Hint: int[] numbers = {value1, value2, value3, value4, value5};
-
+ int[] numbers = {10, 20, 30, 40, 50};
// TODO: 2 - Access and print the first and last elements of the array
// Hint: Arrays are zero-indexed. First element is numbers[0].
// Last element is numbers[numbers.length - 1].
-
+ System.out.println("First element: " + numbers[0]);
+ System.out.println("Last element: " + numbers[numbers.length - 1]);
// TODO: 3 - Change the value of the third element (index 2) to 99 and print it
// Hint: numbers[2] = 99;
-
+ numbers[2] = 99;
+ System.out.println("Third element: " + numbers[2]);
// TODO: 4 - Get the length of the array and print it
// Hint: Use the .length property (not a method, no parentheses)
-
+ System.out.println("Array length: " + numbers.length);
// TODO: 5 - Loop through the array using a standard for loop and print each element
// Hint: for (int i = 0; i < numbers.length; i++) { ... }
-
+ for (int i = 0; i < numbers.length; i++) {
+ System.out.println("numbers[" + i + "] = " + numbers[i]);
+ }
// TODO: 6 - Loop through the array using an enhanced for loop (for-each) and print each element
// Hint: for (int num : numbers) { ... }
-
+ for (int num : numbers) {
+ System.out.println(num);
+ }
// TODO: 7 - Find the sum of all elements in the array and print it
// Hint: Declare a sum variable, loop through the array, and add each element to sum
+ int sum = 0;
+ for (int num : numbers) {
+ sum += num;
+ }
+ System.out.println("Sum: " + sum);
}
}
diff --git a/src/main/java/com/amigoscode/beginners/thebasics/ConditionalStatements.java b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/ConditionalStatements.java
similarity index 54%
rename from src/main/java/com/amigoscode/beginners/thebasics/ConditionalStatements.java
rename to src/main/java/com/amigoscode/_1_beginners/_1_thebasics/ConditionalStatements.java
index ad2cace..5e8299c 100644
--- a/src/main/java/com/amigoscode/beginners/thebasics/ConditionalStatements.java
+++ b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/ConditionalStatements.java
@@ -1,4 +1,4 @@
-package com.amigoscode.beginners.thebasics;
+package com.amigoscode._1_beginners._1_thebasics;
/**
* Exercise: Conditional Statements
@@ -17,7 +17,11 @@ public static void main(String[] args) {
// TODO: 2 - Add an else clause to the above that prints "Not positive"
// Change the value of number to a negative value or 0 to test both branches.
-
+ if (number > 0) {
+ System.out.println("Positive");
+ } else {
+ System.out.println("Not positive");
+ }
// TODO: 3 - Write an if/else if/else chain for grade classification
// Declare an int variable called score and assign it a value (0-100).
@@ -27,7 +31,15 @@ public static void main(String[] args) {
// Else print "Grade: F"
int score = 85;
-
+ if (score >= 90) {
+ System.out.println("Grade: A");
+ } else if (score >= 80) {
+ System.out.println("Grade: B");
+ } else if (score >= 70) {
+ System.out.println("Grade: C");
+ } else {
+ System.out.println("Grade: F");
+ }
// TODO: 4 - Write a switch statement for day of the week
// Declare an int variable called day (1-7).
@@ -36,7 +48,16 @@ public static void main(String[] args) {
// Include a default case for invalid values.
int day = 3;
-
+ switch (day) {
+ case 1: System.out.println("Monday"); break;
+ case 2: System.out.println("Tuesday"); break;
+ case 3: System.out.println("Wednesday"); break;
+ case 4: System.out.println("Thursday"); break;
+ case 5: System.out.println("Friday"); break;
+ case 6: System.out.println("Saturday"); break;
+ case 7: System.out.println("Sunday"); break;
+ default: System.out.println("Invalid day"); break;
+ }
// TODO: 5 - Use a switch statement with a String
// Declare a String variable called month (e.g., "February").
@@ -44,7 +65,13 @@ public static void main(String[] args) {
// Handle at least 3-4 months plus a default case.
String month = "February";
-
+ switch (month) {
+ case "January": System.out.println("31 days"); break;
+ case "February": System.out.println("28 or 29 days"); break;
+ case "March": System.out.println("31 days"); break;
+ case "April": System.out.println("30 days"); break;
+ default: System.out.println("Check a calendar"); break;
+ }
// TODO: 6 - Use a switch expression (Java 14+) to return a value
// Using the 'day' variable from above, assign the day name to a String
@@ -54,7 +81,17 @@ public static void main(String[] args) {
// ...
// };
// Print the result.
-
+ String dayName = switch (day) {
+ case 1 -> "Monday";
+ case 2 -> "Tuesday";
+ case 3 -> "Wednesday";
+ case 4 -> "Thursday";
+ case 5 -> "Friday";
+ case 6 -> "Saturday";
+ case 7 -> "Sunday";
+ default -> "Invalid day";
+ };
+ System.out.println("Day name: " + dayName);
// TODO: 7 - Write a nested if statement to check if a number is positive AND even
// Declare an int variable called value.
@@ -65,6 +102,15 @@ public static void main(String[] args) {
// Else print "Not positive"
int value = 8;
+ if (value > 0) {
+ if (value % 2 == 0) {
+ System.out.println("Positive and even");
+ } else {
+ System.out.println("Positive and odd");
+ }
+ } else {
+ System.out.println("Not positive");
+ }
}
}
diff --git a/src/main/java/com/amigoscode/beginners/thebasics/LoopExercises.java b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/LoopExercises.java
similarity index 65%
rename from src/main/java/com/amigoscode/beginners/thebasics/LoopExercises.java
rename to src/main/java/com/amigoscode/_1_beginners/_1_thebasics/LoopExercises.java
index 1338829..0517c7c 100644
--- a/src/main/java/com/amigoscode/beginners/thebasics/LoopExercises.java
+++ b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/LoopExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.beginners.thebasics;
+package com.amigoscode._1_beginners._1_thebasics;
/**
* Exercise: Loops
@@ -12,33 +12,50 @@ public static void main(String[] args) {
// TODO: 1 - Write a for loop to print numbers 1 to 10
// Hint: for (int i = 1; i <= 10; i++) { ... }
-
+ for (int i = 1; i <= 10; i++) {
+ System.out.println(i);
+ }
// TODO: 2 - Write a while loop to print numbers 10 down to 1 (countdown)
// Hint: Declare a variable before the loop, use a condition, and decrement inside the loop.
-
+ int countdown = 10;
+ while (countdown >= 1) {
+ System.out.println(countdown);
+ countdown--;
+ }
// TODO: 3 - Write a do-while loop that runs at least once
// Print "This runs at least once!" inside the loop.
// Use a condition that is false so the loop only runs once.
// Hint: do { ... } while (condition);
-
+ do {
+ System.out.println("This runs at least once!");
+ } while (false);
// TODO: 4 - Write a for loop to print only even numbers from 1 to 20
// Hint: Use an if statement with the modulus operator (%) inside the loop,
// or increment by 2 starting from 2.
-
+ for (int i = 2; i <= 20; i += 2) {
+ System.out.println(i);
+ }
// TODO: 5 - Write a for loop to calculate the factorial of 5 (5! = 120)
// Declare a variable called factorial and initialize it to 1.
// Multiply factorial by each number from 1 to 5.
// Print the result.
-
+ int factorial = 1;
+ for (int i = 1; i <= 5; i++) {
+ factorial *= i;
+ }
+ System.out.println("5! = " + factorial);
// TODO: 6 - Use an enhanced for loop (for-each) to iterate over a String array
// Declare a String array called fruits with at least 4 fruit names.
// Use an enhanced for loop to print each fruit.
-
+ String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
+ for (String fruit : fruits) {
+ System.out.println(fruit);
+ }
// TODO: 7 - Write a nested for loop to print a 3x3 multiplication table
// The output should look like:
@@ -47,13 +64,23 @@ public static void main(String[] args) {
// 3 6 9
// Hint: Use System.out.print() for values on the same row,
// and System.out.println() to move to the next row.
-
+ for (int i = 1; i <= 3; i++) {
+ for (int j = 1; j <= 3; j++) {
+ System.out.print((i * j) + " ");
+ }
+ System.out.println();
+ }
// TODO: 8 - Use break and continue in a loop
// Write a for loop from 1 to 10:
// - Use 'continue' to skip the number 5 (do not print it)
// - Use 'break' to stop the loop when you reach 8
// Print each number that is not skipped.
+ for (int i = 1; i <= 10; i++) {
+ if (i == 5) continue;
+ if (i == 8) break;
+ System.out.println(i);
+ }
}
}
diff --git a/src/main/java/com/amigoscode/beginners/thebasics/MethodExercises.java b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/MethodExercises.java
similarity index 63%
rename from src/main/java/com/amigoscode/beginners/thebasics/MethodExercises.java
rename to src/main/java/com/amigoscode/_1_beginners/_1_thebasics/MethodExercises.java
index f82cb5a..d845b2b 100644
--- a/src/main/java/com/amigoscode/beginners/thebasics/MethodExercises.java
+++ b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/MethodExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.beginners.thebasics;
+package com.amigoscode._1_beginners._1_thebasics;
/**
* Exercise: Methods
@@ -11,33 +11,53 @@ public class MethodExercises {
// TODO: 1 - Create a method called greet that takes a String parameter 'name'
// and prints "Hello, {name}!"
// Hint: public static void greet(String name) { ... }
-
+ public static void greet(String name) {
+ System.out.println("Hello, " + name + "!");
+ }
// TODO: 2 - Create a method called add that takes two int parameters (a, b)
// and returns their sum
// Hint: public static int add(int a, int b) { ... }
-
+ public static int add(int a, int b) {
+ return a + b;
+ }
// TODO: 3 - Create a method called isEven that takes an int parameter 'number'
// and returns true if the number is even, false otherwise
// Hint: Use the modulus operator (%)
-
+ public static boolean isEven(int number) {
+ return number % 2 == 0;
+ }
// TODO: 4 - Create a method called max that takes two int parameters (a, b)
// and returns the larger of the two
// Hint: Use an if statement or the ternary operator
-
+ public static int max(int a, int b) {
+ return (a >= b) ? a : b;
+ }
// TODO: 5 - Create a method called factorial that takes an int parameter 'n'
// and returns n! (n factorial) using a loop
// Hint: 5! = 5 * 4 * 3 * 2 * 1 = 120. Use a long return type for larger values.
-
+ public static long factorial(int n) {
+ long result = 1;
+ for (int i = 1; i <= n; i++) {
+ result *= i;
+ }
+ return result;
+ }
// TODO: 6 - Create two overloaded methods called multiply:
// - One that takes 2 int parameters and returns their product
// - One that takes 3 int parameters and returns their product
// Overloading means having multiple methods with the same name but different parameters.
+ public static int multiply(int a, int b) {
+ return a * b;
+ }
+ public static int multiply(int a, int b, int c) {
+ return a * b * c;
+ }
public static void main(String[] args) {
@@ -48,6 +68,13 @@ public static void main(String[] args) {
// - Call max with two numbers and print the larger one
// - Call factorial with 5 and print the result
// - Call both multiply methods and print their results
+ greet("Amigos");
+ System.out.println("add(3, 5) = " + add(3, 5));
+ System.out.println("isEven(4) = " + isEven(4));
+ System.out.println("max(7, 12) = " + max(7, 12));
+ System.out.println("factorial(5) = " + factorial(5));
+ System.out.println("multiply(3, 4) = " + multiply(3, 4));
+ System.out.println("multiply(2, 3, 4) = " + multiply(2, 3, 4));
}
}
diff --git a/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/MiniProject.java b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/MiniProject.java
new file mode 100644
index 0000000..1685fe1
--- /dev/null
+++ b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/MiniProject.java
@@ -0,0 +1,79 @@
+package com.amigoscode._1_beginners._1_thebasics;
+
+import java.util.Scanner;
+
+/**
+ * Mini Project: Simple Calculator
+ *
+ * Put together everything you have learned so far to build a simple calculator.
+ * The calculator should display a menu, read the user's choice and two numbers,
+ * perform the chosen operation, and print the result.
+ */
+public class MiniProject {
+
+ public static void main(String[] args) {
+
+ // TODO: 1 - Create a Scanner for user input
+ Scanner scanner = new Scanner(System.in);
+
+ // TODO: 2 - Display a menu with the following options:
+ // Print:
+ // "=== Simple Calculator ==="
+ // "1. Add"
+ // "2. Subtract"
+ // "3. Multiply"
+ // "4. Divide"
+ // "Choose an operation (1-4): "
+ System.out.println("=== Simple Calculator ===");
+ System.out.println("1. Add");
+ System.out.println("2. Subtract");
+ System.out.println("3. Multiply");
+ System.out.println("4. Divide");
+ System.out.print("Choose an operation (1-4): ");
+
+ // TODO: 3 - Read the user's choice into an int variable
+ int choice = scanner.nextInt();
+
+ // TODO: 4 - Prompt and read two double numbers from the user
+ // Print "Enter first number: " and read it.
+ // Print "Enter second number: " and read it.
+ System.out.print("Enter first number: ");
+ double num1 = scanner.nextDouble();
+ System.out.print("Enter second number: ");
+ double num2 = scanner.nextDouble();
+
+ // TODO: 5 - Use a switch statement to perform the chosen operation and print the result
+ // Case 1: Print "Result: " + (num1 + num2)
+ // Case 2: Print "Result: " + (num1 - num2)
+ // Case 3: Print "Result: " + (num1 * num2)
+ // Case 4: Perform division (but handle division by zero first - see TODO 6)
+ // Default: Print "Invalid choice"
+ switch (choice) {
+ case 1:
+ System.out.println("Result: " + (num1 + num2));
+ break;
+ case 2:
+ System.out.println("Result: " + (num1 - num2));
+ break;
+ case 3:
+ System.out.println("Result: " + (num1 * num2));
+ break;
+ case 4:
+ // TODO: 6 - Inside case 4, handle division by zero with an if statement
+ // If the second number is 0, print "Error: Cannot divide by zero"
+ // Otherwise, print the result of the division
+ if (num2 == 0) {
+ System.out.println("Error: Cannot divide by zero");
+ } else {
+ System.out.println("Result: " + (num1 / num2));
+ }
+ break;
+ default:
+ System.out.println("Invalid choice");
+ break;
+ }
+
+ scanner.close();
+
+ }
+}
diff --git a/src/main/java/com/amigoscode/beginners/thebasics/Operators.java b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/Operators.java
similarity index 55%
rename from src/main/java/com/amigoscode/beginners/thebasics/Operators.java
rename to src/main/java/com/amigoscode/_1_beginners/_1_thebasics/Operators.java
index 19a979e..fe3d8d7 100644
--- a/src/main/java/com/amigoscode/beginners/thebasics/Operators.java
+++ b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/Operators.java
@@ -1,4 +1,4 @@
-package com.amigoscode.beginners.thebasics;
+package com.amigoscode._1_beginners._1_thebasics;
/**
* Exercise: Operators
@@ -13,40 +13,68 @@ public static void main(String[] args) {
// TODO: 1 - Use arithmetic operators (+, -, *, /) on two int variables and print the results
// Declare two int variables (e.g., a = 10, b = 3)
// Print the result of a + b, a - b, a * b, and a / b
-
+ int a = 10, b = 3;
+ System.out.println("a + b = " + (a + b));
+ System.out.println("a - b = " + (a - b));
+ System.out.println("a * b = " + (a * b));
+ System.out.println("a / b = " + (a / b));
// TODO: 2 - Use the modulus operator (%) to check if a number is even
// Declare an int variable called number with any value.
// Print the result of number % 2
// Print whether the number is even (result is 0) or odd (result is 1)
-
+ int number = 14;
+ System.out.println("number % 2 = " + (number % 2));
+ System.out.println(number + " is " + ((number % 2 == 0) ? "even" : "odd"));
// TODO: 3 - Use increment (++) and decrement (--) operators
// Declare an int variable called counter, set it to 5
// Use counter++ and print the result, then use counter-- and print the result
-
+ int counter = 5;
+ counter++;
+ System.out.println("After increment: " + counter);
+ counter--;
+ System.out.println("After decrement: " + counter);
// TODO: 4 - Use compound assignment operators (+=, -=, *=)
// Declare an int variable called score, set it to 10
// Use +=, -=, and *= on score, printing after each operation
-
+ int score = 10;
+ score += 5;
+ System.out.println("After += 5: " + score);
+ score -= 3;
+ System.out.println("After -= 3: " + score);
+ score *= 2;
+ System.out.println("After *= 2: " + score);
// TODO: 5 - Use comparison operators (==, !=, >, <, >=, <=) and print the boolean results
// Declare two int variables (e.g., x = 5, y = 10)
// Print the result of each comparison, e.g.: System.out.println("x == y: " + (x == y));
-
+ int x = 5, y = 10;
+ System.out.println("x == y: " + (x == y));
+ System.out.println("x != y: " + (x != y));
+ System.out.println("x > y: " + (x > y));
+ System.out.println("x < y: " + (x < y));
+ System.out.println("x >= y: " + (x >= y));
+ System.out.println("x <= y: " + (x <= y));
// TODO: 6 - Use logical operators (&&, ||, !) to combine conditions
// Declare two boolean variables (e.g., hasLicense = true, hasInsurance = false)
// Print the result of: hasLicense && hasInsurance
// Print the result of: hasLicense || hasInsurance
// Print the result of: !hasLicense
-
+ boolean hasLicense = true, hasInsurance = false;
+ System.out.println("hasLicense && hasInsurance: " + (hasLicense && hasInsurance));
+ System.out.println("hasLicense || hasInsurance: " + (hasLicense || hasInsurance));
+ System.out.println("!hasLicense: " + (!hasLicense));
// TODO: 7 - Use the ternary operator to assign "adult" or "minor" based on age
// Declare an int variable called age with any value
// Use the ternary operator: String status = (condition) ? "adult" : "minor";
// Print the status
+ int age = 20;
+ String status = (age >= 18) ? "adult" : "minor";
+ System.out.println("Status: " + status);
}
}
diff --git a/src/main/java/com/amigoscode/beginners/thebasics/ScannerExercises.java b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/ScannerExercises.java
similarity index 69%
rename from src/main/java/com/amigoscode/beginners/thebasics/ScannerExercises.java
rename to src/main/java/com/amigoscode/_1_beginners/_1_thebasics/ScannerExercises.java
index c38ef43..5d2e9b7 100644
--- a/src/main/java/com/amigoscode/beginners/thebasics/ScannerExercises.java
+++ b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/ScannerExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.beginners.thebasics;
+package com.amigoscode._1_beginners._1_thebasics;
import java.util.Scanner;
@@ -14,31 +14,38 @@ public static void main(String[] args) {
// TODO: 1 - Create a Scanner object to read from System.in
// Hint: Scanner scanner = new Scanner(System.in);
-
+ Scanner scanner = new Scanner(System.in);
// TODO: 2 - Prompt the user for their name and read it using nextLine()
// Print "Enter your name: " then read the input into a String variable.
// Hint: Use System.out.print() (not println) for the prompt so the cursor
// stays on the same line.
-
+ System.out.print("Enter your name: ");
+ String name = scanner.nextLine();
// TODO: 3 - Prompt the user for their age and read it using nextInt()
// Print "Enter your age: " then read the input into an int variable.
// Note: After nextInt(), the newline character remains in the buffer.
-
+ System.out.print("Enter your age: ");
+ int age = scanner.nextInt();
// TODO: 4 - Print a greeting using the name and age
// Example output: "Hello, Alice! You are 25 years old."
-
+ System.out.println("Hello, " + name + "! You are " + age + " years old.");
// TODO: 5 - Prompt the user for two numbers, read them, and print their sum
// Print "Enter first number: ", read it.
// Print "Enter second number: ", read it.
// Print "Sum: " followed by the result.
-
+ System.out.print("Enter first number: ");
+ int first = scanner.nextInt();
+ System.out.print("Enter second number: ");
+ int second = scanner.nextInt();
+ System.out.println("Sum: " + (first + second));
// TODO: 6 - Close the scanner to free resources
// Hint: scanner.close();
+ scanner.close();
}
}
diff --git a/src/main/java/com/amigoscode/beginners/thebasics/StringExercises.java b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/StringExercises.java
similarity index 62%
rename from src/main/java/com/amigoscode/beginners/thebasics/StringExercises.java
rename to src/main/java/com/amigoscode/_1_beginners/_1_thebasics/StringExercises.java
index 6c80449..eac7e6f 100644
--- a/src/main/java/com/amigoscode/beginners/thebasics/StringExercises.java
+++ b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/StringExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.beginners.thebasics;
+package com.amigoscode._1_beginners._1_thebasics;
/**
* Exercise: Strings
@@ -17,35 +17,44 @@ public static void main(String[] args) {
// TODO: 1 - Get the length of the 'message' string and print it
// Hint: Use the .length() method
-
+ System.out.println("Length: " + message.length());
// TODO: 2 - Convert 'message' to uppercase and lowercase, and print both
// Hint: Use .toUpperCase() and .toLowerCase()
-
+ System.out.println("Uppercase: " + message.toUpperCase());
+ System.out.println("Lowercase: " + message.toLowerCase());
// TODO: 3 - Get a substring of 'message' containing the first 5 characters and print it
// Hint: Use .substring(startIndex, endIndex)
-
+ System.out.println("Substring: " + message.substring(0, 5));
// TODO: 4 - Check if 'message' contains the word "Amigoscode" and print the result
// Hint: Use .contains()
-
+ System.out.println("Contains Amigoscode: " + message.contains("Amigoscode"));
// TODO: 5 - Replace "Amigoscode" with "Java" in 'message' and print the new string
// Hint: Use .replace(oldValue, newValue)
-
+ System.out.println("Replaced: " + message.replace("Amigoscode", "Java"));
// TODO: 6 - Trim the whitespace from the 'padded' string and print the result
// Hint: Use .trim()
-
+ System.out.println("Trimmed: '" + padded.trim() + "'");
// TODO: 7 - Split the 'csv' string by commas into a String array and print each element
// Hint: Use .split(",") then loop through the resulting array
-
+ String[] fruits = csv.split(",");
+ for (String fruit : fruits) {
+ System.out.println(fruit);
+ }
// TODO: 8 - Check if two strings are equal using .equals() (not ==)
// Create two String variables with the same text content and compare them.
// Print the result of .equals() and explain why == may not work for Strings.
+ String str1 = new String("Hello");
+ String str2 = new String("Hello");
+ System.out.println("str1.equals(str2): " + str1.equals(str2));
+ System.out.println("str1 == str2: " + (str1 == str2));
+ System.out.println("== compares references, .equals() compares content");
}
}
diff --git a/src/main/java/com/amigoscode/beginners/thebasics/TypeCasting.java b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/TypeCasting.java
similarity index 61%
rename from src/main/java/com/amigoscode/beginners/thebasics/TypeCasting.java
rename to src/main/java/com/amigoscode/_1_beginners/_1_thebasics/TypeCasting.java
index 4ba7b63..8c62541 100644
--- a/src/main/java/com/amigoscode/beginners/thebasics/TypeCasting.java
+++ b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/TypeCasting.java
@@ -1,4 +1,4 @@
-package com.amigoscode.beginners.thebasics;
+package com.amigoscode._1_beginners._1_thebasics;
/**
* Exercise: Type Casting
@@ -14,31 +14,46 @@ public static void main(String[] args) {
// TODO: 1 - Widen an int to a double (implicit casting)
// Declare an int variable with any value, then assign it to a double variable.
// Print both variables to see the result.
-
+ int myInt = 10;
+ double myDouble = myInt;
+ System.out.println("int value: " + myInt);
+ System.out.println("double value: " + myDouble);
// TODO: 2 - Narrow a double to an int (explicit casting)
// Declare a double variable (e.g., 9.78), then cast it to an int.
// Print both variables to see what happens to the decimal part.
-
+ double myDouble2 = 9.78;
+ int myInt2 = (int) myDouble2;
+ System.out.println("double value: " + myDouble2);
+ System.out.println("int value: " + myInt2);
// TODO: 3 - Cast an int to a char to get the character it represents
// Hint: int value 65 corresponds to 'A' in ASCII
// Print the resulting char.
-
+ int asciiValue = 65;
+ char character = (char) asciiValue;
+ System.out.println("Character: " + character);
// TODO: 4 - Cast a char to an int to get its ASCII value
// Hint: char 'Z' has an ASCII value of 90
// Print the resulting int.
-
+ char letter = 'Z';
+ int letterAscii = (int) letter;
+ System.out.println("ASCII value of Z: " + letterAscii);
// TODO: 5 - Convert a String "42" to an int using Integer.parseInt()
// Declare a String variable with the value "42", then parse it to an int.
// Print the result.
-
+ String numberStr = "42";
+ int parsedNumber = Integer.parseInt(numberStr);
+ System.out.println("Parsed int: " + parsedNumber);
// TODO: 6 - Convert an int 42 to a String using String.valueOf()
// Declare an int variable with the value 42, then convert it to a String.
// Print the result.
+ int num = 42;
+ String numStr = String.valueOf(num);
+ System.out.println("String value: " + numStr);
}
}
diff --git a/src/main/java/com/amigoscode/beginners/thebasics/Variables.java b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/Variables.java
similarity index 67%
rename from src/main/java/com/amigoscode/beginners/thebasics/Variables.java
rename to src/main/java/com/amigoscode/_1_beginners/_1_thebasics/Variables.java
index d69115e..c568303 100644
--- a/src/main/java/com/amigoscode/beginners/thebasics/Variables.java
+++ b/src/main/java/com/amigoscode/_1_beginners/_1_thebasics/Variables.java
@@ -1,4 +1,4 @@
-package com.amigoscode.beginners.thebasics;
+package com.amigoscode._1_beginners._1_thebasics;
/**
* Exercise: Variables and Data Types
@@ -11,27 +11,33 @@ public class Variables {
public static void main(String[] args) {
// TODO: 1 - Declare an int variable called age and assign it the value 25
-
+ int age = 25;
// TODO: 2 - Declare a double variable called price and assign it the value 9.99
-
+ double price = 9.99;
// TODO: 3 - Declare a boolean variable called isJavaFun and assign it the value true
-
+ boolean isJavaFun = true;
// TODO: 4 - Declare a String variable called name and assign it your name
-
+ String name = "Amigos";
// TODO: 5 - Declare a char variable called grade and assign it the value 'A'
-
+ char grade = 'A';
// TODO: 6 - Print all the variables above using System.out.println
// Hint: You can print each variable on its own line, e.g.:
// System.out.println("Age: " + age);
-
+ System.out.println("Age: " + age);
+ System.out.println("Price: " + price);
+ System.out.println("Is Java Fun: " + isJavaFun);
+ System.out.println("Name: " + name);
+ System.out.println("Grade: " + grade);
// TODO: 7 - Declare a final (constant) variable called MAX_SCORE, set it to 100, and print it
// Hint: Use the 'final' keyword before the type to make a constant
+ final int MAX_SCORE = 100;
+ System.out.println("Max Score: " + MAX_SCORE);
}
}
diff --git a/src/main/java/com/amigoscode/developers/exceptions/CustomException.java b/src/main/java/com/amigoscode/_2_developers/_10_exceptions/CustomException.java
similarity index 55%
rename from src/main/java/com/amigoscode/developers/exceptions/CustomException.java
rename to src/main/java/com/amigoscode/_2_developers/_10_exceptions/CustomException.java
index b3520a7..cbf42e9 100644
--- a/src/main/java/com/amigoscode/developers/exceptions/CustomException.java
+++ b/src/main/java/com/amigoscode/_2_developers/_10_exceptions/CustomException.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.exceptions;
+package com.amigoscode._2_developers._10_exceptions;
/**
* Custom Exception Exercises
@@ -16,7 +16,18 @@ public class CustomException {
// calls super(message), and stores the amount
// - Have a getter: double getAmount()
// Define it as a static inner class here, or as a separate class in this package.
+ static class InsufficientFundsException extends Exception {
+ private final double amount;
+ public InsufficientFundsException(String message, double amount) {
+ super(message);
+ this.amount = amount;
+ }
+
+ public double getAmount() {
+ return amount;
+ }
+ }
// TODO: 2 - Create a custom UNCHECKED exception class called InvalidAgeException.
// It should:
@@ -25,7 +36,15 @@ public class CustomException {
// - Have a constructor that takes a String message and a Throwable cause,
// and calls super(message, cause)
// Define it as a static inner class here.
+ static class InvalidAgeException extends RuntimeException {
+ public InvalidAgeException(String message) {
+ super(message);
+ }
+ public InvalidAgeException(String message, Throwable cause) {
+ super(message, cause);
+ }
+ }
// TODO: 3 - Create a static inner class BankAccount with:
// - A private double 'balance' field
@@ -35,11 +54,34 @@ public class CustomException {
// message and the shortfall amount (amount - balance).
// Otherwise, subtract amount from balance.
// - A method: double getBalance()
+ static class BankAccount {
+ private double balance;
+
+ public BankAccount(double balance) {
+ this.balance = balance;
+ }
+ public void withdraw(double amount) throws InsufficientFundsException {
+ if (amount > balance) {
+ throw new InsufficientFundsException("Insufficient funds. Short by " + (amount - balance), amount - balance);
+ }
+ balance -= amount;
+ }
+
+ public double getBalance() {
+ return balance;
+ }
+ }
// TODO: 4 - Create a static method: void validateAge(int age)
// If age < 0 or age > 150, throw a new InvalidAgeException with an appropriate message.
// Otherwise, print "Age " + age + " is valid."
+ public static void validateAge(int age) {
+ if (age < 0 || age > 150) {
+ throw new InvalidAgeException("Invalid age: " + age);
+ }
+ System.out.println("Age " + age + " is valid.");
+ }
public static void main(String[] args) {
@@ -50,7 +92,21 @@ public static void main(String[] args) {
// Catch the exception and print its message and the shortage amount.
// Also try validateAge with valid (25) and invalid (-5) values,
// catching InvalidAgeException.
+ BankAccount account = new BankAccount(100);
+ try {
+ account.withdraw(50);
+ System.out.println("Balance after withdrawing 50: " + account.getBalance());
+ account.withdraw(75);
+ } catch (InsufficientFundsException e) {
+ System.out.println("Caught: " + e.getMessage() + ", shortage: " + e.getAmount());
+ }
+ try {
+ validateAge(25);
+ validateAge(-5);
+ } catch (InvalidAgeException e) {
+ System.out.println("Caught: " + e.getMessage());
+ }
System.out.println("\n=== Exception Chaining ===");
// TODO: 6 - Demonstrate exception chaining:
@@ -61,6 +117,15 @@ public static void main(String[] args) {
// In an outer try-catch, catch the InvalidAgeException and print:
// - The exception message
// - The cause (using getCause())
-
+ try {
+ try {
+ Integer.parseInt("abc");
+ } catch (NumberFormatException e) {
+ throw new InvalidAgeException("Failed to parse age", e);
+ }
+ } catch (InvalidAgeException e) {
+ System.out.println("Exception message: " + e.getMessage());
+ System.out.println("Cause: " + e.getCause());
+ }
}
}
diff --git a/src/main/java/com/amigoscode/developers/exceptions/TryCatch.java b/src/main/java/com/amigoscode/_2_developers/_10_exceptions/TryCatch.java
similarity index 82%
rename from src/main/java/com/amigoscode/developers/exceptions/TryCatch.java
rename to src/main/java/com/amigoscode/_2_developers/_10_exceptions/TryCatch.java
index 06b70a5..8b592db 100644
--- a/src/main/java/com/amigoscode/developers/exceptions/TryCatch.java
+++ b/src/main/java/com/amigoscode/_2_developers/_10_exceptions/TryCatch.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.exceptions;
+package com.amigoscode._2_developers._10_exceptions;
import java.util.Scanner;
@@ -23,7 +23,12 @@ public static int safeArrayAccess(int[] arr, int index) {
// try to return arr[index].
// catch ArrayIndexOutOfBoundsException, print "Index out of bounds: " + index,
// and return -1.
- return 0;
+ try {
+ return arr[index];
+ } catch (ArrayIndexOutOfBoundsException e) {
+ System.out.println("Index out of bounds: " + index);
+ return -1;
+ }
}
/**
@@ -36,7 +41,12 @@ public static int safeArrayAccess(int[] arr, int index) {
public static int safeParseInt(String text) {
// TODO: 2 - Wrap Integer.parseInt(text) in a try-catch block.
// catch NumberFormatException, print "Cannot parse: " + text, and return 0.
- return 0;
+ try {
+ return Integer.parseInt(text);
+ } catch (NumberFormatException e) {
+ System.out.println("Cannot parse: " + text);
+ return 0;
+ }
}
/**
@@ -54,7 +64,16 @@ public static int divideWithFinally(int a, int b) {
// finally: print "Division operation completed."
// Return the result. (You'll need a local variable since return in try
// executes after finally.)
- return 0;
+ int result = 0;
+ try {
+ result = a / b;
+ } catch (ArithmeticException e) {
+ System.out.println("Cannot divide by zero!");
+ result = 0;
+ } finally {
+ System.out.println("Division operation completed.");
+ }
+ return result;
}
/**
@@ -72,7 +91,12 @@ public static int multiCatchDemo(String[] data, int index) {
// Catch both ArrayIndexOutOfBoundsException and NumberFormatException
// in a single catch block using: catch (ExType1 | ExType2 e)
// Print "Error: " + e.getMessage() and return -1.
- return 0;
+ try {
+ return Integer.parseInt(data[index]);
+ } catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
+ System.out.println("Error: " + e.getMessage());
+ return -1;
+ }
}
/**
@@ -89,7 +113,11 @@ public static int tryWithResourcesDemo(String input) {
// }
// catch any exception and return -1.
// The Scanner will be automatically closed after the try block.
- return 0;
+ try (Scanner scanner = new Scanner(input)) {
+ return scanner.nextInt();
+ } catch (Exception e) {
+ return -1;
+ }
}
/**
@@ -103,6 +131,7 @@ public static int validateAge(int age) {
// TODO: 6 - If age < 0, throw a new IllegalArgumentException
// with the message "Age cannot be negative: " + age.
// Otherwise, return age.
+ if (age < 0) throw new IllegalArgumentException("Age cannot be negative: " + age);
return age;
}
@@ -120,7 +149,8 @@ public static int processValue(String value) {
// Then call validateAge() with the parsed int.
// Do NOT catch any exceptions here — let them propagate to the caller.
// This demonstrates that exceptions travel up the call stack.
- return 0;
+ int parsed = Integer.parseInt(value);
+ return validateAge(parsed);
}
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/developers/files/FileReading.java b/src/main/java/com/amigoscode/_2_developers/_11_files/FileReading.java
similarity index 85%
rename from src/main/java/com/amigoscode/developers/files/FileReading.java
rename to src/main/java/com/amigoscode/_2_developers/_11_files/FileReading.java
index cd95ccb..6ac2ed2 100644
--- a/src/main/java/com/amigoscode/developers/files/FileReading.java
+++ b/src/main/java/com/amigoscode/_2_developers/_11_files/FileReading.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.files;
+package com.amigoscode._2_developers._11_files;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
@@ -30,7 +30,7 @@ public class FileReading {
public static List readAllLines(String filePath) throws IOException {
// TODO: 1 - Use Files.readAllLines(Path.of(filePath)) to read all lines.
// Return the resulting List.
- return null;
+ return Files.readAllLines(Path.of(filePath));
}
/**
@@ -46,7 +46,12 @@ public static void readWithBufferedReader(String filePath) throws IOException {
// read lines in a loop using reader.readLine() until it returns null.
// Print each line.
// }
-
+ try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ System.out.println(line);
+ }
+ }
}
/**
@@ -60,7 +65,7 @@ public static long countLines(String filePath) throws IOException {
// TODO: 3 - Read the file line by line and count the lines.
// You can use Files.readAllLines() and call .size(),
// or use Files.lines() with .count() for a stream-based approach.
- return 0;
+ return Files.readAllLines(Path.of(filePath)).size();
}
/**
@@ -76,7 +81,9 @@ public static List searchWord(String filePath, String word) throws IOExc
// Filter the lines to only include those that contain the given word.
// Hint: use a for loop and an ArrayList to collect matching lines,
// or use Files.readAllLines().stream().filter(...).toList()
- return null;
+ return Files.readAllLines(Path.of(filePath)).stream()
+ .filter(line -> line.contains(word))
+ .toList();
}
/**
@@ -89,7 +96,7 @@ public static List searchWord(String filePath, String word) throws IOExc
public static String readFileAsString(String filePath) throws IOException {
// TODO: 5 - Use Files.readString(Path.of(filePath)) to read the entire file
// as a single String. Return it.
- return null;
+ return Files.readString(Path.of(filePath));
}
/**
@@ -103,7 +110,13 @@ public static String handleMissingFile(String filePath) {
// Catch FileNotFoundException (or NoSuchFileException) and return
// "File not found: " + filePath.
// Catch IOException and return "Error reading file: " + e.getMessage().
- return null;
+ try {
+ return Files.readString(Path.of(filePath));
+ } catch (java.nio.file.NoSuchFileException e) {
+ return "File not found: " + filePath;
+ } catch (IOException e) {
+ return "Error reading file: " + e.getMessage();
+ }
}
public static void main(String[] args) throws IOException {
diff --git a/src/main/java/com/amigoscode/developers/files/FileWriting.java b/src/main/java/com/amigoscode/_2_developers/_11_files/FileWriting.java
similarity index 87%
rename from src/main/java/com/amigoscode/developers/files/FileWriting.java
rename to src/main/java/com/amigoscode/_2_developers/_11_files/FileWriting.java
index afe45e5..905593e 100644
--- a/src/main/java/com/amigoscode/developers/files/FileWriting.java
+++ b/src/main/java/com/amigoscode/_2_developers/_11_files/FileWriting.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.files;
+package com.amigoscode._2_developers._11_files;
import java.io.BufferedWriter;
import java.io.FileWriter;
@@ -27,7 +27,7 @@ public class FileWriting {
public static void writeString(String filePath, String content) throws IOException {
// TODO: 1 - Use Files.writeString(Path.of(filePath), content) to write the content.
// This creates the file if it doesn't exist, or overwrites it if it does.
-
+ Files.writeString(Path.of(filePath), content);
}
/**
@@ -41,7 +41,7 @@ public static void appendToFile(String filePath, String text) throws IOException
// TODO: 2 - Use Files.writeString with StandardOpenOption.APPEND to append text.
// Add a newline ("\n") before the text so it appears on a new line.
// Example: Files.writeString(Path.of(filePath), "\n" + text, StandardOpenOption.APPEND);
-
+ Files.writeString(Path.of(filePath), "\n" + text, StandardOpenOption.APPEND);
}
/**
@@ -54,7 +54,7 @@ public static void appendToFile(String filePath, String text) throws IOException
public static void writeLines(String filePath, List lines) throws IOException {
// TODO: 3 - Use Files.write(Path.of(filePath), lines) to write all lines.
// Each string in the list becomes one line in the file.
-
+ Files.write(Path.of(filePath), lines);
}
/**
@@ -73,7 +73,13 @@ public static void writeWithBufferedWriter(String filePath) throws IOException {
// writer.newLine();
// writer.write("Line 3");
// }
-
+ try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
+ writer.write("Line 1");
+ writer.newLine();
+ writer.write("Line 2");
+ writer.newLine();
+ writer.write("Line 3");
+ }
}
/**
@@ -89,7 +95,8 @@ public static void copyFile(String sourcePath, String destinationPath) throws IO
// or Files.copy(Path.of(sourcePath), Path.of(destinationPath)) for a direct copy.
// Note: Files.copy will throw if destination already exists unless you add
// StandardCopyOption.REPLACE_EXISTING.
-
+ String content = Files.readString(Path.of(sourcePath));
+ Files.writeString(Path.of(destinationPath), content);
}
/**
@@ -106,7 +113,12 @@ public static void writeCsv(String filePath, String[] headers, String[][] rows)
// Then, for each row, write the values joined by commas, followed by a newline.
// Use StringBuilder or String.join(",", array) to build each line.
// Write the complete result using Files.writeString().
-
+ StringBuilder sb = new StringBuilder();
+ sb.append(String.join(",", headers)).append("\n");
+ for (String[] row : rows) {
+ sb.append(String.join(",", row)).append("\n");
+ }
+ Files.writeString(Path.of(filePath), sb.toString());
}
public static void main(String[] args) throws IOException {
diff --git a/src/main/java/com/amigoscode/_2_developers/_12_classes/ClassesAndObjects.java b/src/main/java/com/amigoscode/_2_developers/_12_classes/ClassesAndObjects.java
new file mode 100644
index 0000000..f0418ee
--- /dev/null
+++ b/src/main/java/com/amigoscode/_2_developers/_12_classes/ClassesAndObjects.java
@@ -0,0 +1,85 @@
+package com.amigoscode._2_developers._12_classes;
+
+import java.util.Objects;
+
+/**
+ * Classes and Objects Exercises
+ *
+ * Practice creating classes with fields, constructors, and methods.
+ * Learn about constructor chaining, toString(), and equals().
+ */
+public class ClassesAndObjects {
+
+ // TODO: 1 - Create a static inner class called Person with:
+ // - A private String field 'name'
+ // - A private int field 'age'
+
+ // TODO: 2 - Add a constructor to Person that takes String name and int age,
+ // and assigns them to the fields.
+
+ // TODO: 3 - Add a no-args constructor to Person that sets name to "Unknown"
+ // and age to 0. Use constructor chaining — call the other constructor
+ // using this("Unknown", 0) instead of setting fields directly.
+
+ // TODO: 4 - Add a toString() method to Person that returns:
+ // "Person{name='', age=}"
+
+ // TODO: 5 - Add an equals() method and hashCode() to Person.
+ static class Person {
+ private String name;
+ private int age;
+
+ public Person(String name, int age) {
+ this.name = name;
+ this.age = age;
+ }
+
+ public Person() {
+ this("Unknown", 0);
+ }
+
+ @Override
+ public String toString() {
+ return "Person{name='" + name + "', age=" + age + "}";
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof Person)) return false;
+ Person person = (Person) o;
+ return age == person.age && Objects.equals(name, person.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, age);
+ }
+ }
+
+
+ public static void main(String[] args) {
+ // TODO: 6 - Create at least three Person objects:
+ // - One using the two-arg constructor (e.g., "Alice", 30)
+ // - One using the no-args constructor
+ // - One with the same name and age as the first
+ // Print all three using System.out.println() (which calls toString()).
+ // Test equals(): compare person1 with person3 (should be true),
+ // and person1 with person2 (should be false).
+ // Print the comparison results.
+ Person person1 = new Person("Alice", 30);
+ Person person2 = new Person();
+ Person person3 = new Person("Alice", 30);
+ System.out.println(person1);
+ System.out.println(person2);
+ System.out.println(person3);
+ System.out.println("person1.equals(person3): " + person1.equals(person3));
+ System.out.println("person1.equals(person2): " + person1.equals(person2));
+
+ // TODO: 7 - Demonstrate constructor chaining with this():
+ // Constructor chaining is when a constructor calls another constructor in the same
+ // class using this(...), avoiding duplicating initialization logic.
+ // The no-args constructor created in TODO 3 already demonstrates this.
+ System.out.println("No-args person: " + person2);
+ }
+}
diff --git a/src/main/java/com/amigoscode/_2_developers/_12_classes/EnumExercises.java b/src/main/java/com/amigoscode/_2_developers/_12_classes/EnumExercises.java
new file mode 100644
index 0000000..5e822e9
--- /dev/null
+++ b/src/main/java/com/amigoscode/_2_developers/_12_classes/EnumExercises.java
@@ -0,0 +1,72 @@
+package com.amigoscode._2_developers._12_classes;
+
+/**
+ * Enum Exercises
+ *
+ * Practice creating and using enums in Java. Enums are special classes that
+ * represent a fixed set of constants. They can have fields, constructors,
+ * and methods just like regular classes.
+ */
+public class EnumExercises {
+
+ // TODO: 1, 2, 3 - Create an enum called Season with descriptions.
+ enum Season {
+ SPRING("Flowers bloom"),
+ SUMMER("Sun shines"),
+ AUTUMN("Leaves fall"),
+ WINTER("Snow falls");
+
+ private final String description;
+
+ Season(String description) {
+ this.description = description;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+ }
+
+ // TODO: 4 - Create an enum called Priority with numeric levels.
+ enum Priority {
+ LOW(1), MEDIUM(2), HIGH(3);
+
+ private final int level;
+
+ Priority(int level) {
+ this.level = level;
+ }
+
+ public int getLevel() {
+ return level;
+ }
+ }
+
+
+ public static void main(String[] args) {
+ System.out.println("=== Season Switch ===");
+ // TODO: 5 - Use a switch statement (or switch expression) with a Season value.
+ // For each season, print a message like "Spring: Flowers bloom"
+ // using the getDescription() method.
+ // Test with Season.SUMMER.
+ Season season = Season.SUMMER;
+ switch (season) {
+ case SPRING -> System.out.println("Spring: " + Season.SPRING.getDescription());
+ case SUMMER -> System.out.println("Summer: " + Season.SUMMER.getDescription());
+ case AUTUMN -> System.out.println("Autumn: " + Season.AUTUMN.getDescription());
+ case WINTER -> System.out.println("Winter: " + Season.WINTER.getDescription());
+ }
+
+ System.out.println("\n=== Iterate Over Enum Values ===");
+ // TODO: 6 - Use Season.values() to get an array of all Season constants.
+ // Loop through them and print each one with its description and ordinal.
+ // Example output: "0: SPRING - Flowers bloom"
+ // Also iterate over Priority.values() and print each with its level.
+ for (Season s : Season.values()) {
+ System.out.println(s.ordinal() + ": " + s + " - " + s.getDescription());
+ }
+ for (Priority p : Priority.values()) {
+ System.out.println(p + " (level " + p.getLevel() + ")");
+ }
+ }
+}
diff --git a/src/main/java/com/amigoscode/developers/staticmembers/StaticExercises.java b/src/main/java/com/amigoscode/_2_developers/_13_staticmembers/StaticExercises.java
similarity index 50%
rename from src/main/java/com/amigoscode/developers/staticmembers/StaticExercises.java
rename to src/main/java/com/amigoscode/_2_developers/_13_staticmembers/StaticExercises.java
index 153f50d..7677fd8 100644
--- a/src/main/java/com/amigoscode/developers/staticmembers/StaticExercises.java
+++ b/src/main/java/com/amigoscode/_2_developers/_13_staticmembers/StaticExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.staticmembers;
+package com.amigoscode._2_developers._13_staticmembers;
/**
* Static Members Exercises
@@ -11,6 +11,7 @@ public class StaticExercises {
// TODO: 1 - Create a private static int field called 'counter' initialized to 0.
// This field is shared among ALL instances of StaticExercises.
+ private static int counter = 0;
// An instance field for comparison (already provided)
private String instanceName;
@@ -18,56 +19,60 @@ public class StaticExercises {
// TODO: 2 - Create a constructor that takes a String name parameter.
// Assign the name to instanceName.
// Increment the static counter by 1 each time a new instance is created.
-
+ public StaticExercises(String name) {
+ this.instanceName = name;
+ counter++;
+ }
// TODO: 3 - Create a public static method: int getCount()
// Returns the current value of counter.
// Note: static methods can only access static fields, not instance fields.
-
+ public static int getCount() {
+ return counter;
+ }
// TODO: 4 - Create a public static utility method: double celsiusToFahrenheit(double celsius)
// Returns the temperature in Fahrenheit using the formula: (celsius * 9/5) + 32.
- // Utility methods are a common use case for static methods — they don't need
- // any instance state.
-
+ public static double celsiusToFahrenheit(double celsius) {
+ return (celsius * 9.0 / 5.0) + 32;
+ }
// TODO: 5 - Create a public method (non-static): String getInfo()
// Returns "Instance: , Total instances: "
- // This demonstrates that instance methods can access BOTH instance and static fields.
- // A static method could NOT access instanceName.
-
+ public String getInfo() {
+ return "Instance: " + instanceName + ", Total instances: " + counter;
+ }
// TODO: 6 - Create a public static factory method: StaticExercises createDefault()
// Returns a new StaticExercises instance with the name "Default".
- // Factory methods are static methods that create and return instances.
- // They are an alternative to constructors and can have descriptive names.
+ public static StaticExercises createDefault() {
+ return new StaticExercises("Default");
+ }
public static void main(String[] args) {
- // Uncomment the code below after completing all TODOs:
-
- // System.out.println("=== Static Counter ===");
- // System.out.println("Count before creating instances: " + getCount());
+ System.out.println("=== Static Counter ===");
+ System.out.println("Count before creating instances: " + getCount());
- // StaticExercises obj1 = new StaticExercises("First");
- // StaticExercises obj2 = new StaticExercises("Second");
- // StaticExercises obj3 = new StaticExercises("Third");
+ StaticExercises obj1 = new StaticExercises("First");
+ StaticExercises obj2 = new StaticExercises("Second");
+ StaticExercises obj3 = new StaticExercises("Third");
- // System.out.println("Count after creating 3 instances: " + getCount());
+ System.out.println("Count after creating 3 instances: " + getCount());
- // System.out.println("\n=== Static Utility Method ===");
- // System.out.println("0°C = " + celsiusToFahrenheit(0) + "°F");
- // System.out.println("100°C = " + celsiusToFahrenheit(100) + "°F");
- // System.out.println("37°C = " + celsiusToFahrenheit(37) + "°F");
+ System.out.println("\n=== Static Utility Method ===");
+ System.out.println("0°C = " + celsiusToFahrenheit(0) + "°F");
+ System.out.println("100°C = " + celsiusToFahrenheit(100) + "°F");
+ System.out.println("37°C = " + celsiusToFahrenheit(37) + "°F");
- // System.out.println("\n=== Static vs Instance ===");
- // System.out.println(obj1.getInfo());
- // System.out.println(obj2.getInfo());
+ System.out.println("\n=== Static vs Instance ===");
+ System.out.println(obj1.getInfo());
+ System.out.println(obj2.getInfo());
// Note: getCount() is called on the class, getInfo() is called on an instance
// StaticExercises.getCount() works, but StaticExercises.getInfo() does NOT compile
- // System.out.println("\n=== Static Factory Method ===");
- // StaticExercises defaultObj = StaticExercises.createDefault();
- // System.out.println(defaultObj.getInfo());
+ System.out.println("\n=== Static Factory Method ===");
+ StaticExercises defaultObj = StaticExercises.createDefault();
+ System.out.println(defaultObj.getInfo());
}
}
diff --git a/src/main/java/com/amigoscode/developers/nullhandling/OptionalExercises.java b/src/main/java/com/amigoscode/_2_developers/_14_nullhandling/OptionalExercises.java
similarity index 94%
rename from src/main/java/com/amigoscode/developers/nullhandling/OptionalExercises.java
rename to src/main/java/com/amigoscode/_2_developers/_14_nullhandling/OptionalExercises.java
index d87c2b0..f0ed9a6 100644
--- a/src/main/java/com/amigoscode/developers/nullhandling/OptionalExercises.java
+++ b/src/main/java/com/amigoscode/_2_developers/_14_nullhandling/OptionalExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.nullhandling;
+package com.amigoscode._2_developers._14_nullhandling;
import java.util.NoSuchElementException;
import java.util.Optional;
@@ -22,7 +22,7 @@ public class OptionalExercises {
public static Optional createOptional(String value) {
// TODO: 1 - Use Optional.of(value) to create and return an Optional.
// Note: Optional.of() will throw NullPointerException if value is null.
- return null;
+ return Optional.of(value);
}
/**
@@ -35,7 +35,7 @@ public static Optional createOptional(String value) {
public static Optional createNullableOptional(String value) {
// TODO: 2 - Use Optional.ofNullable(value) to safely create an Optional.
// This returns Optional.empty() if value is null, or Optional.of(value) otherwise.
- return null;
+ return Optional.ofNullable(value);
}
/**
@@ -50,7 +50,7 @@ public static String checkAndGet(Optional optional) {
// If present, return optional.get().
// If not present, return "EMPTY".
// Note: calling get() on an empty Optional throws NoSuchElementException!
- return null;
+ return optional.isPresent() ? optional.get() : "EMPTY";
}
/**
@@ -64,7 +64,7 @@ public static String getOrDefault(Optional optional, String defaultValue
// TODO: 4 - Use optional.orElse(defaultValue) to return the value if present,
// or defaultValue if the Optional is empty.
// This is cleaner than using isPresent() + get().
- return null;
+ return optional.orElse(defaultValue);
}
/**
@@ -79,7 +79,7 @@ public static String getOrThrow(Optional optional) {
// or throw NoSuchElementException if empty.
// You can also use orElseThrow(() -> new RuntimeException("No value!"))
// to throw a custom exception.
- return null;
+ return optional.orElseThrow();
}
/**
@@ -93,7 +93,7 @@ public static Optional transformValue(Optional optional) {
// TODO: 6 - Use optional.map(String::toUpperCase) to transform the value.
// map() applies the function if a value is present, and returns a new Optional.
// If the original Optional is empty, map() returns an empty Optional.
- return null;
+ return optional.map(String::toUpperCase);
}
/**
@@ -108,7 +108,7 @@ public static Optional extractDomain(Optional emailOptional) {
// flatMap() is like map(), but used when the transformation function itself
// returns an Optional. It "flattens" Optional> to Optional.
// Call: emailOptional.flatMap(OptionalExercises::getDomain)
- return null;
+ return emailOptional.flatMap(OptionalExercises::getDomain);
}
/**
diff --git a/src/main/java/com/amigoscode/developers/loops/LoopExercises.java b/src/main/java/com/amigoscode/_2_developers/_1_loops/LoopExercises.java
similarity index 79%
rename from src/main/java/com/amigoscode/developers/loops/LoopExercises.java
rename to src/main/java/com/amigoscode/_2_developers/_1_loops/LoopExercises.java
index cac7d9f..900ecfd 100644
--- a/src/main/java/com/amigoscode/developers/loops/LoopExercises.java
+++ b/src/main/java/com/amigoscode/_2_developers/_1_loops/LoopExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.loops;
+package com.amigoscode._2_developers._1_loops;
/**
* Loop Exercises
@@ -21,7 +21,12 @@ public static void printMultiplicationTable(int n) {
// TODO: 1 - Use nested for loops to print an n x n multiplication table.
// Outer loop iterates rows 1..n, inner loop iterates columns 1..n.
// Print each product followed by a tab, and a newline after each row.
-
+ for (int i = 1; i <= n; i++) {
+ for (int j = 1; j <= n; j++) {
+ System.out.print(i * j + "\t");
+ }
+ System.out.println();
+ }
}
/**
@@ -35,7 +40,11 @@ public static int sumWithSkipAndStop(int n) {
int sum = 0;
// TODO: 2 - Loop from 1 to n. Use 'continue' to skip multiples of 3.
// Use 'break' to stop if sum exceeds 100. Add the current number to sum otherwise.
-
+ for (int i = 1; i <= n; i++) {
+ if (i % 3 == 0) continue;
+ sum += i;
+ if (sum > 100) break;
+ }
return sum;
}
@@ -53,7 +62,15 @@ public static String findInMatrix(int[][] matrix, int target) {
// Use nested loops to iterate through the matrix.
// When the target is found, set result to "Found at [row][col]" and
// use 'break search;' to exit both loops.
-
+ search:
+ for (int i = 0; i < matrix.length; i++) {
+ for (int j = 0; j < matrix[i].length; j++) {
+ if (matrix[i][j] == target) {
+ result = "Found at [" + i + "][" + j + "]";
+ break search;
+ }
+ }
+ }
return result;
}
@@ -68,7 +85,9 @@ public static long factorial(int n) {
long accumulator = 1;
// TODO: 4 - Use a for loop from 1 to n (inclusive), multiplying accumulator
// by the loop variable each iteration. Return the result.
-
+ for (int i = 1; i <= n; i++) {
+ accumulator *= i;
+ }
return accumulator;
}
@@ -86,7 +105,15 @@ public static void printPyramid(int rows) {
// TODO: 5 - Use nested loops to print a centered pyramid of stars.
// For each row i (0-based), print (rows - i - 1) spaces followed by (2 * i + 1) stars.
// Print a newline after each row.
-
+ for (int i = 0; i < rows; i++) {
+ for (int j = 0; j < rows - i - 1; j++) {
+ System.out.print(" ");
+ }
+ for (int j = 0; j < 2 * i + 1; j++) {
+ System.out.print("*");
+ }
+ System.out.println();
+ }
}
/**
@@ -100,7 +127,10 @@ public static String iterateBackwards(int[] arr) {
StringBuilder sb = new StringBuilder();
// TODO: 6 - Use a for loop starting from the last index down to 0.
// Append each element to sb. Add ", " between elements but not after the last one.
-
+ for (int i = arr.length - 1; i >= 0; i--) {
+ sb.append(arr[i]);
+ if (i > 0) sb.append(", ");
+ }
return sb.toString();
}
@@ -118,7 +148,11 @@ public static int countUntilMatch(int target) {
// TODO: 7 - Use while(true) to create an infinite loop.
// Each iteration: increment attempts, generate a random int between 1 and 100,
// and break if it matches the target.
-
+ while (true) {
+ attempts++;
+ int guess = random.nextInt(100) + 1;
+ if (guess == target) break;
+ }
return attempts;
}
diff --git a/src/main/java/com/amigoscode/developers/conditionals/IfStatements.java b/src/main/java/com/amigoscode/_2_developers/_2_conditionals/IfStatements.java
similarity index 86%
rename from src/main/java/com/amigoscode/developers/conditionals/IfStatements.java
rename to src/main/java/com/amigoscode/_2_developers/_2_conditionals/IfStatements.java
index 0a569eb..432fcf8 100644
--- a/src/main/java/com/amigoscode/developers/conditionals/IfStatements.java
+++ b/src/main/java/com/amigoscode/_2_developers/_2_conditionals/IfStatements.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.conditionals;
+package com.amigoscode._2_developers._2_conditionals;
/**
* If Statements and Conditional Exercises
@@ -18,7 +18,7 @@ public class IfStatements {
public static String evenOrOdd(int number) {
// TODO: 1 - Use the ternary operator ( condition ? valueIfTrue : valueIfFalse )
// to return "Even" or "Odd" based on whether number % 2 == 0.
- return null;
+ return number % 2 == 0 ? "Even" : "Odd";
}
/**
@@ -33,7 +33,7 @@ public static String evenOrOdd(int number) {
public static boolean isEligibleForLoan(int age, double income, boolean hasGuarantor) {
// TODO: 2 - Use a single return statement with && and || operators
// to express the eligibility condition described above.
- return false;
+ return (age >= 18 && income >= 30000) || (hasGuarantor && age >= 16);
}
/**
@@ -46,7 +46,7 @@ public static boolean isEligibleForLoan(int age, double income, boolean hasGuara
public static String getGrade(int score) {
// TODO: 3 - Use nested ternary operators to return the correct grade.
// Example pattern: score >= 90 ? "A" : score >= 80 ? "B" : ...
- return null;
+ return score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 60 ? "D" : "F";
}
/**
@@ -59,7 +59,7 @@ public static String getGrade(int score) {
public static int safeLength(String text) {
// TODO: 4 - Check if text is null before calling text.length().
// Return -1 if text is null, otherwise return text.length().
- return 0;
+ return text == null ? -1 : text.length();
}
/**
@@ -75,7 +75,9 @@ public static boolean safeEquals(String a, String b) {
// If both are null, return true.
// If only one is null, return false.
// Otherwise, use a.equals(b) — never use == for string content comparison.
- return false;
+ if (a == null && b == null) return true;
+ if (a == null || b == null) return false;
+ return a.equals(b);
}
/**
@@ -95,7 +97,16 @@ public static String getDayName(int day) {
// ...
// default -> "Invalid";
// };
- return null;
+ return switch (day) {
+ case 1 -> "Monday";
+ case 2 -> "Tuesday";
+ case 3 -> "Wednesday";
+ case 4 -> "Thursday";
+ case 5 -> "Friday";
+ case 6 -> "Saturday";
+ case 7 -> "Sunday";
+ default -> "Invalid";
+ };
}
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/developers/packages/PackageDemo.java b/src/main/java/com/amigoscode/_2_developers/_3_packages/PackageDemo.java
similarity index 76%
rename from src/main/java/com/amigoscode/developers/packages/PackageDemo.java
rename to src/main/java/com/amigoscode/_2_developers/_3_packages/PackageDemo.java
index 6868a90..312fb31 100644
--- a/src/main/java/com/amigoscode/developers/packages/PackageDemo.java
+++ b/src/main/java/com/amigoscode/_2_developers/_3_packages/PackageDemo.java
@@ -1,10 +1,14 @@
-package com.amigoscode.developers.packages;
+package com.amigoscode._2_developers._3_packages;
// TODO: 1 - Import java.util.List and java.util.ArrayList, then create a List
// in the useListFromUtil() method below.
-
+import java.util.List;
+import java.util.ArrayList;
// TODO: 2 - Import java.time.LocalDate, then use it in the printToday() method below.
+import java.time.LocalDate;
+
+import static java.lang.Math.PI;
/**
@@ -21,7 +25,11 @@ public class PackageDemo {
public static void useListFromUtil() {
// TODO: 1 (continued) - Create a List using ArrayList, add three fruits,
// and print the list. Make sure you have the import statements at the top.
-
+ List fruits = new ArrayList<>();
+ fruits.add("Apple");
+ fruits.add("Banana");
+ fruits.add("Cherry");
+ System.out.println(fruits);
}
/**
@@ -30,7 +38,7 @@ public static void useListFromUtil() {
public static void printToday() {
// TODO: 2 (continued) - Use LocalDate.now() to get today's date and print it.
// Make sure you have the import statement at the top.
-
+ System.out.println(LocalDate.now());
}
/**
@@ -41,7 +49,10 @@ public static void useFullyQualifiedName() {
// TODO: 3 - Create a java.util.HashMap using the fully qualified
// class name (no import). Put two entries (e.g., "Alice"->90, "Bob"->85) and print it.
// Example: java.util.HashMap map = new java.util.HashMap<>();
-
+ java.util.HashMap map = new java.util.HashMap<>();
+ map.put("Alice", 90);
+ map.put("Bob", 85);
+ System.out.println(map);
}
// TODO: 4 - Add a static import for java.lang.Math.PI at the top of this file,
@@ -57,7 +68,7 @@ public static void useFullyQualifiedName() {
public static double circleArea(double radius) {
// TODO: 4 (continued) - Return PI * radius * radius using the statically imported PI.
// You need to add: import static java.lang.Math.PI; at the top of this file.
- return 0;
+ return PI * radius * radius;
}
/**
@@ -66,10 +77,11 @@ public static double circleArea(double radius) {
*/
public static void useClassFromAnotherPackage() {
// TODO: 5 - Import or use a fully qualified name for a class from another package
- // in this project (e.g., com.amigoscode.developers.conditionals.IfStatements).
+ // in this project (e.g., com.amigoscode._2_developers._2_conditionals.IfStatements).
// Call one of its static methods and print the result.
- // Example: String result = com.amigoscode.developers.conditionals.IfStatements.evenOrOdd(4);
-
+ // Example: String result = com.amigoscode._2_developers._2_conditionals.IfStatements.evenOrOdd(4);
+ String result = com.amigoscode._2_developers._2_conditionals.IfStatements.evenOrOdd(4);
+ System.out.println("4 is " + result);
}
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/developers/accessmodifiers/AccessDemo.java b/src/main/java/com/amigoscode/_2_developers/_4_accessmodifiers/AccessDemo.java
similarity index 71%
rename from src/main/java/com/amigoscode/developers/accessmodifiers/AccessDemo.java
rename to src/main/java/com/amigoscode/_2_developers/_4_accessmodifiers/AccessDemo.java
index b2922dd..e3bef2a 100644
--- a/src/main/java/com/amigoscode/developers/accessmodifiers/AccessDemo.java
+++ b/src/main/java/com/amigoscode/_2_developers/_4_accessmodifiers/AccessDemo.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.accessmodifiers;
+package com.amigoscode._2_developers._4_accessmodifiers;
/**
* Access Modifiers Demo
@@ -10,25 +10,34 @@ public class AccessDemo {
public static void main(String[] args) {
// TODO: 1 - Create an instance of AccessModifiers.
+ AccessModifiers instance = new AccessModifiers();
System.out.println("=== Calling Public Method ===");
// TODO: 2 - Call the publicGreeting() method on your instance and print the result.
// This works because public methods are accessible from anywhere.
+ System.out.println(instance.publicGreeting());
System.out.println("\n=== Calling Package-Private Method ===");
// TODO: 3 - Call the packageGreeting() method on your instance and print the result.
// This works because AccessDemo is in the SAME package as AccessModifiers.
+ System.out.println(instance.packageGreeting());
System.out.println("\n=== Accessing Private Field Through Getter ===");
// TODO: 4 - Use setSecret() to set a value, then use getSecret() to read it back.
// Print the result. This demonstrates proper encapsulation:
// we access the private field only through public getter/setter methods.
+ instance.setSecret("My secret value");
+ System.out.println(instance.getSecret());
System.out.println("\n=== Why Direct Private Access Won't Work ===");
// TODO: 5 - Write a comment explaining why the following line would NOT compile:
// // instance.secret = "trying direct access";
// Then leave the line commented out, preceded by your explanation.
// Hint: think about what 'private' means for field visibility outside the class.
+ // The 'secret' field is declared as private in AccessModifiers, so it is only
+ // accessible within the AccessModifiers class itself. Other classes, even in the
+ // same package, cannot access private fields directly.
+ // instance.secret = "trying direct access";
}
}
diff --git a/src/main/java/com/amigoscode/developers/accessmodifiers/AccessModifiers.java b/src/main/java/com/amigoscode/_2_developers/_4_accessmodifiers/AccessModifiers.java
similarity index 71%
rename from src/main/java/com/amigoscode/developers/accessmodifiers/AccessModifiers.java
rename to src/main/java/com/amigoscode/_2_developers/_4_accessmodifiers/AccessModifiers.java
index 69cbf29..55eeb8f 100644
--- a/src/main/java/com/amigoscode/developers/accessmodifiers/AccessModifiers.java
+++ b/src/main/java/com/amigoscode/_2_developers/_4_accessmodifiers/AccessModifiers.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.accessmodifiers;
+package com.amigoscode._2_developers._4_accessmodifiers;
/**
* Access Modifiers Exercises
@@ -11,27 +11,39 @@ public class AccessModifiers {
// TODO: 1 - Declare a private String field called 'secret'.
// Private means only this class can access it directly.
-
+ private String secret;
// TODO: 2 - Declare a public method called 'publicGreeting' that returns
// the String "Hello from a public method!".
// Public means any class, in any package, can call this method.
-
+ public String publicGreeting() {
+ return "Hello from a public method!";
+ }
// TODO: 3 - Declare a protected method called 'protectedGreeting' that returns
// the String "Hello from a protected method!".
// Protected means accessible within this package and by subclasses in other packages.
-
+ protected String protectedGreeting() {
+ return "Hello from a protected method!";
+ }
// TODO: 4 - Declare a package-private (default) method called 'packageGreeting'
// that returns the String "Hello from a package-private method!".
// Package-private means no access modifier keyword — accessible only within this package.
-
+ String packageGreeting() {
+ return "Hello from a package-private method!";
+ }
// TODO: 5 - Create a getter (getSecret) and a setter (setSecret) for the 'secret' field.
// The getter should be public and return the secret.
// The setter should be public, take a String parameter, and assign it to the field.
+ public String getSecret() {
+ return secret;
+ }
+ public void setSecret(String secret) {
+ this.secret = secret;
+ }
// TODO: 6 - Create a public method called 'demonstrateInternalAccess' that:
// - Sets the secret field directly (not through the setter) to "Internal access works!"
@@ -39,5 +51,9 @@ public class AccessModifiers {
// - Returns a String summarizing: the secret value and all three greetings,
// separated by newlines.
// This demonstrates that within the same class, ALL access levels are accessible.
+ public String demonstrateInternalAccess() {
+ secret = "Internal access works!";
+ return secret + "\n" + publicGreeting() + "\n" + protectedGreeting() + "\n" + packageGreeting();
+ }
}
diff --git a/src/main/java/com/amigoscode/developers/methods/MethodOverloading.java b/src/main/java/com/amigoscode/_2_developers/_5_methods/MethodOverloading.java
similarity index 62%
rename from src/main/java/com/amigoscode/developers/methods/MethodOverloading.java
rename to src/main/java/com/amigoscode/_2_developers/_5_methods/MethodOverloading.java
index e18aaf5..1a4025d 100644
--- a/src/main/java/com/amigoscode/developers/methods/MethodOverloading.java
+++ b/src/main/java/com/amigoscode/_2_developers/_5_methods/MethodOverloading.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.methods;
+package com.amigoscode._2_developers._5_methods;
/**
* Method Overloading Exercises
@@ -11,28 +11,41 @@ public class MethodOverloading {
// TODO: 1 - Create a method: int add(int a, int b)
// Returns the sum of two integers.
-
+ public int add(int a, int b) {
+ return a + b;
+ }
// TODO: 2 - Create an overloaded method: int add(int a, int b, int c)
// Returns the sum of three integers.
-
+ public int add(int a, int b, int c) {
+ return a + b + c;
+ }
// TODO: 3 - Create an overloaded method: double add(double a, double b)
// Returns the sum of two doubles.
-
+ public double add(double a, double b) {
+ return a + b;
+ }
// TODO: 4 - Create a method: String format(String value)
// Returns the string wrapped in square brackets, e.g., "[hello]".
-
+ public String format(String value) {
+ return "[" + value + "]";
+ }
// TODO: 5 - Create an overloaded method: String format(int value)
// Returns the integer formatted with leading zeros to 5 digits.
// Example: format(42) returns "00042".
// Hint: use String.format("%05d", value)
-
+ public String format(int value) {
+ return String.format("%05d", value);
+ }
// TODO: 6 - Create an overloaded method: String format(String label, int value)
// Returns "label: value", e.g., format("Score", 95) returns "Score: 95".
+ public String format(String label, int value) {
+ return label + ": " + value;
+ }
public static void main(String[] args) {
@@ -46,6 +59,11 @@ public static void main(String[] args) {
// - format(42)
// - format("Score", 95)
// Print each result with a descriptive label.
-
+ System.out.println("add(2, 3) = " + mo.add(2, 3));
+ System.out.println("add(1, 2, 3) = " + mo.add(1, 2, 3));
+ System.out.println("add(1.5, 2.5) = " + mo.add(1.5, 2.5));
+ System.out.println("format(\"hello\") = " + mo.format("hello"));
+ System.out.println("format(42) = " + mo.format(42));
+ System.out.println("format(\"Score\", 95) = " + mo.format("Score", 95));
}
}
diff --git a/src/main/java/com/amigoscode/developers/methods/VarArgs.java b/src/main/java/com/amigoscode/_2_developers/_5_methods/VarArgs.java
similarity index 61%
rename from src/main/java/com/amigoscode/developers/methods/VarArgs.java
rename to src/main/java/com/amigoscode/_2_developers/_5_methods/VarArgs.java
index 5053cdc..f600322 100644
--- a/src/main/java/com/amigoscode/developers/methods/VarArgs.java
+++ b/src/main/java/com/amigoscode/_2_developers/_5_methods/VarArgs.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.methods;
+package com.amigoscode._2_developers._5_methods;
/**
* Variable Arguments (Varargs) Exercises
@@ -12,20 +12,35 @@ public class VarArgs {
// Returns the sum of all provided numbers.
// If no arguments are provided, return 0.
// Hint: use a for-each loop to iterate over 'numbers'.
-
+ public int sum(int... numbers) {
+ int total = 0;
+ for (int n : numbers) {
+ total += n;
+ }
+ return total;
+ }
// TODO: 2 - Create a method: String concatenate(String... strings)
// Joins all strings with a single space between them.
// Example: concatenate("Hello", "World") returns "Hello World"
// If no arguments, return an empty string "".
// Hint: use StringBuilder or String.join(" ", strings).
-
+ public String concatenate(String... strings) {
+ return String.join(" ", strings);
+ }
// TODO: 3 - Create a method: int findMax(int... numbers)
// Returns the largest value among the arguments.
// If no arguments are provided, throw an IllegalArgumentException
// with the message "At least one number required".
-
+ public int findMax(int... numbers) {
+ if (numbers.length == 0) throw new IllegalArgumentException("At least one number required");
+ int max = numbers[0];
+ for (int n : numbers) {
+ if (n > max) max = n;
+ }
+ return max;
+ }
// TODO: 4 - Create a method: void printAll(Object... items)
// Prints each item on a separate line, prefixed with its index.
@@ -33,7 +48,23 @@ public class VarArgs {
// [0] Hello
// [1] 42
// [2] true
+ public void printAll(Object... items) {
+ for (int i = 0; i < items.length; i++) {
+ System.out.println("[" + i + "] " + items[i]);
+ }
+ }
+
+ // TODO: 6 - format method with mixed params
+ public String format(String prefix, int... numbers) {
+ StringBuilder sb = new StringBuilder(prefix + ": [");
+ for (int i = 0; i < numbers.length; i++) {
+ sb.append(numbers[i]);
+ if (i < numbers.length - 1) sb.append(", ");
+ }
+ sb.append("]");
+ return sb.toString();
+ }
public static void main(String[] args) {
VarArgs va = new VarArgs();
@@ -44,16 +75,21 @@ public static void main(String[] args) {
// - sum(5) -> 5 (one arg)
// - sum(1, 2, 3, 4) -> 10 (many args)
// Print each result.
-
+ System.out.println("sum() = " + va.sum());
+ System.out.println("sum(5) = " + va.sum(5));
+ System.out.println("sum(1, 2, 3, 4) = " + va.sum(1, 2, 3, 4));
System.out.println("\n=== Concatenate ===");
// Print: concatenate("Java", "is", "awesome")
+ System.out.println(va.concatenate("Java", "is", "awesome"));
System.out.println("\n=== Find Max ===");
// Print: findMax(3, 7, 2, 9, 1)
+ System.out.println("Max: " + va.findMax(3, 7, 2, 9, 1));
System.out.println("\n=== Print All ===");
// Call: printAll("Hello", 42, true, 3.14)
+ va.printAll("Hello", 42, true, 3.14);
System.out.println("\n=== Mixed Params ===");
// TODO: 6 - Create a method: String format(String prefix, int... numbers)
@@ -62,6 +98,6 @@ public static void main(String[] args) {
// Example: format("Values", 1, 2, 3) returns "Values: [1, 2, 3]"
// Hint: varargs must be the LAST parameter in the method signature.
// Then call the method and print the result here.
-
+ System.out.println(va.format("Values", 1, 2, 3));
}
}
diff --git a/src/main/java/com/amigoscode/developers/strings/StringBuilderExercises.java b/src/main/java/com/amigoscode/_2_developers/_6_strings/StringBuilderExercises.java
similarity index 78%
rename from src/main/java/com/amigoscode/developers/strings/StringBuilderExercises.java
rename to src/main/java/com/amigoscode/_2_developers/_6_strings/StringBuilderExercises.java
index 6cef145..9e5cf0a 100644
--- a/src/main/java/com/amigoscode/developers/strings/StringBuilderExercises.java
+++ b/src/main/java/com/amigoscode/_2_developers/_6_strings/StringBuilderExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.strings;
+package com.amigoscode._2_developers._6_strings;
/**
* StringBuilder Exercises
@@ -20,7 +20,9 @@ public static String buildGreeting(String name, int age) {
// TODO: 1 - Create a new StringBuilder.
// Append "Hello, ", then name, then "! You are ", then age, then " years old."
// Convert to String and return.
- return null;
+ StringBuilder sb = new StringBuilder();
+ sb.append("Hello, ").append(name).append("! You are ").append(age).append(" years old.");
+ return sb.toString();
}
/**
@@ -36,7 +38,10 @@ public static String insertMiddleName(String fullName, String middleName) {
// Find the index of the first space using indexOf(" ").
// Insert middleName + " " at position (spaceIndex + 1).
// Convert to String and return.
- return null;
+ StringBuilder sb = new StringBuilder(fullName);
+ int spaceIndex = sb.indexOf(" ");
+ sb.insert(spaceIndex + 1, middleName + " ");
+ return sb.toString();
}
/**
@@ -51,7 +56,13 @@ public static String removeVowels(String text) {
// Use deleteCharAt(i) to remove characters that are vowels.
// Hint: check if "aeiouAEIOU".indexOf(ch) >= 0
// Convert to String and return.
- return null;
+ StringBuilder sb = new StringBuilder(text);
+ for (int i = sb.length() - 1; i >= 0; i--) {
+ if ("aeiouAEIOU".indexOf(sb.charAt(i)) >= 0) {
+ sb.deleteCharAt(i);
+ }
+ }
+ return sb.toString();
}
/**
@@ -62,7 +73,7 @@ public static String removeVowels(String text) {
*/
public static String reverseText(String text) {
// TODO: 4 - Create a StringBuilder from text, call reverse(), convert to String.
- return null;
+ return new StringBuilder(text).reverse().toString();
}
/**
@@ -78,7 +89,11 @@ public static String convertDemo(String text) {
// Call toUpperCase() on that String (String method, not StringBuilder).
// Create a new StringBuilder from the uppercased String, append "!!!"
// Return the final String.
- return null;
+ StringBuilder sb = new StringBuilder(text);
+ String upper = sb.toString().toUpperCase();
+ StringBuilder result = new StringBuilder(upper);
+ result.append("!!!");
+ return result.toString();
}
/**
@@ -94,7 +109,12 @@ public static String buildCsvLine(String[] values) {
// Append each value, and append a comma between values (but NOT after the last one).
// Hint: you can check if it's not the last element, or use deleteCharAt at the end.
// Return the result as a String.
- return null;
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < values.length; i++) {
+ sb.append(values[i]);
+ if (i < values.length - 1) sb.append(",");
+ }
+ return sb.toString();
}
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/developers/strings/StringMethods.java b/src/main/java/com/amigoscode/_2_developers/_6_strings/StringMethods.java
similarity index 85%
rename from src/main/java/com/amigoscode/developers/strings/StringMethods.java
rename to src/main/java/com/amigoscode/_2_developers/_6_strings/StringMethods.java
index 814385f..81a472a 100644
--- a/src/main/java/com/amigoscode/developers/strings/StringMethods.java
+++ b/src/main/java/com/amigoscode/_2_developers/_6_strings/StringMethods.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.strings;
+package com.amigoscode._2_developers._6_strings;
/**
* String Methods Exercises
@@ -19,7 +19,7 @@ public class StringMethods {
public static String compareEquality(String a, String b) {
// TODO: 1 - Use equals() and equalsIgnoreCase() to compare a and b.
// Return a string in the format: "equals: , equalsIgnoreCase: "
- return null;
+ return "equals: " + a.equals(b) + ", equalsIgnoreCase: " + a.equalsIgnoreCase(b);
}
/**
@@ -33,7 +33,8 @@ public static String compareEquality(String a, String b) {
public static String compareLexicographic(String a, String b) {
// TODO: 2 - Use a.compareTo(b) and return:
// "before" if result < 0, "equal" if result == 0, "after" if result > 0.
- return null;
+ int cmp = a.compareTo(b);
+ return cmp < 0 ? "before" : cmp == 0 ? "equal" : "after";
}
/**
@@ -48,7 +49,7 @@ public static String searchString(String text, String keyword) {
// TODO: 3 - Use contains() to check if text contains keyword.
// Use indexOf() to find the position of keyword in text.
// Return "contains: , indexOf: "
- return null;
+ return "contains: " + text.contains(keyword) + ", indexOf: " + text.indexOf(keyword);
}
/**
@@ -64,7 +65,7 @@ public static String replaceDemo(String text, String oldWord, String newWord) {
// TODO: 4 - First use replace(oldWord, newWord) to swap words.
// Then use replaceAll("\\d", "#") to replace all digits with "#".
// Return the final result.
- return null;
+ return text.replace(oldWord, newWord).replaceAll("\\d", "#");
}
/**
@@ -79,7 +80,13 @@ public static String splitDemo(String text, String delimiter) {
// TODO: 5 - Use text.split(delimiter) to get an array of parts.
// Build a result string with each part on a new line: "[i] part"
// Example: "[0] apple\n[1] banana\n[2] cherry"
- return null;
+ String[] parts = text.split(delimiter);
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < parts.length; i++) {
+ sb.append("[").append(i).append("] ").append(parts[i]);
+ if (i < parts.length - 1) sb.append("\n");
+ }
+ return sb.toString();
}
/**
@@ -93,7 +100,7 @@ public static String splitDemo(String text, String delimiter) {
public static String checkStartEnd(String filename, String prefix, String extension) {
// TODO: 6 - Use startsWith(prefix) and endsWith(extension).
// Return: "startsWith '': , endsWith '': "
- return null;
+ return "startsWith '" + prefix + "': " + filename.startsWith(prefix) + ", endsWith '" + extension + "': " + filename.endsWith(extension);
}
/**
@@ -107,7 +114,7 @@ public static String checkStartEnd(String filename, String prefix, String extens
public static String substringDemo(String text, int beginIndex, int endIndex) {
// TODO: 7 - Use text.substring(beginIndex, endIndex) to extract a portion of text.
// Return the substring.
- return null;
+ return text.substring(beginIndex, endIndex);
}
/**
@@ -122,7 +129,7 @@ public static String substringDemo(String text, int beginIndex, int endIndex) {
public static String formatReceipt(String item, int quantity, double price) {
// TODO: 8 - Use String.format() to create a formatted string.
// Format: "%-15s x%-5d $%.2f" (left-align item in 15 chars, quantity in 5, price with 2 decimals)
- return null;
+ return String.format("%-15s x%-5d $%.2f", item, quantity, price);
}
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/developers/dates/DateExercises.java b/src/main/java/com/amigoscode/_2_developers/_7_dates/DateExercises.java
similarity index 88%
rename from src/main/java/com/amigoscode/developers/dates/DateExercises.java
rename to src/main/java/com/amigoscode/_2_developers/_7_dates/DateExercises.java
index 2804f43..54f6fe2 100644
--- a/src/main/java/com/amigoscode/developers/dates/DateExercises.java
+++ b/src/main/java/com/amigoscode/_2_developers/_7_dates/DateExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.dates;
+package com.amigoscode._2_developers._7_dates;
import java.time.LocalDate;
import java.time.LocalDateTime;
@@ -20,7 +20,7 @@ public class DateExercises {
*/
public static LocalDate getToday() {
// TODO: 1 - Use LocalDate.now() to get and return today's date.
- return null;
+ return LocalDate.now();
}
/**
@@ -30,7 +30,7 @@ public static LocalDate getToday() {
*/
public static LocalDate getIndependenceDay() {
// TODO: 2 - Use LocalDate.of(year, month, day) to create and return July 4, 1776.
- return null;
+ return LocalDate.of(1776, 7, 4);
}
/**
@@ -40,7 +40,7 @@ public static LocalDate getIndependenceDay() {
*/
public static LocalDateTime getCurrentDateTime() {
// TODO: 3 - Use LocalDateTime.now() to get and return the current date and time.
- return null;
+ return LocalDateTime.now();
}
/**
@@ -56,7 +56,7 @@ public static LocalDate addToDate(LocalDate date, int days, int months, int year
// TODO: 4 - Use plusDays(), plusMonths(), and plusYears() on the date.
// Remember: LocalDate is immutable, so each method returns a NEW LocalDate.
// Chain the calls or apply them sequentially.
- return null;
+ return date.plusDays(days).plusMonths(months).plusYears(years);
}
/**
@@ -69,7 +69,9 @@ public static LocalDate addToDate(LocalDate date, int days, int months, int year
public static String compareDates(LocalDate date1, LocalDate date2) {
// TODO: 5 - Use isBefore() and isAfter() methods on date1 to compare with date2.
// Return "before", "after", or "equal".
- return null;
+ if (date1.isBefore(date2)) return "before";
+ if (date1.isAfter(date2)) return "after";
+ return "equal";
}
/**
@@ -84,7 +86,8 @@ public static String formatDate(LocalDate date, String pattern) {
// TODO: 6 - Create a DateTimeFormatter using DateTimeFormatter.ofPattern(pattern).
// Use date.format(formatter) to format the date.
// Return the formatted string.
- return null;
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
+ return date.format(formatter);
}
/**
@@ -98,7 +101,8 @@ public static LocalDate parseDate(String dateString) {
// TODO: 7 - Create a DateTimeFormatter with the pattern "dd-MM-yyyy".
// Use LocalDate.parse(dateString, formatter) to parse the string.
// Return the resulting LocalDate.
- return null;
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
+ return LocalDate.parse(dateString, formatter);
}
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/developers/bigdecimal/BigDecimalExercises.java b/src/main/java/com/amigoscode/_2_developers/_8_bigdecimal/BigDecimalExercises.java
similarity index 89%
rename from src/main/java/com/amigoscode/developers/bigdecimal/BigDecimalExercises.java
rename to src/main/java/com/amigoscode/_2_developers/_8_bigdecimal/BigDecimalExercises.java
index 7cbf672..025f4dd 100644
--- a/src/main/java/com/amigoscode/developers/bigdecimal/BigDecimalExercises.java
+++ b/src/main/java/com/amigoscode/_2_developers/_8_bigdecimal/BigDecimalExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.bigdecimal;
+package com.amigoscode._2_developers._8_bigdecimal;
import java.math.BigDecimal;
import java.math.RoundingMode;
@@ -23,7 +23,7 @@ public static BigDecimal createFromString(String value) {
// TODO: 1 - Create and return a BigDecimal using new BigDecimal(value).
// The String constructor preserves the exact decimal value.
// NEVER use new BigDecimal(0.1) — see TODO 6 for why.
- return null;
+ return new BigDecimal(value);
}
/**
@@ -36,7 +36,7 @@ public static BigDecimal createFromString(String value) {
public static BigDecimal addValues(BigDecimal a, BigDecimal b) {
// TODO: 2 - Use the add() method to add a and b. Return the result.
// Remember: BigDecimal is immutable, so add() returns a NEW BigDecimal.
- return null;
+ return a.add(b);
}
/**
@@ -48,7 +48,7 @@ public static BigDecimal addValues(BigDecimal a, BigDecimal b) {
*/
public static BigDecimal multiplyValues(BigDecimal a, BigDecimal b) {
// TODO: 3 - Use the multiply() method to multiply a and b. Return the result.
- return null;
+ return a.multiply(b);
}
/**
@@ -63,7 +63,7 @@ public static BigDecimal divideValues(BigDecimal a, BigDecimal b, int scale) {
// TODO: 4 - Use a.divide(b, scale, RoundingMode.HALF_UP) to divide.
// You MUST specify a rounding mode for division, otherwise you may get
// an ArithmeticException for non-terminating decimals (like 1/3).
- return null;
+ return a.divide(b, scale, RoundingMode.HALF_UP);
}
/**
@@ -80,7 +80,7 @@ public static int compareValues(BigDecimal a, BigDecimal b) {
// TODO: 5 - Use a.compareTo(b) to compare the two values.
// Return the result (which will be -1, 0, or 1).
// Do NOT use equals() for numeric comparison!
- return 0;
+ return a.compareTo(b);
}
/**
@@ -94,7 +94,11 @@ public static void demonstrateDoubleProblem() {
// Print both values. Notice that fromDouble is NOT exactly 0.1!
// It will show something like 0.1000000000000000055511151231257827021181583404541015625
// Print a message explaining why the String constructor should be preferred.
-
+ BigDecimal fromDouble = new BigDecimal(0.1);
+ BigDecimal fromString = new BigDecimal("0.1");
+ System.out.println("From double: " + fromDouble);
+ System.out.println("From string: " + fromString);
+ System.out.println("Always use the String constructor to avoid floating-point precision issues.");
}
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/developers/userinput/UserInputExercises.java b/src/main/java/com/amigoscode/_2_developers/_9_userinput/UserInputExercises.java
similarity index 72%
rename from src/main/java/com/amigoscode/developers/userinput/UserInputExercises.java
rename to src/main/java/com/amigoscode/_2_developers/_9_userinput/UserInputExercises.java
index 2efb3e7..fe95c83 100644
--- a/src/main/java/com/amigoscode/developers/userinput/UserInputExercises.java
+++ b/src/main/java/com/amigoscode/_2_developers/_9_userinput/UserInputExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.developers.userinput;
+package com.amigoscode._2_developers._9_userinput;
import java.util.InputMismatchException;
import java.util.Scanner;
@@ -20,7 +20,8 @@ public class UserInputExercises {
public static String readString(Scanner scanner) {
// TODO: 1 - Prompt the user with "Enter your name: " (use System.out.print).
// Read a full line using scanner.nextLine() and return it.
- return null;
+ System.out.print("Enter your name: ");
+ return scanner.nextLine();
}
/**
@@ -38,7 +39,16 @@ public static int readIntSafely(Scanner scanner) {
// catch InputMismatchException, print "Invalid input!", and return -1.
// Don't forget to consume the leftover newline with scanner.nextLine()
// after reading the int (both in success and failure cases).
- return 0;
+ System.out.print("Enter a number: ");
+ try {
+ int num = scanner.nextInt();
+ scanner.nextLine();
+ return num;
+ } catch (InputMismatchException e) {
+ System.out.println("Invalid input!");
+ scanner.nextLine();
+ return -1;
+ }
}
/**
@@ -53,7 +63,12 @@ public static void readUntilQuit(Scanner scanner) {
// Read a line with scanner.nextLine().
// If the line equals "quit" (case-insensitive), break out of the loop.
// Otherwise, print "You entered: " followed by the input.
-
+ while (true) {
+ System.out.print("Enter text (or 'quit' to stop): ");
+ String line = scanner.nextLine();
+ if (line.equalsIgnoreCase("quit")) break;
+ System.out.println("You entered: " + line);
+ }
}
/**
@@ -64,7 +79,7 @@ public static void readUntilQuit(Scanner scanner) {
*/
public static boolean isValidAge(int age) {
// TODO: 4 - Return true if age is between 0 and 150 (inclusive), false otherwise.
- return false;
+ return age >= 0 && age <= 150;
}
/**
@@ -75,7 +90,7 @@ public static boolean isValidAge(int age) {
*/
public static boolean isValidEmail(String email) {
// TODO: 5 - Return true if email is not null and contains "@", false otherwise.
- return false;
+ return email != null && email.contains("@");
}
/**
@@ -92,7 +107,34 @@ public static void registrationForm(Scanner scanner) {
// 3. Ask for email. Keep asking until isValidEmail() returns true.
// 4. Print a summary: "Registration complete!"
// "Name: ...", "Age: ...", "Email: ..."
-
+ String name = "";
+ while (name.isEmpty()) {
+ System.out.print("Enter name: ");
+ name = scanner.nextLine().trim();
+ }
+
+ int age = -1;
+ while (!isValidAge(age)) {
+ System.out.print("Enter age: ");
+ try {
+ age = scanner.nextInt();
+ scanner.nextLine();
+ } catch (InputMismatchException e) {
+ System.out.println("Invalid input!");
+ scanner.nextLine();
+ }
+ }
+
+ String email = "";
+ while (!isValidEmail(email)) {
+ System.out.print("Enter email: ");
+ email = scanner.nextLine().trim();
+ }
+
+ System.out.println("Registration complete!");
+ System.out.println("Name: " + name);
+ System.out.println("Age: " + age);
+ System.out.println("Email: " + email);
}
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/oop/encapsulation/BankAccount.java b/src/main/java/com/amigoscode/_3_oop/_1_encapsulation/BankAccount.java
similarity index 65%
rename from src/main/java/com/amigoscode/oop/encapsulation/BankAccount.java
rename to src/main/java/com/amigoscode/_3_oop/_1_encapsulation/BankAccount.java
index 9f8b1ad..7713570 100644
--- a/src/main/java/com/amigoscode/oop/encapsulation/BankAccount.java
+++ b/src/main/java/com/amigoscode/_3_oop/_1_encapsulation/BankAccount.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.encapsulation;
+package com.amigoscode._3_oop._1_encapsulation;
/**
* Exercise: Encapsulation with BankAccount
@@ -18,17 +18,28 @@ public class BankAccount {
// - accountNumber (String)
// - balance (double)
// - ownerName (String)
-
+ private String accountNumber;
+ private double balance;
+ private String ownerName;
// TODO: 2 - Create a constructor that takes accountNumber, ownerName,
// and an initialBalance. Validate that initialBalance >= 0,
// throwing IllegalArgumentException if not. Assign all fields.
-
+ public BankAccount(String accountNumber, String ownerName, double initialBalance) {
+ if (initialBalance < 0) {
+ throw new IllegalArgumentException("Initial balance must be >= 0");
+ }
+ this.accountNumber = accountNumber;
+ this.ownerName = ownerName;
+ this.balance = initialBalance;
+ }
// TODO: 3 - Create a getter method for balance (getBalance).
// Do NOT create a setter for balance — it should only change
// through deposit() and withdraw().
-
+ public double getBalance() {
+ return balance;
+ }
// TODO: 4 - Create a deposit(double amount) method.
// - If amount <= 0, throw IllegalArgumentException with message
@@ -36,7 +47,14 @@ public class BankAccount {
// - Add amount to balance
// - Call the private logTransaction() helper with a descriptive message
// - Return the new balance
-
+ public double deposit(double amount) {
+ if (amount <= 0) {
+ throw new IllegalArgumentException("Deposit amount must be positive");
+ }
+ balance += amount;
+ logTransaction("Deposited " + amount);
+ return balance;
+ }
// TODO: 5 - Create a withdraw(double amount) method.
// - If amount <= 0, throw IllegalArgumentException with message
@@ -46,16 +64,32 @@ public class BankAccount {
// - Subtract amount from balance
// - Call the private logTransaction() helper with a descriptive message
// - Return the new balance
-
+ public double withdraw(double amount) {
+ if (amount <= 0) {
+ throw new IllegalArgumentException("Withdrawal amount must be positive");
+ }
+ if (amount > balance) {
+ throw new IllegalStateException("Insufficient funds");
+ }
+ balance -= amount;
+ logTransaction("Withdrew " + amount);
+ return balance;
+ }
// TODO: 6 - Override toString() to return a string in the format:
// "BankAccount{accountNumber='XXX', ownerName='XXX', balance=XXX}"
-
+ @Override
+ public String toString() {
+ return "BankAccount{accountNumber='" + accountNumber + "', ownerName='" + ownerName + "', balance=" + balance + "}";
+ }
// TODO: 7 - Create a private helper method logTransaction(String message)
// that prints the message to the console prefixed with
// "[Transaction Log] ". This method should NOT be accessible
// from outside the class.
+ private void logTransaction(String message) {
+ System.out.println("[Transaction Log] " + message);
+ }
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/oop/encapsulation/ImmutablePerson.java b/src/main/java/com/amigoscode/_3_oop/_1_encapsulation/ImmutablePerson.java
similarity index 72%
rename from src/main/java/com/amigoscode/oop/encapsulation/ImmutablePerson.java
rename to src/main/java/com/amigoscode/_3_oop/_1_encapsulation/ImmutablePerson.java
index 231b0f9..0e216b3 100644
--- a/src/main/java/com/amigoscode/oop/encapsulation/ImmutablePerson.java
+++ b/src/main/java/com/amigoscode/_3_oop/_1_encapsulation/ImmutablePerson.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.encapsulation;
+package com.amigoscode._3_oop._1_encapsulation;
/**
* Exercise: Immutability
@@ -19,30 +19,46 @@ public final class ImmutablePerson {
// - name (String)
// - age (int)
// - email (String)
-
+ private final String name;
+ private final int age;
+ private final String email;
// TODO: 2 - Create a constructor that takes name, age, and email
// and assigns them to the fields. Since the fields are final,
// they can only be set here.
-
+ public ImmutablePerson(String name, int age, String email) {
+ this.name = name;
+ this.age = age;
+ this.email = email;
+ }
// TODO: 3 - Create getter methods for all three fields:
// getName(), getAge(), getEmail().
// Do NOT create any setter methods — this class is immutable.
-
+ public String getName() { return name; }
+ public int getAge() { return age; }
+ public String getEmail() { return email; }
// TODO: 4 - Create a withName(String newName) method that returns
// a NEW ImmutablePerson with the changed name but the same
// age and email. The original object must remain unchanged.
-
+ public ImmutablePerson withName(String newName) {
+ return new ImmutablePerson(newName, this.age, this.email);
+ }
// TODO: 5 - Create a withAge(int newAge) method that returns
// a NEW ImmutablePerson with the changed age but the same
// name and email. The original object must remain unchanged.
-
+ public ImmutablePerson withAge(int newAge) {
+ return new ImmutablePerson(this.name, newAge, this.email);
+ }
// TODO: 6 - Override toString() to return a string in the format:
// "ImmutablePerson{name='XXX', age=XXX, email='XXX'}"
+ @Override
+ public String toString() {
+ return "ImmutablePerson{name='" + name + "', age=" + age + ", email='" + email + "'}";
+ }
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/oop/inheritance/Animal.java b/src/main/java/com/amigoscode/_3_oop/_2_inheritance/Animal.java
similarity index 71%
rename from src/main/java/com/amigoscode/oop/inheritance/Animal.java
rename to src/main/java/com/amigoscode/_3_oop/_2_inheritance/Animal.java
index 6466568..5c2b399 100644
--- a/src/main/java/com/amigoscode/oop/inheritance/Animal.java
+++ b/src/main/java/com/amigoscode/_3_oop/_2_inheritance/Animal.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.inheritance;
+package com.amigoscode._3_oop._2_inheritance;
/**
* Exercise: Inheritance - Base Class
@@ -17,24 +17,36 @@ public class Animal {
// TODO: 1 - Declare two protected fields:
// - name (String)
// - age (int)
-
+ protected String name;
+ protected int age;
// TODO: 2 - Create a constructor that takes name and age
// and assigns them to the fields.
-
+ public Animal(String name, int age) {
+ this.name = name;
+ this.age = age;
+ }
// TODO: 3 - Create a makeSound() method that prints:
// "Some generic animal sound"
// Subclasses will override this with their specific sound.
-
+ public void makeSound() {
+ System.out.println("Some generic animal sound");
+ }
// TODO: 4 - Create an eat(String food) method that prints:
// " is eating "
// For example: "Buddy is eating kibble"
-
+ public void eat(String food) {
+ System.out.println(name + " is eating " + food);
+ }
// TODO: 5 - Override toString() to return:
// "Animal{name='XXX', age=XXX}"
+ @Override
+ public String toString() {
+ return "Animal{name='" + name + "', age=" + age + "}";
+ }
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/oop/inheritance/Dog.java b/src/main/java/com/amigoscode/_3_oop/_2_inheritance/Dog.java
similarity index 76%
rename from src/main/java/com/amigoscode/oop/inheritance/Dog.java
rename to src/main/java/com/amigoscode/_3_oop/_2_inheritance/Dog.java
index 8c9bf24..9229f35 100644
--- a/src/main/java/com/amigoscode/oop/inheritance/Dog.java
+++ b/src/main/java/com/amigoscode/_3_oop/_2_inheritance/Dog.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.inheritance;
+package com.amigoscode._3_oop._2_inheritance;
/**
* Exercise: Inheritance - Subclass
@@ -16,31 +16,43 @@
// TODO: 1 - Make this class extend Animal.
// Change the class declaration so Dog inherits from Animal.
-public class Dog {
+public class Dog extends Animal {
// TODO: 2 - Add a private field:
// - breed (String)
-
+ private String breed;
// TODO: 3 - Create a constructor that takes name, age, and breed.
// Call super(name, age) to initialize the parent fields,
// then set the breed field.
-
+ public Dog(String name, int age, String breed) {
+ super(name, age);
+ this.breed = breed;
+ }
// TODO: 4 - Override the makeSound() method to print:
// " says: Woof! Woof!"
// Use the @Override annotation. You can access `name` because
// it is a protected field in Animal.
-
+ @Override
+ public void makeSound() {
+ System.out.println(name + " says: Woof! Woof!");
+ }
// TODO: 5 - Add a fetch(String item) method specific to Dog.
// This method should print:
// " fetches the !"
// This method does not exist in Animal — it is unique to Dog.
-
+ public void fetch(String item) {
+ System.out.println(name + " fetches the " + item + "!");
+ }
// TODO: 6 - Override toString() to return:
// "Dog{name='XXX', age=XXX, breed='XXX'}"
+ @Override
+ public String toString() {
+ return "Dog{name='" + name + "', age=" + age + ", breed='" + breed + "'}";
+ }
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/oop/inheritance/ElectricCar.java b/src/main/java/com/amigoscode/_3_oop/_2_inheritance/ElectricCar.java
similarity index 71%
rename from src/main/java/com/amigoscode/oop/inheritance/ElectricCar.java
rename to src/main/java/com/amigoscode/_3_oop/_2_inheritance/ElectricCar.java
index 389b587..4689557 100644
--- a/src/main/java/com/amigoscode/oop/inheritance/ElectricCar.java
+++ b/src/main/java/com/amigoscode/_3_oop/_2_inheritance/ElectricCar.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.inheritance;
+package com.amigoscode._3_oop._2_inheritance;
/**
* Exercise: Inheritance - ElectricCar Subclass
@@ -14,32 +14,49 @@
*/
// TODO: 1 - Make this class extend Vehicle.
-public class ElectricCar {
+public class ElectricCar extends Vehicle {
// TODO: 2 - Add a private field:
// - batteryLevel (int) representing percentage from 0 to 100
-
+ private int batteryLevel;
// TODO: 3 - Create a constructor that takes make, model, year, and batteryLevel.
// Call super(make, model, year) first, then set the batteryLevel field.
-
+ public ElectricCar(String make, String model, int year, int batteryLevel) {
+ super(make, model, year);
+ this.batteryLevel = batteryLevel;
+ }
// TODO: 4 - Override the start() method to print:
// " electric motor starting silently..."
// Use the @Override annotation. Access make and model from
// the parent class (they are protected).
-
+ @Override
+ public void start() {
+ System.out.println(make + " " + model + " electric motor starting silently...");
+ }
// TODO: 5 - Add a charge(int percent) method specific to ElectricCar.
// - Add percent to batteryLevel
// - Cap batteryLevel at 100 (use Math.min)
// - Print: "Charging... Battery now at %"
-
+ public void charge(int percent) {
+ batteryLevel = Math.min(batteryLevel + percent, 100);
+ System.out.println("Charging... Battery now at " + batteryLevel + "%");
+ }
// TODO: 6 - Add a getBatteryStatus() method that returns a String:
// "Battery: %"
// Also override toString() to return:
// "ElectricCar{make='XXX', model='XXX', year=XXX, batteryLevel=XXX%}"
+ public String getBatteryStatus() {
+ return "Battery: " + batteryLevel + "%";
+ }
+
+ @Override
+ public String toString() {
+ return "ElectricCar{make='" + make + "', model='" + model + "', year=" + year + ", batteryLevel=" + batteryLevel + "%}";
+ }
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/oop/inheritance/Vehicle.java b/src/main/java/com/amigoscode/_3_oop/_2_inheritance/Vehicle.java
similarity index 69%
rename from src/main/java/com/amigoscode/oop/inheritance/Vehicle.java
rename to src/main/java/com/amigoscode/_3_oop/_2_inheritance/Vehicle.java
index da4e670..56af363 100644
--- a/src/main/java/com/amigoscode/oop/inheritance/Vehicle.java
+++ b/src/main/java/com/amigoscode/_3_oop/_2_inheritance/Vehicle.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.inheritance;
+package com.amigoscode._3_oop._2_inheritance;
/**
* Exercise: Inheritance - Vehicle Base Class
@@ -18,24 +18,38 @@ public class Vehicle {
// - make (String) e.g., "Toyota"
// - model (String) e.g., "Camry"
// - year (int) e.g., 2024
-
+ protected String make;
+ protected String model;
+ protected int year;
// TODO: 2 - Create a constructor that takes make, model, and year
// and assigns them to the fields.
-
+ public Vehicle(String make, String model, int year) {
+ this.make = make;
+ this.model = model;
+ this.year = year;
+ }
// TODO: 3 - Create a start() method that prints:
// " engine is starting... Vroom!"
// For example: "Toyota Camry engine is starting... Vroom!"
-
+ public void start() {
+ System.out.println(make + " " + model + " engine is starting... Vroom!");
+ }
// TODO: 4 - Create a getInfo() method that returns a String:
// ""
// For example: "2024 Toyota Camry"
-
+ public String getInfo() {
+ return year + " " + make + " " + model;
+ }
// TODO: 5 - Override toString() to return:
// "Vehicle{make='XXX', model='XXX', year=XXX}"
+ @Override
+ public String toString() {
+ return "Vehicle{make='" + make + "', model='" + model + "', year=" + year + "}";
+ }
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/oop/abstractclasses/Circle.java b/src/main/java/com/amigoscode/_3_oop/_3_abstractclasses/Circle.java
similarity index 72%
rename from src/main/java/com/amigoscode/oop/abstractclasses/Circle.java
rename to src/main/java/com/amigoscode/_3_oop/_3_abstractclasses/Circle.java
index 9f2e7b1..2cc7647 100644
--- a/src/main/java/com/amigoscode/oop/abstractclasses/Circle.java
+++ b/src/main/java/com/amigoscode/_3_oop/_3_abstractclasses/Circle.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.abstractclasses;
+package com.amigoscode._3_oop._3_abstractclasses;
/**
* Exercise: Abstract Classes - Circle
@@ -13,25 +13,37 @@
*/
// TODO: 1 - Make this class extend Shape.
-public class Circle {
+public class Circle extends Shape {
// TODO: 2 - Declare a private field:
// - radius (double)
-
+ private double radius;
// TODO: 3 - Create a constructor that takes a radius.
// Validate that radius > 0, throwing IllegalArgumentException if not.
// Assign the field.
-
+ public Circle(double radius) {
+ if (radius <= 0) {
+ throw new IllegalArgumentException("Radius must be > 0");
+ }
+ this.radius = radius;
+ }
// TODO: 4 - Implement the area() method from Shape.
// Formula: Math.PI * radius * radius
// Use the @Override annotation.
-
+ @Override
+ public double area() {
+ return Math.PI * radius * radius;
+ }
// TODO: 5 - Implement the perimeter() method from Shape.
// Formula: 2 * Math.PI * radius
// Use the @Override annotation.
+ @Override
+ public double perimeter() {
+ return 2 * Math.PI * radius;
+ }
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/oop/abstractclasses/Employee.java b/src/main/java/com/amigoscode/_3_oop/_3_abstractclasses/Employee.java
similarity index 55%
rename from src/main/java/com/amigoscode/oop/abstractclasses/Employee.java
rename to src/main/java/com/amigoscode/_3_oop/_3_abstractclasses/Employee.java
index 9b208a7..d6d3683 100644
--- a/src/main/java/com/amigoscode/oop/abstractclasses/Employee.java
+++ b/src/main/java/com/amigoscode/_3_oop/_3_abstractclasses/Employee.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.abstractclasses;
+package com.amigoscode._3_oop._3_abstractclasses;
import java.util.ArrayList;
import java.util.List;
@@ -21,29 +21,61 @@
// - name (String)
// - baseSalary (double)
// Create a constructor that takes both fields and assigns them.
-class Employee {
+abstract class Employee {
+ protected String name;
+ protected double baseSalary;
+
+ public Employee(String name, double baseSalary) {
+ this.name = name;
+ this.baseSalary = baseSalary;
+ }
// TODO: 2 - Declare an abstract method: double calculatePay()
// Each subclass will compute pay differently.
-
+ public abstract double calculatePay();
// TODO: 3 - Create a concrete method: String getDetails()
// Return: " - Pay: $"
// Use String.format("%.2f", calculatePay()) for formatting.
-
+ public String getDetails() {
+ return name + " - Pay: $" + String.format("%.2f", calculatePay());
+ }
}
// TODO: 4 - Create a FullTimeEmployee class that extends Employee.
// - Constructor takes name and baseSalary, calls super(name, baseSalary)
// - Implement calculatePay() to simply return baseSalary
+class FullTimeEmployee extends Employee {
+ public FullTimeEmployee(String name, double baseSalary) {
+ super(name, baseSalary);
+ }
+ @Override
+ public double calculatePay() {
+ return baseSalary;
+ }
+}
// TODO: 5 - Create a ContractEmployee class that extends Employee.
// - Add two private fields: hourlyRate (double) and hoursWorked (int)
// - Constructor takes name, hourlyRate, and hoursWorked
// (pass name and 0.0 as baseSalary to super)
// - Implement calculatePay() to return hourlyRate * hoursWorked
+class ContractEmployee extends Employee {
+ private double hourlyRate;
+ private int hoursWorked;
+ public ContractEmployee(String name, double hourlyRate, int hoursWorked) {
+ super(name, 0.0);
+ this.hourlyRate = hourlyRate;
+ this.hoursWorked = hoursWorked;
+ }
+
+ @Override
+ public double calculatePay() {
+ return hourlyRate * hoursWorked;
+ }
+}
// TODO: 6 - In the EmployeeDemo class below, complete the main method:
// - Create a List with at least one FullTimeEmployee
@@ -55,7 +87,27 @@ class Employee {
// Call it from main and print the result.
class EmployeeDemo {
+ static Employee getHighestPaid(List employees) {
+ Employee highest = null;
+ for (Employee e : employees) {
+ if (highest == null || e.calculatePay() > highest.calculatePay()) {
+ highest = e;
+ }
+ }
+ return highest;
+ }
+
public static void main(String[] args) {
// Complete TODOs 6 and 7 here
+ List employees = new ArrayList<>();
+ employees.add(new FullTimeEmployee("Alice", 5000.0));
+ employees.add(new ContractEmployee("Bob", 50.0, 160));
+
+ for (Employee e : employees) {
+ System.out.println(e.getDetails());
+ }
+
+ Employee highestPaid = getHighestPaid(employees);
+ System.out.println("Highest paid: " + highestPaid.getDetails());
}
}
diff --git a/src/main/java/com/amigoscode/oop/abstractclasses/Rectangle.java b/src/main/java/com/amigoscode/_3_oop/_3_abstractclasses/Rectangle.java
similarity index 69%
rename from src/main/java/com/amigoscode/oop/abstractclasses/Rectangle.java
rename to src/main/java/com/amigoscode/_3_oop/_3_abstractclasses/Rectangle.java
index 66beaf9..3267433 100644
--- a/src/main/java/com/amigoscode/oop/abstractclasses/Rectangle.java
+++ b/src/main/java/com/amigoscode/_3_oop/_3_abstractclasses/Rectangle.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.abstractclasses;
+package com.amigoscode._3_oop._3_abstractclasses;
/**
* Exercise: Abstract Classes - Rectangle
@@ -13,26 +13,40 @@
*/
// TODO: 1 - Make this class extend Shape.
-public class Rectangle {
+public class Rectangle extends Shape {
// TODO: 2 - Declare two private fields:
// - width (double)
// - height (double)
-
+ private double width;
+ private double height;
// TODO: 3 - Create a constructor that takes width and height.
// Validate that both are > 0, throwing IllegalArgumentException if not.
// Assign the fields.
-
+ public Rectangle(double width, double height) {
+ if (width <= 0 || height <= 0) {
+ throw new IllegalArgumentException("Width and height must be > 0");
+ }
+ this.width = width;
+ this.height = height;
+ }
// TODO: 4 - Implement the area() method from Shape.
// Formula: width * height
// Use the @Override annotation.
-
+ @Override
+ public double area() {
+ return width * height;
+ }
// TODO: 5 - Implement the perimeter() method from Shape.
// Formula: 2 * (width + height)
// Use the @Override annotation.
+ @Override
+ public double perimeter() {
+ return 2 * (width + height);
+ }
public static void main(String[] args) {
diff --git a/src/main/java/com/amigoscode/oop/abstractclasses/Shape.java b/src/main/java/com/amigoscode/_3_oop/_3_abstractclasses/Shape.java
similarity index 75%
rename from src/main/java/com/amigoscode/oop/abstractclasses/Shape.java
rename to src/main/java/com/amigoscode/_3_oop/_3_abstractclasses/Shape.java
index 7cdff11..ea7abb9 100644
--- a/src/main/java/com/amigoscode/oop/abstractclasses/Shape.java
+++ b/src/main/java/com/amigoscode/_3_oop/_3_abstractclasses/Shape.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.abstractclasses;
+package com.amigoscode._3_oop._3_abstractclasses;
/**
* Exercise: Abstract Classes - Shape
@@ -16,26 +16,32 @@
// TODO: 1 - Make this class abstract by adding the `abstract` keyword.
// An abstract class cannot be instantiated directly.
-public class Shape {
+public abstract class Shape {
// TODO: 2 - Declare an abstract method: double area()
// Abstract methods have no body — just the signature followed by ;
// Every subclass of Shape must implement this method.
-
+ public abstract double area();
// TODO: 3 - Declare an abstract method: double perimeter()
// Every subclass of Shape must implement this method.
-
+ public abstract double perimeter();
// TODO: 4 - Create a concrete (non-abstract) method: void describe()
// This method should print:
// "This shape has area: and perimeter: "
// Note: you can call abstract methods from concrete methods!
// At runtime, the subclass implementation will be used.
-
+ public void describe() {
+ System.out.println("This shape has area: " + area() + " and perimeter: " + perimeter());
+ }
// TODO: 5 - Override toString() to return:
// "Shape[area=, perimeter=]"
// Use String.format("%.2f", value) to format to 2 decimal places.
+ @Override
+ public String toString() {
+ return "Shape[area=" + String.format("%.2f", area()) + ", perimeter=" + String.format("%.2f", perimeter()) + "]";
+ }
}
diff --git a/src/main/java/com/amigoscode/oop/polymorphism/PaymentProcessor.java b/src/main/java/com/amigoscode/_3_oop/_4_polymorphism/PaymentProcessor.java
similarity index 55%
rename from src/main/java/com/amigoscode/oop/polymorphism/PaymentProcessor.java
rename to src/main/java/com/amigoscode/_3_oop/_4_polymorphism/PaymentProcessor.java
index bb52615..e592511 100644
--- a/src/main/java/com/amigoscode/oop/polymorphism/PaymentProcessor.java
+++ b/src/main/java/com/amigoscode/_3_oop/_4_polymorphism/PaymentProcessor.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.polymorphism;
+package com.amigoscode._3_oop._4_polymorphism;
import java.util.ArrayList;
import java.util.List;
@@ -24,7 +24,13 @@
// - A default method: void printReceipt(double amount) that prints:
// "Receipt: $ paid via "
// Default methods provide a body in the interface itself.
-
+interface Payment {
+ boolean processPayment(double amount);
+ String getPaymentMethod();
+ default void printReceipt(double amount) {
+ System.out.println("Receipt: $" + amount + " paid via " + getPaymentMethod());
+ }
+}
// TODO: 2 - Create a CreditCardPayment class that implements Payment.
// - Add a private field: cardNumber (String)
@@ -33,7 +39,24 @@
// "Processing credit card payment of $ with card "
// and return true
// - Implement getPaymentMethod() to return "Credit Card"
+class CreditCardPayment implements Payment {
+ private String cardNumber;
+
+ public CreditCardPayment(String cardNumber) {
+ this.cardNumber = cardNumber;
+ }
+
+ @Override
+ public boolean processPayment(double amount) {
+ System.out.println("Processing credit card payment of $" + amount + " with card " + cardNumber);
+ return true;
+ }
+ @Override
+ public String getPaymentMethod() {
+ return "Credit Card";
+ }
+}
// TODO: 3 - Create a PayPalPayment class that implements Payment.
// - Add a private field: email (String)
@@ -42,7 +65,24 @@
// "Processing PayPal payment of $ from "
// and return true
// - Implement getPaymentMethod() to return "PayPal"
+class PayPalPayment implements Payment {
+ private String email;
+
+ public PayPalPayment(String email) {
+ this.email = email;
+ }
+
+ @Override
+ public boolean processPayment(double amount) {
+ System.out.println("Processing PayPal payment of $" + amount + " from " + email);
+ return true;
+ }
+ @Override
+ public String getPaymentMethod() {
+ return "PayPal";
+ }
+}
// TODO: 4 - Create a BankTransferPayment class that implements Payment.
// - Add a private field: bankAccountId (String)
@@ -51,20 +91,50 @@
// "Processing bank transfer of $ from account "
// and return true
// - Implement getPaymentMethod() to return "Bank Transfer"
+class BankTransferPayment implements Payment {
+ private String bankAccountId;
+
+ public BankTransferPayment(String bankAccountId) {
+ this.bankAccountId = bankAccountId;
+ }
+
+ @Override
+ public boolean processPayment(double amount) {
+ System.out.println("Processing bank transfer of $" + amount + " from account " + bankAccountId);
+ return true;
+ }
+ @Override
+ public String getPaymentMethod() {
+ return "Bank Transfer";
+ }
+}
// TODO: 5 - Create a PaymentProcessor class with a method:
// void processAllPayments(List payments, double amount)
// Iterate over the list and call processPayment(amount) on each.
// After each payment, call printReceipt(amount).
-
+class PaymentProcessor {
+ void processAllPayments(List payments, double amount) {
+ for (Payment payment : payments) {
+ payment.processPayment(amount);
+ payment.printReceipt(amount);
+ }
+ }
+}
class PaymentDemo {
public static void main(String[] args) {
// TODO: 6 - Create a List containing one of each payment type:
// CreditCardPayment, PayPalPayment, BankTransferPayment.
// Then create a PaymentProcessor and call processAllPayments().
+ List payments = new ArrayList<>();
+ payments.add(new CreditCardPayment("1234-5678-9012-3456"));
+ payments.add(new PayPalPayment("user@email.com"));
+ payments.add(new BankTransferPayment("ACC-98765"));
+ PaymentProcessor processor = new PaymentProcessor();
+ processor.processAllPayments(payments, 100.0);
// TODO: 7 - Demonstrate runtime polymorphism:
// Create a Payment variable and assign different implementations to it.
@@ -75,6 +145,12 @@ public static void main(String[] args) {
// payment.processPayment(100.0);
// payment = new PayPalPayment("user@email.com");
// payment.processPayment(200.0);
+ Payment payment = new CreditCardPayment("1234-5678");
+ payment.processPayment(100.0);
+ payment = new PayPalPayment("user@email.com");
+ payment.processPayment(200.0);
+ payment = new BankTransferPayment("ACC-11111");
+ payment.processPayment(300.0);
}
}
diff --git a/src/main/java/com/amigoscode/_3_oop/_4_polymorphism/ShapeCalculator.java b/src/main/java/com/amigoscode/_3_oop/_4_polymorphism/ShapeCalculator.java
new file mode 100644
index 0000000..ad7c9aa
--- /dev/null
+++ b/src/main/java/com/amigoscode/_3_oop/_4_polymorphism/ShapeCalculator.java
@@ -0,0 +1,113 @@
+package com.amigoscode._3_oop._4_polymorphism;
+
+import com.amigoscode._3_oop._3_abstractclasses.Circle;
+import com.amigoscode._3_oop._3_abstractclasses.Rectangle;
+import com.amigoscode._3_oop._3_abstractclasses.Shape;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Exercise: Polymorphism - Shape Calculator
+ *
+ * Use polymorphism to write methods that work with any Shape.
+ * Because Circle and Rectangle both extend Shape, a single method
+ * can handle both — and any future Shape subclass — without modification.
+ *
+ * Key concepts:
+ * - Methods that accept a supertype parameter
+ * - Polymorphic collections (List)
+ * - instanceof with pattern matching (Java 16+)
+ * - Open/closed principle in practice
+ *
+ * Prerequisites: Complete Shape.java, Circle.java, and Rectangle.java first.
+ */
+public class ShapeCalculator {
+
+ // TODO: 1 - Create a method: void printShapeArea(Shape shape)
+ // Print: "The has an area of "
+ // Use shape.getClass().getSimpleName() to get the class name.
+ // Use String.format("%.2f", shape.area()) for formatting.
+ public void printShapeArea(Shape shape) {
+ System.out.println("The " + shape.getClass().getSimpleName() + " has an area of " + String.format("%.2f", shape.area()));
+ }
+
+ // TODO: 2 - Create a method: double totalArea(List shapes)
+ // Iterate over all shapes and return the sum of their areas.
+ public double totalArea(List shapes) {
+ double total = 0;
+ for (Shape shape : shapes) {
+ total += shape.area();
+ }
+ return total;
+ }
+
+ // TODO: 3 - Create a method: Shape largestShape(List shapes)
+ // Return the shape with the largest area.
+ // If the list is empty, return null.
+ public Shape largestShape(List shapes) {
+ if (shapes.isEmpty()) return null;
+ Shape largest = shapes.get(0);
+ for (Shape shape : shapes) {
+ if (shape.area() > largest.area()) {
+ largest = shape;
+ }
+ }
+ return largest;
+ }
+
+ // TODO: 4 - Create a method: String describeShape(Shape shape)
+ // Use instanceof with pattern matching (Java 16+) to return
+ // specific descriptions:
+ // - If shape is a Circle c: return "Circle with radius info"
+ // (just return "Circle detected with area: " + c.area())
+ // - If shape is a Rectangle r: return "Rectangle detected with area: " + r.area()
+ // - Otherwise: return "Unknown shape with area: " + shape.area()
+ public String describeShape(Shape shape) {
+ if (shape instanceof Circle c) {
+ return "Circle detected with area: " + c.area();
+ } else if (shape instanceof Rectangle r) {
+ return "Rectangle detected with area: " + r.area();
+ } else {
+ return "Unknown shape with area: " + shape.area();
+ }
+ }
+
+ // TODO: 5 - Create a method: String formatSummary(List shapes)
+ // Return a formatted summary string like:
+ // "Summary: shapes, total area: , largest area: "
+ // Use the totalArea() and largestShape() methods you already wrote.
+ public String formatSummary(List shapes) {
+ double total = totalArea(shapes);
+ Shape largest = largestShape(shapes);
+ double largestArea = largest != null ? largest.area() : 0;
+ return "Summary: " + shapes.size() + " shapes, total area: " + String.format("%.2f", total) + ", largest area: " + String.format("%.2f", largestArea);
+ }
+
+ // TODO: 6 - In main, create a List with at least two Circles
+ // and two Rectangles. Call all the methods above and print results.
+ // This demonstrates polymorphism: the same method handles
+ // different shape types seamlessly.
+
+ public static void main(String[] args) {
+ // Complete TODO 6 here.
+ ShapeCalculator calc = new ShapeCalculator();
+ List shapes = new ArrayList<>();
+ shapes.add(new Circle(5.0));
+ shapes.add(new Circle(3.0));
+ shapes.add(new Rectangle(4.0, 6.0));
+ shapes.add(new Rectangle(10.0, 2.0));
+
+ for (Shape shape : shapes) {
+ calc.printShapeArea(shape);
+ }
+
+ System.out.println("Total area: " + String.format("%.2f", calc.totalArea(shapes)));
+ System.out.println("Largest: " + calc.largestShape(shapes));
+ System.out.println(calc.formatSummary(shapes));
+
+ for (Shape shape : shapes) {
+ System.out.println(calc.describeShape(shape));
+ }
+ }
+}
diff --git a/src/main/java/com/amigoscode/oop/dependencyinjection/NotificationService.java b/src/main/java/com/amigoscode/_3_oop/_5_dependencyinjection/NotificationService.java
similarity index 62%
rename from src/main/java/com/amigoscode/oop/dependencyinjection/NotificationService.java
rename to src/main/java/com/amigoscode/_3_oop/_5_dependencyinjection/NotificationService.java
index 839109e..a649edb 100644
--- a/src/main/java/com/amigoscode/oop/dependencyinjection/NotificationService.java
+++ b/src/main/java/com/amigoscode/_3_oop/_5_dependencyinjection/NotificationService.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.dependencyinjection;
+package com.amigoscode._3_oop._5_dependencyinjection;
/**
* Exercise: Dependency Injection - Notification Service
@@ -17,17 +17,29 @@
// TODO: 1 - Create a MessageSender interface with a single method:
// void send(String to, String message)
-
+interface MessageSender {
+ void send(String to, String message);
+}
// TODO: 2 - Create an EmailSender class that implements MessageSender.
// Implement send() to print:
// "[Email] Sending to : "
-
+class EmailSender implements MessageSender {
+ @Override
+ public void send(String to, String message) {
+ System.out.println("[Email] Sending to " + to + ": " + message);
+ }
+}
// TODO: 3 - Create an SmsSender class that implements MessageSender.
// Implement send() to print:
// "[SMS] Sending to : "
-
+class SmsSender implements MessageSender {
+ @Override
+ public void send(String to, String message) {
+ System.out.println("[SMS] Sending to " + to + ": " + message);
+ }
+}
// TODO: 4 - Create the NotificationService class.
// - Add a private final field: messageSender (MessageSender)
@@ -35,12 +47,21 @@
// and assigns it to the field. This is constructor injection —
// the dependency is provided from outside, not created inside.
-
// TODO: 5 - In NotificationService, add a method:
// void sendNotification(String to, String message)
// This method should delegate to messageSender.send(to, message).
// NotificationService does NOT know whether it is using email or SMS.
+class NotificationService {
+ private final MessageSender messageSender;
+ public NotificationService(MessageSender messageSender) {
+ this.messageSender = messageSender;
+ }
+
+ public void sendNotification(String to, String message) {
+ messageSender.send(to, message);
+ }
+}
class NotificationDemo {
public static void main(String[] args) {
@@ -48,7 +69,11 @@ public static void main(String[] args) {
// Call sendNotification("alice@example.com", "Hello via email!").
// Then create ANOTHER NotificationService with an SmsSender.
// Call sendNotification("+1234567890", "Hello via SMS!").
+ NotificationService emailService = new NotificationService(new EmailSender());
+ emailService.sendNotification("alice@example.com", "Hello via email!");
+ NotificationService smsService = new NotificationService(new SmsSender());
+ smsService.sendNotification("+1234567890", "Hello via SMS!");
// TODO: 7 - Demonstrate swapping implementations:
// Create a MessageSender variable, assign EmailSender to it,
@@ -57,6 +82,11 @@ public static void main(String[] args) {
// create a new NotificationService and send a message.
// Notice how NotificationService code never changed —
// only the injected dependency changed.
+ MessageSender sender = new EmailSender();
+ new NotificationService(sender).sendNotification("bob@example.com", "Swappable email!");
+
+ sender = new SmsSender();
+ new NotificationService(sender).sendNotification("+9876543210", "Swappable SMS!");
}
}
diff --git a/src/main/java/com/amigoscode/oop/dependencyinjection/OrderProcessor.java b/src/main/java/com/amigoscode/_3_oop/_5_dependencyinjection/OrderProcessor.java
similarity index 54%
rename from src/main/java/com/amigoscode/oop/dependencyinjection/OrderProcessor.java
rename to src/main/java/com/amigoscode/_3_oop/_5_dependencyinjection/OrderProcessor.java
index 58bcd5f..3fda580 100644
--- a/src/main/java/com/amigoscode/oop/dependencyinjection/OrderProcessor.java
+++ b/src/main/java/com/amigoscode/_3_oop/_5_dependencyinjection/OrderProcessor.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.dependencyinjection;
+package com.amigoscode._3_oop._5_dependencyinjection;
/**
* Exercise: Dependency Injection - Order Processing
@@ -18,13 +18,32 @@
// boolean charge(double amount)
// Also create a concrete StripeGateway class that implements it.
// In charge(), print "[Stripe] Charging $" and return true.
+interface PaymentGateway {
+ boolean charge(double amount);
+}
+class StripeGateway implements PaymentGateway {
+ @Override
+ public boolean charge(double amount) {
+ System.out.println("[Stripe] Charging $" + amount);
+ return true;
+ }
+}
// TODO: 2 - Create an OrderRepository interface with:
// void save(Order order)
// Also create a concrete InMemoryOrderRepository class that implements it.
// In save(), print "[Repository] Order saved: "
+interface OrderRepository {
+ void save(Order order);
+}
+class InMemoryOrderRepository implements OrderRepository {
+ @Override
+ public void save(Order order) {
+ System.out.println("[Repository] Order saved: " + order);
+ }
+}
// TODO: 3 - Create an Order class with three fields:
// - id (String)
@@ -32,7 +51,26 @@
// - amount (double)
// Create a constructor, getters, and a toString() method.
// (You may use a record if you prefer: record Order(String id, String item, double amount) {} )
+class Order {
+ private String id;
+ private String item;
+ private double amount;
+
+ public Order(String id, String item, double amount) {
+ this.id = id;
+ this.item = item;
+ this.amount = amount;
+ }
+ public String getId() { return id; }
+ public String getItem() { return item; }
+ public double getAmount() { return amount; }
+
+ @Override
+ public String toString() {
+ return "Order{id='" + id + "', item='" + item + "', amount=" + amount + "}";
+ }
+}
// TODO: 4 - Create the OrderProcessor class.
// - Add two private final fields:
@@ -40,14 +78,31 @@
// - orderRepository (OrderRepository)
// - Create a constructor that takes both as parameters (constructor injection).
-
// TODO: 5 - In OrderProcessor, add a method:
// boolean processOrder(Order order)
// - First, call paymentGateway.charge(order.getAmount())
// - If charge returns true, call orderRepository.save(order) and return true
// - If charge returns false, print "Payment failed for order: "
// and return false
+class OrderProcessor {
+ private final PaymentGateway paymentGateway;
+ private final OrderRepository orderRepository;
+
+ public OrderProcessor(PaymentGateway paymentGateway, OrderRepository orderRepository) {
+ this.paymentGateway = paymentGateway;
+ this.orderRepository = orderRepository;
+ }
+ public boolean processOrder(Order order) {
+ if (paymentGateway.charge(order.getAmount())) {
+ orderRepository.save(order);
+ return true;
+ } else {
+ System.out.println("Payment failed for order: " + order.getId());
+ return false;
+ }
+ }
+}
class OrderProcessorDemo {
public static void main(String[] args) {
@@ -60,6 +115,13 @@ public static void main(String[] args) {
// - Notice: OrderProcessor has no idea which gateway or
// repository it uses. You could swap in a PayPalGateway
// or a DatabaseOrderRepository without changing OrderProcessor.
+ PaymentGateway gateway = new StripeGateway();
+ OrderRepository repository = new InMemoryOrderRepository();
+ OrderProcessor processor = new OrderProcessor(gateway, repository);
+
+ Order order = new Order("ORD-001", "Java Course", 29.99);
+ boolean result = processor.processOrder(order);
+ System.out.println("Order processed: " + result);
}
}
diff --git a/src/main/java/com/amigoscode/oop/solid/SolidExercises.java b/src/main/java/com/amigoscode/_3_oop/_6_solid/SolidExercises.java
similarity index 66%
rename from src/main/java/com/amigoscode/oop/solid/SolidExercises.java
rename to src/main/java/com/amigoscode/_3_oop/_6_solid/SolidExercises.java
index b260f94..4faf08f 100644
--- a/src/main/java/com/amigoscode/oop/solid/SolidExercises.java
+++ b/src/main/java/com/amigoscode/_3_oop/_6_solid/SolidExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.oop.solid;
+package com.amigoscode._3_oop._6_solid;
import java.util.ArrayList;
import java.util.List;
@@ -47,7 +47,42 @@ void createUser(String name, String email) {
// that prints "Sending welcome email to ..."
// Then create a refactored UserManager that uses all three via
// constructor injection and has a createUser(name, email) method.
+ static class UserValidator {
+ void validate(String name, String email) {
+ if (name == null || name.isEmpty()) throw new IllegalArgumentException("Invalid name");
+ if (!email.contains("@")) throw new IllegalArgumentException("Invalid email");
+ }
+ }
+
+ static class UserRepository {
+ void save(String name, String email) {
+ System.out.println("Saving user " + name + " to database...");
+ }
+ }
+
+ static class UserNotifier {
+ void sendWelcome(String email) {
+ System.out.println("Sending welcome email to " + email + "...");
+ }
+ }
+ static class UserManager {
+ private final UserValidator validator;
+ private final UserRepository repository;
+ private final UserNotifier notifier;
+
+ UserManager(UserValidator validator, UserRepository repository, UserNotifier notifier) {
+ this.validator = validator;
+ this.repository = repository;
+ this.notifier = notifier;
+ }
+
+ void createUser(String name, String email) {
+ validator.validate(name, email);
+ repository.save(name, email);
+ notifier.sendWelcome(email);
+ }
+ }
// =========================================================================
// OCP - Open/Closed Principle
@@ -75,7 +110,29 @@ static class DiscountCalculatorBroken {
// double calculate(Discount discount, double price)
// that just calls discount.apply(price)
// Now new discount types can be added without modifying DiscountCalculator.
+ interface Discount {
+ double apply(double price);
+ }
+ static class SeasonalDiscount implements Discount {
+ @Override
+ public double apply(double price) {
+ return price * 0.10;
+ }
+ }
+
+ static class ClearanceDiscount implements Discount {
+ @Override
+ public double apply(double price) {
+ return price * 0.50;
+ }
+ }
+
+ static class DiscountCalculator {
+ double calculate(Discount discount, double price) {
+ return discount.apply(price);
+ }
+ }
// =========================================================================
// LSP - Liskov Substitution Principle
@@ -108,7 +165,37 @@ static class MutableSquareBroken extends MutableRectangleBroken {
// - Create an ImmutableSquare class implementing LspShape with
// a final field side, constructor, and area() returning side * side
// Now neither class pretends to be the other. Both satisfy LspShape.
+ interface LspShape {
+ int area();
+ }
+
+ static class ImmutableRectangle implements LspShape {
+ private final int width;
+ private final int height;
+
+ ImmutableRectangle(int width, int height) {
+ this.width = width;
+ this.height = height;
+ }
+ @Override
+ public int area() {
+ return width * height;
+ }
+ }
+
+ static class ImmutableSquare implements LspShape {
+ private final int side;
+
+ ImmutableSquare(int side) {
+ this.side = side;
+ }
+
+ @Override
+ public int area() {
+ return side * side;
+ }
+ }
// =========================================================================
// ISP - Interface Segregation Principle
@@ -144,7 +231,27 @@ public void sleep() { /* Robots don't sleep — forced to implement! */ }
// - HumanWorker class implementing Workable, Eatable, Sleepable
// - RobotWorker class implementing only Workable
// Now RobotWorker is not forced to implement methods it cannot use.
+ interface Workable {
+ void work();
+ }
+ interface Eatable {
+ void eat();
+ }
+
+ interface Sleepable {
+ void sleep();
+ }
+
+ static class HumanWorker implements Workable, Eatable, Sleepable {
+ public void work() { System.out.println("Human working"); }
+ public void eat() { System.out.println("Human eating"); }
+ public void sleep() { System.out.println("Human sleeping"); }
+ }
+
+ static class RobotWorker implements Workable {
+ public void work() { System.out.println("Robot working"); }
+ }
// =========================================================================
// DIP - Dependency Inversion Principle
@@ -175,7 +282,35 @@ String generateReport() {
// (its query() returns "PostgreSQL result for: " + sql)
// - Create ReportGenerator that takes Database in its constructor
// (constructor injection) and uses it in generateReport()
+ interface Database {
+ String query(String sql);
+ }
+ static class MySQLDatabase implements Database {
+ @Override
+ public String query(String sql) {
+ return "MySQL result for: " + sql;
+ }
+ }
+
+ static class PostgreSQLDatabase implements Database {
+ @Override
+ public String query(String sql) {
+ return "PostgreSQL result for: " + sql;
+ }
+ }
+
+ static class ReportGenerator {
+ private final Database database;
+
+ ReportGenerator(Database database) {
+ this.database = database;
+ }
+
+ String generateReport() {
+ return database.query("SELECT * FROM reports");
+ }
+ }
// =========================================================================
// Main method to test all exercises
@@ -185,16 +320,24 @@ public static void main(String[] args) {
// TODO: 6 - Test SRP: Create UserValidator, UserRepository, UserNotifier,
// and a refactored UserManager. Call createUser("Alice", "alice@test.com").
-
+ UserManager userManager = new UserManager(new UserValidator(), new UserRepository(), new UserNotifier());
+ userManager.createUser("Alice", "alice@test.com");
// TODO: 7 - Test OCP: Create a DiscountCalculator and several Discount
// implementations. Calculate discounts for a $100 item and print results.
-
+ DiscountCalculator discountCalc = new DiscountCalculator();
+ System.out.println("Seasonal discount on $100: $" + discountCalc.calculate(new SeasonalDiscount(), 100.0));
+ System.out.println("Clearance discount on $100: $" + discountCalc.calculate(new ClearanceDiscount(), 100.0));
// TODO: 8 - Test DIP: Create a ReportGenerator with MySQLDatabase,
// generate a report. Then create another with PostgreSQLDatabase
// and generate a report. Print both results to show the
// implementation was swapped without changing ReportGenerator.
+ ReportGenerator mysqlReport = new ReportGenerator(new MySQLDatabase());
+ System.out.println(mysqlReport.generateReport());
+
+ ReportGenerator pgReport = new ReportGenerator(new PostgreSQLDatabase());
+ System.out.println(pgReport.generateReport());
}
}
diff --git a/src/main/java/com/amigoscode/datastructures/arrays/ArrayBasics.java b/src/main/java/com/amigoscode/_4_datastructures/_1_arrays/ArrayBasics.java
similarity index 60%
rename from src/main/java/com/amigoscode/datastructures/arrays/ArrayBasics.java
rename to src/main/java/com/amigoscode/_4_datastructures/_1_arrays/ArrayBasics.java
index fbe7f35..971baae 100644
--- a/src/main/java/com/amigoscode/datastructures/arrays/ArrayBasics.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_1_arrays/ArrayBasics.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.arrays;
+package com.amigoscode._4_datastructures._1_arrays;
// Exercise: Array Basics
// Learn how to create, manipulate, and search through arrays in Java.
@@ -10,30 +10,39 @@ public class ArrayBasics {
public static void main(String[] args) {
// TODO: 1 - Create an int array of size 5
-
+ int[] numbers = new int[5];
// TODO: 2 - Fill the array with values 10, 20, 30, 40, 50 using a for loop
// (hint: use i * 10 + 10 or similar pattern)
-
+ for (int i = 0; i < numbers.length; i++) {
+ numbers[i] = (i + 1) * 10;
+ }
// TODO: 3 - Print all elements of the array using Arrays.toString()
-
+ System.out.println(Arrays.toString(numbers));
// TODO: 4 - Find the maximum value in the array
// Iterate through the array and track the largest value found
-
+ int max = numbers[0];
+ for (int num : numbers) { if (num > max) max = num; }
+ System.out.println("Max: " + max);
// TODO: 5 - Find the minimum value in the array
// Iterate through the array and track the smallest value found
-
+ int min = numbers[0];
+ for (int num : numbers) { if (num < min) min = num; }
+ System.out.println("Min: " + min);
// TODO: 6 - Sort the array using Arrays.sort()
// Then print the sorted array
-
+ Arrays.sort(numbers);
+ System.out.println("Sorted: " + Arrays.toString(numbers));
// TODO: 7 - Use Arrays.binarySearch() to find the index of value 30
// Note: the array must be sorted before using binarySearch
// Print the index where the value was found
+ int index = Arrays.binarySearch(numbers, 30);
+ System.out.println("Index of 30: " + index);
}
}
diff --git a/src/main/java/com/amigoscode/datastructures/arrays/TwoDArrays.java b/src/main/java/com/amigoscode/_4_datastructures/_1_arrays/TwoDArrays.java
similarity index 54%
rename from src/main/java/com/amigoscode/datastructures/arrays/TwoDArrays.java
rename to src/main/java/com/amigoscode/_4_datastructures/_1_arrays/TwoDArrays.java
index 04b43ae..7635a8e 100644
--- a/src/main/java/com/amigoscode/datastructures/arrays/TwoDArrays.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_1_arrays/TwoDArrays.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.arrays;
+package com.amigoscode._4_datastructures._1_arrays;
// Exercise: Two-Dimensional Arrays
// Learn how to create and work with 2D arrays (matrices) in Java.
@@ -8,7 +8,7 @@ public class TwoDArrays {
public static void main(String[] args) {
// TODO: 1 - Create a 3x3 int 2D array called 'matrix'
-
+ int[][] matrix = new int[3][3];
// TODO: 2 - Fill the matrix with multiplication table values
// matrix[i][j] should equal (i + 1) * (j + 1)
@@ -16,23 +16,47 @@ public static void main(String[] args) {
// 1 2 3
// 2 4 6
// 3 6 9
-
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
+ matrix[i][j] = (i + 1) * (j + 1);
+ }
+ }
// TODO: 3 - Print the matrix in row/column format
// Each row on a new line, values separated by spaces or tabs
-
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
+ System.out.print(matrix[i][j] + " ");
+ }
+ System.out.println();
+ }
// TODO: 4 - Find and print the sum of all elements in the matrix
// Use nested loops to accumulate the total
-
+ int totalSum = 0;
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
+ totalSum += matrix[i][j];
+ }
+ }
+ System.out.println("Sum of all elements: " + totalSum);
// TODO: 5 - Find and print the sum of row index 1 (the second row: 2, 4, 6)
// Iterate through all columns of that specific row
-
+ int rowSum = 0;
+ for (int j = 0; j < 3; j++) {
+ rowSum += matrix[1][j];
+ }
+ System.out.println("Sum of row 1: " + rowSum);
// TODO: 6 - Find and print the sum of the diagonal elements (top-left to bottom-right)
// Diagonal elements are where row index == column index
// Expected: matrix[0][0] + matrix[1][1] + matrix[2][2] = 1 + 4 + 9 = 14
+ int diagSum = 0;
+ for (int i = 0; i < 3; i++) {
+ diagSum += matrix[i][i];
+ }
+ System.out.println("Sum of diagonal: " + diagSum);
}
}
diff --git a/src/main/java/com/amigoscode/datastructures/arraylist/ArrayListBasics.java b/src/main/java/com/amigoscode/_4_datastructures/_2_arraylist/ArrayListBasics.java
similarity index 62%
rename from src/main/java/com/amigoscode/datastructures/arraylist/ArrayListBasics.java
rename to src/main/java/com/amigoscode/_4_datastructures/_2_arraylist/ArrayListBasics.java
index 99bdd7b..8753dec 100644
--- a/src/main/java/com/amigoscode/datastructures/arraylist/ArrayListBasics.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_2_arraylist/ArrayListBasics.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.arraylist;
+package com.amigoscode._4_datastructures._2_arraylist;
// Exercise: ArrayList Basics
// Learn the fundamental operations of ArrayList - Java's resizable array implementation.
@@ -10,28 +10,36 @@ public class ArrayListBasics {
public static void main(String[] args) {
// TODO: 1 - Create an ArrayList of Strings called 'names'
-
+ ArrayList names = new ArrayList<>();
// TODO: 2 - Add 5 names to the list: "Alice", "Bob", "Charlie", "Diana", "Eve"
-
+ names.add("Alice");
+ names.add("Bob");
+ names.add("Charlie");
+ names.add("Diana");
+ names.add("Eve");
// TODO: 3 - Get the element at index 2 and print it
// Expected output: Charlie
-
+ System.out.println(names.get(2));
// TODO: 4 - Check if the name "Bob" is in the list using contains()
// Print the result (true or false)
-
+ System.out.println(names.contains("Bob"));
// TODO: 5 - Remove the name "Diana" from the list by value
// Print the list after removal
-
+ names.remove("Diana");
+ System.out.println(names);
// TODO: 6 - Get and print the size of the list
-
+ System.out.println("Size: " + names.size());
// TODO: 7 - Iterate using a for-each loop and print each name
// Format: "Name: "
+ for (String name : names) {
+ System.out.println("Name: " + name);
+ }
}
}
diff --git a/src/main/java/com/amigoscode/datastructures/arraylist/ArrayListOperations.java b/src/main/java/com/amigoscode/_4_datastructures/_2_arraylist/ArrayListOperations.java
similarity index 57%
rename from src/main/java/com/amigoscode/datastructures/arraylist/ArrayListOperations.java
rename to src/main/java/com/amigoscode/_4_datastructures/_2_arraylist/ArrayListOperations.java
index eee6abc..5b0ece5 100644
--- a/src/main/java/com/amigoscode/datastructures/arraylist/ArrayListOperations.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_2_arraylist/ArrayListOperations.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.arraylist;
+package com.amigoscode._4_datastructures._2_arraylist;
// Exercise: ArrayList Operations
// Learn advanced ArrayList operations including sorting, reversing, and converting.
@@ -13,30 +13,39 @@ public static void main(String[] args) {
// TODO: 1 - Create an ArrayList of Integers called 'numbers'
// Add these 10 numbers: 45, 12, 78, 34, 56, 23, 89, 67, 11, 90
-
+ ArrayList numbers = new ArrayList<>();
+ numbers.add(45); numbers.add(12); numbers.add(78); numbers.add(34); numbers.add(56);
+ numbers.add(23); numbers.add(89); numbers.add(67); numbers.add(11); numbers.add(90);
// TODO: 2 - Sort the list in ascending order using Collections.sort()
// Print the sorted list
-
+ Collections.sort(numbers);
+ System.out.println("Sorted: " + numbers);
// TODO: 3 - Reverse the list using Collections.reverse()
// Print the reversed list
-
+ Collections.reverse(numbers);
+ System.out.println("Reversed: " + numbers);
// TODO: 4 - Find and print the maximum value using Collections.max()
-
+ System.out.println("Max: " + Collections.max(numbers));
// TODO: 5 - Create a subList containing the first 5 elements (indices 0 to 4)
// Print the subList
// Note: subList returns a view, not a copy
-
+ List subList = numbers.subList(0, 5);
+ System.out.println("SubList: " + subList);
// TODO: 6 - Convert the ArrayList to an Integer array using toArray()
// Print the array length to verify
-
+ Integer[] array = numbers.toArray(new Integer[0]);
+ System.out.println("Array length: " + array.length);
// TODO: 7 - Clear the list using clear() and verify it's empty
// Print the size and the result of isEmpty()
+ numbers.clear();
+ System.out.println("Size: " + numbers.size());
+ System.out.println("Is empty: " + numbers.isEmpty());
}
}
diff --git a/src/main/java/com/amigoscode/datastructures/stacks/StackExercises.java b/src/main/java/com/amigoscode/_4_datastructures/_3_stacks/StackExercises.java
similarity index 52%
rename from src/main/java/com/amigoscode/datastructures/stacks/StackExercises.java
rename to src/main/java/com/amigoscode/_4_datastructures/_3_stacks/StackExercises.java
index 41c0fc9..b0fa6d7 100644
--- a/src/main/java/com/amigoscode/datastructures/stacks/StackExercises.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_3_stacks/StackExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.stacks;
+package com.amigoscode._4_datastructures._3_stacks;
// Exercise: Stack Operations
// Learn how to use the Stack data structure - Last In, First Out (LIFO).
@@ -10,22 +10,27 @@ public class StackExercises {
public static void main(String[] args) {
// TODO: 1 - Create a Stack of Strings called 'stack'
-
+ Stack stack = new Stack<>();
// TODO: 2 - Push 5 elements onto the stack: "Java", "Python", "C++", "JavaScript", "Go"
-
+ stack.push("Java");
+ stack.push("Python");
+ stack.push("C++");
+ stack.push("JavaScript");
+ stack.push("Go");
// TODO: 3 - Peek at the top element without removing it
// Print the result (should be "Go")
-
+ System.out.println("Peek: " + stack.peek());
// TODO: 4 - Pop an element from the stack and print it
// Then print the stack to see the remaining elements
-
+ System.out.println("Popped: " + stack.pop());
+ System.out.println("Stack: " + stack);
// TODO: 5 - Check if the stack is empty using isEmpty()
// Print the result
-
+ System.out.println("Is empty: " + stack.isEmpty());
// --- String Reversal ---
System.out.println("\n--- String Reversal ---");
@@ -33,7 +38,16 @@ public static void main(String[] args) {
// TODO: 6 - Use a Stack to reverse the string 'original'
// Push each character onto a stack, then pop them all to build the reversed string
// Print both original and reversed strings
-
+ Stack charStack = new Stack<>();
+ for (char c : original.toCharArray()) {
+ charStack.push(c);
+ }
+ StringBuilder reversed = new StringBuilder();
+ while (!charStack.isEmpty()) {
+ reversed.append(charStack.pop());
+ }
+ System.out.println("Original: " + original);
+ System.out.println("Reversed: " + reversed);
// --- Balanced Brackets ---
System.out.println("\n--- Balanced Brackets ---");
@@ -45,6 +59,23 @@ public static void main(String[] args) {
// that the top of stack is the matching opening bracket
// Test with both 'balanced' and 'unbalanced' strings
// Print whether each string is balanced or not
+ System.out.println(balanced + " is balanced: " + isBalanced(balanced));
+ System.out.println(unbalanced + " is balanced: " + isBalanced(unbalanced));
+
+ }
+ private static boolean isBalanced(String str) {
+ Stack s = new Stack<>();
+ for (char c : str.toCharArray()) {
+ if (c == '(' || c == '{' || c == '[') {
+ s.push(c);
+ } else if (c == ')' || c == '}' || c == ']') {
+ if (s.isEmpty()) return false;
+ char top = s.pop();
+ if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '['))
+ return false;
+ }
+ }
+ return s.isEmpty();
}
}
diff --git a/src/main/java/com/amigoscode/datastructures/queues/QueueExercises.java b/src/main/java/com/amigoscode/_4_datastructures/_4_queues/QueueExercises.java
similarity index 64%
rename from src/main/java/com/amigoscode/datastructures/queues/QueueExercises.java
rename to src/main/java/com/amigoscode/_4_datastructures/_4_queues/QueueExercises.java
index fc95dd2..b76bd4d 100644
--- a/src/main/java/com/amigoscode/datastructures/queues/QueueExercises.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_4_queues/QueueExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.queues;
+package com.amigoscode._4_datastructures._4_queues;
// Exercise: Queue Operations
// Learn how to use Queue and PriorityQueue - First In, First Out (FIFO) and priority-based ordering.
@@ -16,22 +16,29 @@ public static void main(String[] args) {
// TODO: 1 - Create a Queue of Strings using LinkedList as the implementation
// Queue queue = ...
-
+ Queue queue = new LinkedList<>();
// TODO: 2 - Add 5 elements to the queue using offer(): "Task1", "Task2", "Task3", "Task4", "Task5"
-
+ queue.offer("Task1");
+ queue.offer("Task2");
+ queue.offer("Task3");
+ queue.offer("Task4");
+ queue.offer("Task5");
// TODO: 3 - Peek at the front element without removing it
// Print the result (should be "Task1")
-
+ System.out.println("Peek: " + queue.peek());
// TODO: 4 - Poll (remove) an element from the front and print it
// Then print the queue to see the remaining elements
-
+ System.out.println("Polled: " + queue.poll());
+ System.out.println("Queue: " + queue);
// TODO: 5 - Iterate through the queue using a for-each loop and print each element
// Note: this does NOT remove elements from the queue
-
+ for (String element : queue) {
+ System.out.println(element);
+ }
// --- PriorityQueue ---
System.out.println("\n--- PriorityQueue ---");
@@ -39,7 +46,11 @@ public static void main(String[] args) {
// TODO: 6 - Create a PriorityQueue of Integers, add these values: 50, 20, 40, 10, 30
// Poll all elements one by one and print them
// Observe how they come out in natural (ascending) order, not insertion order
-
+ PriorityQueue pq = new PriorityQueue<>();
+ pq.add(50); pq.add(20); pq.add(40); pq.add(10); pq.add(30);
+ while (!pq.isEmpty()) {
+ System.out.println(pq.poll());
+ }
// --- Print Queue Simulation ---
System.out.println("\n--- Print Queue Simulation ---");
@@ -48,6 +59,14 @@ public static void main(String[] args) {
// Add these jobs using offer(): "Report.pdf", "Photo.jpg", "Letter.docx", "Slides.pptx"
// Process (poll) each job one by one, printing "Printing: " for each
// Continue until the queue is empty
+ Queue printQueue = new LinkedList<>();
+ printQueue.offer("Report.pdf");
+ printQueue.offer("Photo.jpg");
+ printQueue.offer("Letter.docx");
+ printQueue.offer("Slides.pptx");
+ while (!printQueue.isEmpty()) {
+ System.out.println("Printing: " + printQueue.poll());
+ }
}
}
diff --git a/src/main/java/com/amigoscode/datastructures/linkedlists/LinkedListExercises.java b/src/main/java/com/amigoscode/_4_datastructures/_5_linkedlists/LinkedListExercises.java
similarity index 62%
rename from src/main/java/com/amigoscode/datastructures/linkedlists/LinkedListExercises.java
rename to src/main/java/com/amigoscode/_4_datastructures/_5_linkedlists/LinkedListExercises.java
index 842ff1b..ca60689 100644
--- a/src/main/java/com/amigoscode/datastructures/linkedlists/LinkedListExercises.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_5_linkedlists/LinkedListExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.linkedlists;
+package com.amigoscode._4_datastructures._5_linkedlists;
// Exercise: LinkedList Operations
// Learn how to use LinkedList - a doubly-linked list implementation in Java.
@@ -11,32 +11,45 @@ public class LinkedListExercises {
public static void main(String[] args) {
// TODO: 1 - Create a LinkedList of Strings called 'list'
-
+ LinkedList list = new LinkedList<>();
// TODO: 2 - Add elements at the beginning using addFirst(): "First", "Second"
// Print the list after each addition to observe the order
-
+ list.addFirst("First");
+ System.out.println(list);
+ list.addFirst("Second");
+ System.out.println(list);
// TODO: 3 - Add elements at the end using addLast(): "Third", "Fourth"
// Print the list
-
+ list.addLast("Third");
+ list.addLast("Fourth");
+ System.out.println(list);
// TODO: 4 - Get and print the first element using getFirst()
// Get and print the last element using getLast()
-
+ System.out.println("First: " + list.getFirst());
+ System.out.println("Last: " + list.getLast());
// TODO: 5 - Remove the first element using removeFirst()
// Remove the last element using removeLast()
// Print the list after removals
-
+ list.removeFirst();
+ list.removeLast();
+ System.out.println(list);
// TODO: 6 - Add an element at index 1 using add(index, element): "Inserted"
// Print the list to see the element in position
-
+ list.add(1, "Inserted");
+ System.out.println(list);
// TODO: 7 - Iterate using an Iterator and print each element
// Use list.iterator() to get the Iterator
// Use hasNext() and next() in a while loop
+ Iterator iterator = list.iterator();
+ while (iterator.hasNext()) {
+ System.out.println(iterator.next());
+ }
}
}
diff --git a/src/main/java/com/amigoscode/_4_datastructures/_5_linkedlists/LinkedListVsArrayList.java b/src/main/java/com/amigoscode/_4_datastructures/_5_linkedlists/LinkedListVsArrayList.java
new file mode 100644
index 0000000..a5044b4
--- /dev/null
+++ b/src/main/java/com/amigoscode/_4_datastructures/_5_linkedlists/LinkedListVsArrayList.java
@@ -0,0 +1,75 @@
+package com.amigoscode._4_datastructures._5_linkedlists;
+
+// Exercise: LinkedList vs ArrayList Performance Comparison
+// Understand when to use LinkedList vs ArrayList by measuring operation times.
+
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+
+public class LinkedListVsArrayList {
+
+ public static void main(String[] args) {
+
+ // TODO: 1 - Create both an ArrayList and a LinkedList
+ // Fill each with 10000 elements (0 to 9999) using a for loop
+ ArrayList arrayList = new ArrayList<>();
+ LinkedList linkedList = new LinkedList<>();
+ for (int i = 0; i < 10000; i++) {
+ arrayList.add(i);
+ linkedList.add(i);
+ }
+
+ // TODO: 2 - Measure time to add an element at the beginning (index 0) for both lists
+ // Use System.nanoTime() before and after the operation
+ // Perform the add(0, value) operation 1000 times for each list
+ // Print the time taken for each in milliseconds
+ // (divide nanoseconds by 1_000_000 to get milliseconds)
+ long start = System.nanoTime();
+ for (int i = 0; i < 1000; i++) arrayList.add(0, i);
+ long alAddBegin = System.nanoTime() - start;
+
+ start = System.nanoTime();
+ for (int i = 0; i < 1000; i++) linkedList.add(0, i);
+ long llAddBegin = System.nanoTime() - start;
+
+ System.out.println("Add at beginning - ArrayList: " + alAddBegin / 1_000_000 + "ms, LinkedList: " + llAddBegin / 1_000_000 + "ms");
+
+ // TODO: 3 - Measure time to add an element at the end for both lists
+ // Perform the add(value) operation 1000 times for each list
+ // Print the time taken for each
+ start = System.nanoTime();
+ for (int i = 0; i < 1000; i++) arrayList.add(i);
+ long alAddEnd = System.nanoTime() - start;
+
+ start = System.nanoTime();
+ for (int i = 0; i < 1000; i++) linkedList.add(i);
+ long llAddEnd = System.nanoTime() - start;
+
+ System.out.println("Add at end - ArrayList: " + alAddEnd / 1_000_000 + "ms, LinkedList: " + llAddEnd / 1_000_000 + "ms");
+
+ // TODO: 4 - Measure time to get an element at the middle index for both lists
+ // Perform get(list.size() / 2) operation 1000 times for each list
+ // Print the time taken for each
+ start = System.nanoTime();
+ for (int i = 0; i < 1000; i++) arrayList.get(arrayList.size() / 2);
+ long alGet = System.nanoTime() - start;
+
+ start = System.nanoTime();
+ for (int i = 0; i < 1000; i++) linkedList.get(linkedList.size() / 2);
+ long llGet = System.nanoTime() - start;
+
+ System.out.println("Get middle - ArrayList: " + alGet / 1_000_000 + "ms, LinkedList: " + llGet / 1_000_000 + "ms");
+
+ // TODO: 5 - Print a summary explaining the differences
+ // Use System.out.println() to explain:
+ // - Why LinkedList is faster for insertions at the beginning
+ // - Why ArrayList is faster for random access (get by index)
+ // - When you would choose one over the other
+ System.out.println("\nSummary:");
+ System.out.println("- LinkedList is faster for insertions at the beginning because it only needs to update pointers.");
+ System.out.println("- ArrayList is faster for random access because it uses a contiguous array with O(1) index access.");
+ System.out.println("- Use LinkedList when you frequently insert/remove at the beginning. Use ArrayList for random access.");
+
+ }
+}
diff --git a/src/main/java/com/amigoscode/datastructures/sets/HashSetExercises.java b/src/main/java/com/amigoscode/_4_datastructures/_6_sets/HashSetExercises.java
similarity index 68%
rename from src/main/java/com/amigoscode/datastructures/sets/HashSetExercises.java
rename to src/main/java/com/amigoscode/_4_datastructures/_6_sets/HashSetExercises.java
index 92f5adf..f67f28c 100644
--- a/src/main/java/com/amigoscode/datastructures/sets/HashSetExercises.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_6_sets/HashSetExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.sets;
+package com.amigoscode._4_datastructures._6_sets;
// Exercise: HashSet Operations
// Learn how to use HashSet - an unordered collection that contains no duplicate elements.
@@ -14,27 +14,32 @@ public class HashSetExercises {
public static void main(String[] args) {
// TODO: 1 - Create a HashSet of Strings called 'fruits'
-
+ Set fruits = new HashSet<>();
// TODO: 2 - Add elements: "Apple", "Banana", "Cherry", "Apple", "Date", "Banana"
// Print the set after adding all elements
// Observe that duplicates are automatically ignored
-
+ fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry");
+ fruits.add("Apple"); fruits.add("Date"); fruits.add("Banana");
+ System.out.println(fruits);
// TODO: 3 - Check if "Cherry" exists in the set using contains()
// Print the result
-
+ System.out.println("Contains Cherry: " + fruits.contains("Cherry"));
// TODO: 4 - Remove "Date" from the set
// Print the set after removal
-
+ fruits.remove("Date");
+ System.out.println(fruits);
// TODO: 5 - Get and print the size of the set
-
+ System.out.println("Size: " + fruits.size());
// TODO: 6 - Iterate over the set using a for-each loop and print each element
// Note: the order may not match insertion order (HashSet is unordered)
-
+ for (String fruit : fruits) {
+ System.out.println(fruit);
+ }
// --- Removing Duplicates from a List ---
System.out.println("\n--- Removing Duplicates ---");
@@ -46,6 +51,9 @@ public static void main(String[] args) {
// TODO: 7 - Use a HashSet to remove duplicates from 'listWithDuplicates'
// Create a new HashSet from the list, then create a new ArrayList from the set
// Print the deduplicated list
+ Set uniqueSet = new HashSet<>(listWithDuplicates);
+ List deduplicated = new ArrayList<>(uniqueSet);
+ System.out.println("Deduplicated: " + deduplicated);
}
}
diff --git a/src/main/java/com/amigoscode/datastructures/sets/TreeSetExercises.java b/src/main/java/com/amigoscode/_4_datastructures/_6_sets/TreeSetExercises.java
similarity index 60%
rename from src/main/java/com/amigoscode/datastructures/sets/TreeSetExercises.java
rename to src/main/java/com/amigoscode/_4_datastructures/_6_sets/TreeSetExercises.java
index 908e670..93cf975 100644
--- a/src/main/java/com/amigoscode/datastructures/sets/TreeSetExercises.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_6_sets/TreeSetExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.sets;
+package com.amigoscode._4_datastructures._6_sets;
// Exercise: TreeSet Operations
// Learn how to use TreeSet - a sorted set implementation backed by a TreeMap.
@@ -10,26 +10,33 @@ public class TreeSetExercises {
public static void main(String[] args) {
// TODO: 1 - Create a TreeSet of Integers called 'numbers'
-
+ TreeSet numbers = new TreeSet<>();
// TODO: 2 - Add these elements: 50, 20, 40, 10, 30, 60, 15, 45
// Print the set and observe that elements are automatically sorted
-
+ numbers.add(50); numbers.add(20); numbers.add(40); numbers.add(10);
+ numbers.add(30); numbers.add(60); numbers.add(15); numbers.add(45);
+ System.out.println(numbers);
// TODO: 3 - Get and print the first (lowest) element using first()
// Get and print the last (highest) element using last()
-
+ System.out.println("First: " + numbers.first());
+ System.out.println("Last: " + numbers.last());
// TODO: 4 - Get a subset of elements from 20 (inclusive) to 45 (exclusive) using subSet()
// Print the subset
-
+ System.out.println("SubSet(20, 45): " + numbers.subSet(20, 45));
// TODO: 5 - Get and print the headSet (elements less than 30)
// Get and print the tailSet (elements greater than or equal to 30)
-
+ System.out.println("HeadSet(30): " + numbers.headSet(30));
+ System.out.println("TailSet(30): " + numbers.tailSet(30));
// TODO: 6 - Iterate over the TreeSet using a for-each loop
// Print each element and observe the natural ascending order
+ for (int num : numbers) {
+ System.out.println(num);
+ }
}
}
diff --git a/src/main/java/com/amigoscode/datastructures/maps/HashMapExercises.java b/src/main/java/com/amigoscode/_4_datastructures/_7_maps/HashMapExercises.java
similarity index 57%
rename from src/main/java/com/amigoscode/datastructures/maps/HashMapExercises.java
rename to src/main/java/com/amigoscode/_4_datastructures/_7_maps/HashMapExercises.java
index 25cf26d..dc72af8 100644
--- a/src/main/java/com/amigoscode/datastructures/maps/HashMapExercises.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_7_maps/HashMapExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.maps;
+package com.amigoscode._4_datastructures._7_maps;
// Exercise: HashMap Operations
// Learn how to use HashMap - a key-value pair data structure for fast lookups.
@@ -12,33 +12,42 @@ public static void main(String[] args) {
// TODO: 1 - Create a HashMap called 'studentGrades'
// This will store student names as keys and their grades as values
-
+ HashMap studentGrades = new HashMap<>();
// TODO: 2 - Put 5 entries into the map:
// "Alice" -> 92, "Bob" -> 85, "Charlie" -> 78, "Diana" -> 95, "Eve" -> 88
-
+ studentGrades.put("Alice", 92);
+ studentGrades.put("Bob", 85);
+ studentGrades.put("Charlie", 78);
+ studentGrades.put("Diana", 95);
+ studentGrades.put("Eve", 88);
// TODO: 3 - Get the grade for "Charlie" using get() and print it
-
+ System.out.println("Charlie's grade: " + studentGrades.get("Charlie"));
// TODO: 4 - Check if the key "Bob" exists using containsKey()
// Print the result
-
+ System.out.println("Contains Bob: " + studentGrades.containsKey("Bob"));
// TODO: 5 - Check if the value 95 exists using containsValue()
// Print the result
-
+ System.out.println("Contains value 95: " + studentGrades.containsValue(95));
// TODO: 6 - Remove the entry for "Eve" using remove()
// Print the map after removal
-
+ studentGrades.remove("Eve");
+ System.out.println(studentGrades);
// TODO: 7 - Iterate over the entrySet() using a for-each loop
// Print each entry in the format: "Student: , Grade: "
-
+ for (Map.Entry entry : studentGrades.entrySet()) {
+ System.out.println("Student: " + entry.getKey() + ", Grade: " + entry.getValue());
+ }
// TODO: 8 - Iterate over just the keys using keySet() and print them
// Then iterate over just the values using values() and print them
+ System.out.println("Keys: " + studentGrades.keySet());
+ System.out.println("Values: " + studentGrades.values());
}
}
diff --git a/src/main/java/com/amigoscode/_4_datastructures/_7_maps/HashMapWordCount.java b/src/main/java/com/amigoscode/_4_datastructures/_7_maps/HashMapWordCount.java
new file mode 100644
index 0000000..7d15cf0
--- /dev/null
+++ b/src/main/java/com/amigoscode/_4_datastructures/_7_maps/HashMapWordCount.java
@@ -0,0 +1,64 @@
+package com.amigoscode._4_datastructures._7_maps;
+
+// Exercise: Word Frequency Counter using HashMap
+// A practical exercise to count word occurrences in a sentence.
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class HashMapWordCount {
+
+ public static void main(String[] args) {
+
+ String sentence = "the cat sat on the mat and the cat ate the rat on the mat";
+
+ // TODO: 1 - Split the sentence into an array of words using split(" ")
+ String[] words = sentence.split(" ");
+
+ // TODO: 2 - Create a HashMap called 'wordCount'
+ // Iterate through the words array and count the frequency of each word
+ // Hint: use getOrDefault(word, 0) + 1 to increment the count
+ HashMap wordCount = new HashMap<>();
+ for (String word : words) {
+ wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
+ }
+
+ // TODO: 3 - Print each word and its count by iterating over the map
+ // Format: ": "
+ for (Map.Entry entry : wordCount.entrySet()) {
+ System.out.println(entry.getKey() + ": " + entry.getValue());
+ }
+
+ // TODO: 4 - Find and print the most frequent word
+ // Iterate through the entrySet and track the entry with the highest value
+ Map.Entry mostFrequent = null;
+ for (Map.Entry entry : wordCount.entrySet()) {
+ if (mostFrequent == null || entry.getValue() > mostFrequent.getValue()) {
+ mostFrequent = entry;
+ }
+ }
+ System.out.println("Most frequent: " + mostFrequent.getKey() + " (" + mostFrequent.getValue() + ")");
+
+ // TODO: 5 - Find and print all words that appear only once
+ // Iterate through the entrySet and collect entries where value == 1
+ System.out.println("Words appearing once:");
+ for (Map.Entry entry : wordCount.entrySet()) {
+ if (entry.getValue() == 1) {
+ System.out.println(" " + entry.getKey());
+ }
+ }
+
+ // TODO: 6 - Sort the map entries by value (frequency) in descending order and print
+ // Hint: create a List from entrySet(), then sort using a Comparator
+ // that compares entry values in reverse order
+ List> sorted = new ArrayList<>(wordCount.entrySet());
+ sorted.sort((a, b) -> b.getValue() - a.getValue());
+ System.out.println("Sorted by frequency:");
+ for (Map.Entry entry : sorted) {
+ System.out.println(" " + entry.getKey() + ": " + entry.getValue());
+ }
+
+ }
+}
diff --git a/src/main/java/com/amigoscode/datastructures/maps/MapAdvanced.java b/src/main/java/com/amigoscode/_4_datastructures/_7_maps/MapAdvanced.java
similarity index 64%
rename from src/main/java/com/amigoscode/datastructures/maps/MapAdvanced.java
rename to src/main/java/com/amigoscode/_4_datastructures/_7_maps/MapAdvanced.java
index 285d933..a7bb261 100644
--- a/src/main/java/com/amigoscode/datastructures/maps/MapAdvanced.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_7_maps/MapAdvanced.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.maps;
+package com.amigoscode._4_datastructures._7_maps;
// Exercise: Advanced Map Operations (Java 8+)
// Learn modern Map methods: getOrDefault, putIfAbsent, computeIfAbsent, merge, replaceAll, and immutable maps.
@@ -20,33 +20,47 @@ public static void main(String[] args) {
// Use a default value of 0
// Also get the score for "Alice" using getOrDefault with default 0
// Print both results
-
+ System.out.println("Diana: " + scores.getOrDefault("Diana", 0));
+ System.out.println("Alice: " + scores.getOrDefault("Alice", 0));
// TODO: 2 - Use putIfAbsent() to try adding "Bob" with value 100
// Then use putIfAbsent() to add "Diana" with value 92
// Print the map - Bob's value should remain 85, Diana should be added
-
+ scores.putIfAbsent("Bob", 100);
+ scores.putIfAbsent("Diana", 92);
+ System.out.println("After putIfAbsent: " + scores);
// TODO: 3 - Use computeIfAbsent() to add "Eve" with a computed value
// The computation: the key's length * 10 (so "Eve" -> 3 * 10 = 30)
// Print the map after the operation
-
+ scores.computeIfAbsent("Eve", key -> key.length() * 10);
+ System.out.println("After computeIfAbsent: " + scores);
// TODO: 4 - Use merge() to add 5 bonus points to "Charlie"'s score
// merge("Charlie", 5, Integer::sum) adds 5 to the existing value
// Also merge "Frank" with value 88 (new entry since key doesn't exist)
// Print the map
-
+ scores.merge("Charlie", 5, Integer::sum);
+ scores.merge("Frank", 88, Integer::sum);
+ System.out.println("After merge: " + scores);
// TODO: 5 - Use replaceAll() to add 10 points to every student's score
// replaceAll takes a BiFunction (key, value) -> newValue
// Print the map after the operation
-
+ scores.replaceAll((key, value) -> value + 10);
+ System.out.println("After replaceAll: " + scores);
// TODO: 6 - Create an immutable map using Map.of() with 3 entries:
// "Math" -> 95, "Science" -> 88, "English" -> 92
// Print the immutable map
// Try adding to it (will throw UnsupportedOperationException) - wrap in try-catch
+ Map immutableMap = Map.of("Math", 95, "Science", 88, "English", 92);
+ System.out.println("Immutable map: " + immutableMap);
+ try {
+ immutableMap.put("History", 80);
+ } catch (UnsupportedOperationException e) {
+ System.out.println("Cannot modify immutable map: " + e.getMessage());
+ }
}
}
diff --git a/src/main/java/com/amigoscode/datastructures/maps/TreeMapExercises.java b/src/main/java/com/amigoscode/_4_datastructures/_7_maps/TreeMapExercises.java
similarity index 56%
rename from src/main/java/com/amigoscode/datastructures/maps/TreeMapExercises.java
rename to src/main/java/com/amigoscode/_4_datastructures/_7_maps/TreeMapExercises.java
index 327944b..92c5a6e 100644
--- a/src/main/java/com/amigoscode/datastructures/maps/TreeMapExercises.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_7_maps/TreeMapExercises.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.maps;
+package com.amigoscode._4_datastructures._7_maps;
// Exercise: TreeMap Operations
// Learn how to use TreeMap - a sorted map implementation that maintains keys in natural order.
@@ -12,28 +12,39 @@ public static void main(String[] args) {
// TODO: 1 - Create a TreeMap called 'productPrices'
// This will store product names and their prices
-
+ TreeMap productPrices = new TreeMap<>();
// TODO: 2 - Add 5 products with prices:
// "Laptop" -> 999.99, "Phone" -> 699.99, "Tablet" -> 449.99,
// "Headphones" -> 149.99, "Mouse" -> 29.99
-
+ productPrices.put("Laptop", 999.99);
+ productPrices.put("Phone", 699.99);
+ productPrices.put("Tablet", 449.99);
+ productPrices.put("Headphones", 149.99);
+ productPrices.put("Mouse", 29.99);
// TODO: 3 - Get and print the first key using firstKey()
// Get and print the last key using lastKey()
// Observe that they are in alphabetical order
-
+ System.out.println("First key: " + productPrices.firstKey());
+ System.out.println("Last key: " + productPrices.lastKey());
// TODO: 4 - Get a submap of products from "Laptop" (inclusive) to "Phone" (exclusive)
// using subMap() and print it
-
+ System.out.println("SubMap: " + productPrices.subMap("Laptop", "Phone"));
// TODO: 5 - Iterate over the TreeMap in natural (ascending) key order
// Print each product and price in format: ": $"
-
+ for (Map.Entry entry : productPrices.entrySet()) {
+ System.out.println(entry.getKey() + ": $" + entry.getValue());
+ }
// TODO: 6 - Iterate in reverse order using descendingMap()
// Print each product and price
+ System.out.println("\nReverse order:");
+ for (Map.Entry entry : productPrices.descendingMap().entrySet()) {
+ System.out.println(entry.getKey() + ": $" + entry.getValue());
+ }
}
}
diff --git a/src/main/java/com/amigoscode/datastructures/challenge/DataStructureChallenge.java b/src/main/java/com/amigoscode/_4_datastructures/_8_challenge/DataStructureChallenge.java
similarity index 50%
rename from src/main/java/com/amigoscode/datastructures/challenge/DataStructureChallenge.java
rename to src/main/java/com/amigoscode/_4_datastructures/_8_challenge/DataStructureChallenge.java
index 6c849e3..16c4f91 100644
--- a/src/main/java/com/amigoscode/datastructures/challenge/DataStructureChallenge.java
+++ b/src/main/java/com/amigoscode/_4_datastructures/_8_challenge/DataStructureChallenge.java
@@ -1,4 +1,4 @@
-package com.amigoscode.datastructures.challenge;
+package com.amigoscode._4_datastructures._8_challenge;
// Exercise: Data Structure Challenge
// Combine multiple data structures to solve a real-world problem.
@@ -19,42 +19,80 @@ public class DataStructureChallenge {
// String name, int grade, String subject
// If using a record: record Student(String name, int grade, String subject) {}
// If using a class: include constructor, getters, and a toString() method
-
+ record Student(String name, int grade, String subject) {}
public static void main(String[] args) {
// TODO: 2 - Create a List of 10 students with various names, grades, and subjects
// Use at least 3 different subjects (e.g., "Math", "Science", "English")
// Example: new Student("Alice", 92, "Math")
-
+ List students = new ArrayList<>();
+ students.add(new Student("Alice", 92, "Math"));
+ students.add(new Student("Bob", 85, "Science"));
+ students.add(new Student("Charlie", 78, "English"));
+ students.add(new Student("Diana", 95, "Math"));
+ students.add(new Student("Eve", 88, "Science"));
+ students.add(new Student("Frank", 72, "English"));
+ students.add(new Student("Grace", 91, "Math"));
+ students.add(new Student("Hank", 83, "Science"));
+ students.add(new Student("Ivy", 96, "English"));
+ students.add(new Student("Jack", 80, "Math"));
// TODO: 3 - Use a Map> to group students by subject
// Iterate through the student list
// For each student, use computeIfAbsent() to get or create the list for their subject
// Then add the student to that list
// Print each subject and its students
-
+ Map> bySubject = new HashMap<>();
+ for (Student s : students) {
+ bySubject.computeIfAbsent(s.subject(), k -> new ArrayList<>()).add(s);
+ }
+ for (Map.Entry> entry : bySubject.entrySet()) {
+ System.out.println(entry.getKey() + ": " + entry.getValue());
+ }
// TODO: 4 - Use a Set to find all unique subjects
// Iterate through the students and add each subject to the set
// Print the unique subjects
-
+ Set subjects = new HashSet<>();
+ for (Student s : students) {
+ subjects.add(s.subject());
+ }
+ System.out.println("Unique subjects: " + subjects);
// TODO: 5 - Use a Stack to track the last 3 students "viewed"
// Push any 3 students from the list onto the stack
// Then pop and print them to show the viewing history (most recent first)
-
+ Stack viewHistory = new Stack<>();
+ viewHistory.push(students.get(0));
+ viewHistory.push(students.get(3));
+ viewHistory.push(students.get(7));
+ System.out.println("\nViewing history (most recent first):");
+ while (!viewHistory.isEmpty()) {
+ System.out.println(viewHistory.pop());
+ }
// TODO: 6 - Sort the student list by grade in descending order using a Comparator
// Use list.sort() with Comparator.comparingInt() and .reversed()
// Print the sorted list
-
+ students.sort(Comparator.comparingInt(Student::grade).reversed());
+ System.out.println("\nSorted by grade (descending):");
+ for (Student s : students) {
+ System.out.println(s);
+ }
// TODO: 7 - Print a summary report:
// - Total number of students
// - Number of unique subjects (from the Set)
// - Highest grade student (first in sorted list)
// - Number of students per subject (from the Map)
+ System.out.println("\n--- Summary Report ---");
+ System.out.println("Total students: " + students.size());
+ System.out.println("Unique subjects: " + subjects.size());
+ System.out.println("Highest grade: " + students.get(0));
+ for (Map.Entry> entry : bySubject.entrySet()) {
+ System.out.println(entry.getKey() + ": " + entry.getValue().size() + " students");
+ }
}
}
diff --git a/src/main/java/com/amigoscode/generics/classcastexception/ClassCastProblem.java b/src/main/java/com/amigoscode/_5_generics/_1_classcastexception/ClassCastProblem.java
similarity index 62%
rename from src/main/java/com/amigoscode/generics/classcastexception/ClassCastProblem.java
rename to src/main/java/com/amigoscode/_5_generics/_1_classcastexception/ClassCastProblem.java
index 983027d..dfe5fc2 100644
--- a/src/main/java/com/amigoscode/generics/classcastexception/ClassCastProblem.java
+++ b/src/main/java/com/amigoscode/_5_generics/_1_classcastexception/ClassCastProblem.java
@@ -1,4 +1,4 @@
-package com.amigoscode.generics.classcastexception;
+package com.amigoscode._5_generics._1_classcastexception;
import java.util.ArrayList;
import java.util.List;
@@ -18,11 +18,12 @@ public static void main(String[] args) {
// TODO: 1 - Create a raw (non-generic) ArrayList without any type parameter.
// Hint: List list = new ArrayList();
-
+ List list = new ArrayList();
// TODO: 2 - Add a String "Hello" and an Integer 42 to the raw list.
// This compiles fine because raw lists accept any Object.
-
+ list.add("Hello");
+ list.add(42);
// TODO: 3 - Iterate through the list and try to cast every element to String.
// Use a for loop: for (int i = 0; i < list.size(); i++)
@@ -30,16 +31,27 @@ public static void main(String[] args) {
// This will compile, but will throw ClassCastException at runtime
// when it reaches the Integer element.
-
// TODO: 4 - Wrap the casting code from TODO 3 in a try-catch block
// that catches ClassCastException. Print the exception message
// so you can see what went wrong.
-
+ try {
+ for (int i = 0; i < list.size(); i++) {
+ String s = (String) list.get(i);
+ System.out.println(s);
+ }
+ } catch (ClassCastException e) {
+ System.out.println("ClassCastException: " + e.getMessage());
+ }
// TODO: 5 - Add a comment below explaining:
// (a) Why did the ClassCastException occur?
// (b) How do generics (e.g., List) prevent this problem?
// (c) At what stage (compile-time or runtime) do generics catch type errors?
+ // (a) The ClassCastException occurred because we added an Integer (42) to the raw list
+ // and then tried to cast it to String. Integer cannot be cast to String.
+ // (b) Generics (e.g., List) prevent this by restricting what types can be added
+ // to the list. The compiler would refuse to add an Integer to a List.
+ // (c) Generics catch type errors at compile-time, preventing runtime ClassCastExceptions.
}
}
diff --git a/src/main/java/com/amigoscode/generics/typeparameters/TypeParameterBasics.java b/src/main/java/com/amigoscode/_5_generics/_2_typeparameters/TypeParameterBasics.java
similarity index 58%
rename from src/main/java/com/amigoscode/generics/typeparameters/TypeParameterBasics.java
rename to src/main/java/com/amigoscode/_5_generics/_2_typeparameters/TypeParameterBasics.java
index 143512d..8ee3f12 100644
--- a/src/main/java/com/amigoscode/generics/typeparameters/TypeParameterBasics.java
+++ b/src/main/java/com/amigoscode/_5_generics/_2_typeparameters/TypeParameterBasics.java
@@ -1,4 +1,4 @@
-package com.amigoscode.generics.typeparameters;
+package com.amigoscode._5_generics._2_typeparameters;
/**
* Exercise: Type Parameter Basics
@@ -13,19 +13,32 @@ public class TypeParameterBasics {
// TODO: 1 - Declare a generic class Container with a single private field
// of type T called "value".
-
-
// TODO: 2 - Add a constructor to Container that takes a parameter of type T
// and assigns it to the "value" field.
-
-
// TODO: 3 - Add a getter method "T getValue()" and a setter method
// "void setValue(T value)" to the Container class.
-
-
// TODO: 4 - Add a toString() method to Container that returns
// "Container{value=" + value + "}".
+ static class Container {
+ private T value;
+ public Container(T value) {
+ this.value = value;
+ }
+
+ public T getValue() {
+ return value;
+ }
+
+ public void setValue(T value) {
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return "Container{value=" + value + "}";
+ }
+ }
public static void main(String[] args) {
@@ -33,12 +46,19 @@ public static void main(String[] args) {
// (a) Container holding the value "Java Generics"
// (b) Container holding the value 2024
// Print both containers using toString().
-
+ Container stringContainer = new Container<>("Java Generics");
+ Container intContainer = new Container<>(2024);
+ System.out.println(stringContainer);
+ System.out.println(intContainer);
// TODO: 6 - Demonstrate type safety: try to call setValue(123) on the
// Container instance. Comment it out and explain why the
// compiler rejects it. Then call setValue with a valid String and
// print the updated container.
+ // stringContainer.setValue(123); // Compiler rejects this because 123 is an Integer, not a String.
+ // The Container only accepts String values for setValue().
+ stringContainer.setValue("Updated Generics");
+ System.out.println(stringContainer);
}
}
diff --git a/src/main/java/com/amigoscode/generics/genericclasses/Box.java b/src/main/java/com/amigoscode/_5_generics/_3_genericclasses/Box.java
similarity index 60%
rename from src/main/java/com/amigoscode/generics/genericclasses/Box.java
rename to src/main/java/com/amigoscode/_5_generics/_3_genericclasses/Box.java
index bd400ad..5cc23a2 100644
--- a/src/main/java/com/amigoscode/generics/genericclasses/Box.java
+++ b/src/main/java/com/amigoscode/_5_generics/_3_genericclasses/Box.java
@@ -1,4 +1,4 @@
-package com.amigoscode.generics.genericclasses;
+package com.amigoscode._5_generics._3_genericclasses;
/**
* Exercise: Generic Box Class
@@ -13,29 +13,49 @@ public class Box {
// TODO: 1 - Declare a private field of type T called "content".
// This field will store the item inside the box.
-
+ private T content;
// TODO: 2 - Create a put(T item) method that stores the item in the box,
// and a get() method that returns the stored item.
+ public void put(T item) {
+ this.content = item;
+ }
+ public T get() {
+ return content;
+ }
// TODO: 3 - Create an isEmpty() method that returns true if the content
// is null, and false otherwise.
-
+ public boolean isEmpty() {
+ return content == null;
+ }
// TODO: 4 - Override toString() to return "Box{content=" + content + "}".
// If the box is empty, it should show "Box{content=null}".
-
+ @Override
+ public String toString() {
+ return "Box{content=" + content + "}";
+ }
public static void main(String[] args) {
// TODO: 5 - Create a Box, put "Hello Generics" in it,
// print the box, and print whether it is empty.
-
+ Box stringBox = new Box<>();
+ stringBox.put("Hello Generics");
+ System.out.println(stringBox);
+ System.out.println("Is empty: " + stringBox.isEmpty());
// TODO: 6 - Create a Box, put 3.14 in it, retrieve the value
// using get(), and print it. Then create another Box without
// putting anything in it and verify isEmpty() returns true.
+ Box doubleBox = new Box<>();
+ doubleBox.put(3.14);
+ System.out.println("Value: " + doubleBox.get());
+
+ Box emptyBox = new Box<>();
+ System.out.println("Empty box is empty: " + emptyBox.isEmpty());
}
}
diff --git a/src/main/java/com/amigoscode/generics/genericclasses/Pair.java b/src/main/java/com/amigoscode/_5_generics/_3_genericclasses/Pair.java
similarity index 55%
rename from src/main/java/com/amigoscode/generics/genericclasses/Pair.java
rename to src/main/java/com/amigoscode/_5_generics/_3_genericclasses/Pair.java
index d0220f1..2c63536 100644
--- a/src/main/java/com/amigoscode/generics/genericclasses/Pair.java
+++ b/src/main/java/com/amigoscode/_5_generics/_3_genericclasses/Pair.java
@@ -1,4 +1,4 @@
-package com.amigoscode.generics.genericclasses;
+package com.amigoscode._5_generics._3_genericclasses;
import java.util.Objects;
@@ -14,28 +14,54 @@ public class Pair {
// TODO: 1 - Declare two private fields: one of type K called "key"
// and one of type V called "value".
-
+ private K key;
+ private V value;
// TODO: 2 - Create a constructor that takes a K key and a V value
// and assigns them to the fields.
-
+ public Pair(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
// TODO: 3 - Add getter methods getKey() and getValue() that return
// the key and value respectively.
+ public K getKey() {
+ return key;
+ }
+ public V getValue() {
+ return value;
+ }
// TODO: 4 - Create a swap() method that returns a new Pair with
// the key and value swapped. For example, Pair("age", 25)
// would return Pair(25, "age").
-
+ public Pair swap() {
+ return new Pair<>(value, key);
+ }
// TODO: 5 - Override toString() to return "Pair{key=" + key + ", value=" + value + "}".
-
+ @Override
+ public String toString() {
+ return "Pair{key=" + key + ", value=" + value + "}";
+ }
// TODO: 6 - Override equals(Object o) to compare two Pairs based on both
// key and value fields. Use Objects.equals() for null-safe comparison.
// Also override hashCode() using Objects.hash(key, value).
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Pair, ?> pair = (Pair, ?>) o;
+ return Objects.equals(key, pair.key) && Objects.equals(value, pair.value);
+ }
+ @Override
+ public int hashCode() {
+ return Objects.hash(key, value);
+ }
public static void main(String[] args) {
@@ -43,6 +69,12 @@ public static void main(String[] args) {
// name and age (e.g., "Alice", 30). Print the pair. Call swap()
// and print the swapped pair. Create another pair with the same
// name and age, and test equals() between the two.
+ Pair pair1 = new Pair<>("Alice", 30);
+ System.out.println(pair1);
+ Pair swapped = pair1.swap();
+ System.out.println("Swapped: " + swapped);
+ Pair pair2 = new Pair<>("Alice", 30);
+ System.out.println("pair1.equals(pair2): " + pair1.equals(pair2));
}
}
diff --git a/src/main/java/com/amigoscode/generics/genericmethods/GenericMethods.java b/src/main/java/com/amigoscode/_5_generics/_4_genericmethods/GenericMethods.java
similarity index 53%
rename from src/main/java/com/amigoscode/generics/genericmethods/GenericMethods.java
rename to src/main/java/com/amigoscode/_5_generics/_4_genericmethods/GenericMethods.java
index c5df700..cf2129f 100644
--- a/src/main/java/com/amigoscode/generics/genericmethods/GenericMethods.java
+++ b/src/main/java/com/amigoscode/_5_generics/_4_genericmethods/GenericMethods.java
@@ -1,4 +1,4 @@
-package com.amigoscode.generics.genericmethods;
+package com.amigoscode._5_generics._4_genericmethods;
import java.util.ArrayList;
import java.util.Arrays;
@@ -18,27 +18,51 @@ public class GenericMethods {
// TODO: 1 - Create a static generic method: void printArray(T[] array)
// It should print each element of the array on the same line separated
// by spaces, then print a newline at the end.
-
+ public static void printArray(T[] array) {
+ for (int i = 0; i < array.length; i++) {
+ System.out.print(array[i] + (i < array.length - 1 ? " " : ""));
+ }
+ System.out.println();
+ }
// TODO: 2 - Create a static generic method: T getFirst(List list)
// It should return the first element of the list.
// If the list is empty, return null.
-
+ public static T getFirst(List list) {
+ return list.isEmpty() ? null : list.get(0);
+ }
// TODO: 3 - Create a static generic method: T getLast(List list)
// It should return the last element of the list.
// If the list is empty, return null.
-
+ public static T getLast(List list) {
+ return list.isEmpty() ? null : list.get(list.size() - 1);
+ }
// TODO: 4 - Create a static generic method: List filterNulls(List list)
// It should return a new list containing only the non-null elements
// from the original list. Do not modify the original list.
-
+ public static List filterNulls(List list) {
+ List result = new ArrayList<>();
+ for (T item : list) {
+ if (item != null) {
+ result.add(item);
+ }
+ }
+ return result;
+ }
// TODO: 5 - Create a static generic method: boolean contains(T[] array, T target)
// It should return true if the target is found in the array.
// Use the equals() method for comparison (handle null target).
-
+ public static boolean contains(T[] array, T target) {
+ for (T element : array) {
+ if (target == null ? element == null : target.equals(element)) {
+ return true;
+ }
+ }
+ return false;
+ }
public static void main(String[] args) {
@@ -47,12 +71,28 @@ public static void main(String[] args) {
// (b) getFirst and getLast with a List of names
// (c) filterNulls with a list that contains some null values
// (d) contains to search for an element in an array
+ String[] strings = {"Hello", "World", "Java"};
+ Integer[] integers = {1, 2, 3, 4, 5};
+ printArray(strings);
+ printArray(integers);
+
+ List names = Arrays.asList("Alice", "Bob", "Charlie");
+ System.out.println("First: " + getFirst(names));
+ System.out.println("Last: " + getLast(names));
+
+ List withNulls = Arrays.asList("A", null, "B", null, "C");
+ System.out.println("Filtered: " + filterNulls(withNulls));
+ System.out.println("Contains 'World': " + contains(strings, "World"));
+ System.out.println("Contains 6: " + contains(integers, 6));
// TODO: 7 - Demonstrate type inference: call printArray and contains
// WITHOUT explicitly specifying the type parameter (i.e., just call
// printArray(myArray) instead of GenericMethods.printArray(myArray)).
// Add a comment explaining that the compiler infers T from the arguments.
+ // The compiler infers T from the arguments automatically (type inference).
+ printArray(strings);
+ System.out.println(contains(integers, 3));
}
}
diff --git a/src/main/java/com/amigoscode/generics/genericmethods/GenericSwap.java b/src/main/java/com/amigoscode/_5_generics/_4_genericmethods/GenericSwap.java
similarity index 62%
rename from src/main/java/com/amigoscode/generics/genericmethods/GenericSwap.java
rename to src/main/java/com/amigoscode/_5_generics/_4_genericmethods/GenericSwap.java
index da103ef..85e5296 100644
--- a/src/main/java/com/amigoscode/generics/genericmethods/GenericSwap.java
+++ b/src/main/java/com/amigoscode/_5_generics/_4_genericmethods/GenericSwap.java
@@ -1,4 +1,4 @@
-package com.amigoscode.generics.genericmethods;
+package com.amigoscode._5_generics._4_genericmethods;
import java.util.Arrays;
@@ -15,29 +15,46 @@ public class GenericSwap {
// TODO: 1 - Create a static generic method: void swap(T[] array, int i, int j)
// It should swap the elements at indices i and j in the array.
// Use a temporary variable of type T to perform the swap.
-
+ public static void swap(T[] array, int i, int j) {
+ T temp = array[i];
+ array[i] = array[j];
+ array[j] = temp;
+ }
// TODO: 2 - Create a static generic method: T[] reverse(T[] array)
// It should reverse the array in place and return it.
// Hint: swap elements from both ends, moving toward the center.
// Use the swap() method you wrote in TODO 1.
-
+ public static T[] reverse(T[] array) {
+ for (int i = 0; i < array.length / 2; i++) {
+ swap(array, i, array.length - 1 - i);
+ }
+ return array;
+ }
public static void main(String[] args) {
// TODO: 3 - Create an Integer[] array {1, 2, 3, 4, 5}.
// Use swap() to swap the first and last elements.
// Print the result using Arrays.toString().
-
+ Integer[] intArray = {1, 2, 3, 4, 5};
+ swap(intArray, 0, 4);
+ System.out.println(Arrays.toString(intArray));
// TODO: 4 - Create a String[] array {"A", "B", "C", "D"}.
// Use swap() to swap elements at index 1 and index 2.
// Print the result using Arrays.toString().
-
+ String[] strArray = {"A", "B", "C", "D"};
+ swap(strArray, 1, 2);
+ System.out.println(Arrays.toString(strArray));
// TODO: 5 - Use reverse() on both the Integer[] and String[] arrays.
// Print the reversed arrays using Arrays.toString().
// Verify the output is correct.
+ reverse(intArray);
+ System.out.println(Arrays.toString(intArray));
+ reverse(strArray);
+ System.out.println(Arrays.toString(strArray));
}
}
diff --git a/src/main/java/com/amigoscode/generics/boundedtypes/MultipleBounds.java b/src/main/java/com/amigoscode/_5_generics/_5_boundedtypes/MultipleBounds.java
similarity index 50%
rename from src/main/java/com/amigoscode/generics/boundedtypes/MultipleBounds.java
rename to src/main/java/com/amigoscode/_5_generics/_5_boundedtypes/MultipleBounds.java
index 8918ffb..7a255b7 100644
--- a/src/main/java/com/amigoscode/generics/boundedtypes/MultipleBounds.java
+++ b/src/main/java/com/amigoscode/_5_generics/_5_boundedtypes/MultipleBounds.java
@@ -1,4 +1,4 @@
-package com.amigoscode.generics.boundedtypes;
+package com.amigoscode._5_generics._5_boundedtypes;
import java.util.Arrays;
import java.util.List;
@@ -16,14 +16,25 @@ public class MultipleBounds {
// TODO: 1 - Create an interface called Printable with a single method:
// void print();
-
+ interface Printable {
+ void print();
+ }
// TODO: 2 - Create a static generic method:
// & Printable> T findMin(List list)
// It should return the smallest element using compareTo().
// If the list is empty, return null.
// This method requires T to be both Comparable AND Printable.
-
+ public static & Printable> T findMin(List list) {
+ if (list.isEmpty()) return null;
+ T min = list.get(0);
+ for (T element : list) {
+ if (element.compareTo(min) < 0) {
+ min = element;
+ }
+ }
+ return min;
+ }
// TODO: 3 - Create a static inner class Student that implements both
// Comparable and Printable.
@@ -31,14 +42,43 @@ public class MultipleBounds {
// a constructor, compareTo() based on grade (ascending),
// and print() that prints "Student{name='...', grade=...}".
// Also override toString() with the same format as print().
+ static class Student implements Comparable, Printable {
+ private String name;
+ private double grade;
+
+ public Student(String name, double grade) {
+ this.name = name;
+ this.grade = grade;
+ }
+ @Override
+ public int compareTo(Student other) {
+ return Double.compare(this.grade, other.grade);
+ }
+
+ @Override
+ public void print() {
+ System.out.println("Student{name='" + name + "', grade=" + grade + "}");
+ }
+
+ @Override
+ public String toString() {
+ return "Student{name='" + name + "', grade=" + grade + "}";
+ }
+ }
public static void main(String[] args) {
// TODO: 4 - Create a List with at least 3 students having
// different grades. Call findMin() to find the student with the
// lowest grade. Print the result using the print() method.
-
+ List students = Arrays.asList(
+ new Student("Alice", 85.5),
+ new Student("Bob", 72.0),
+ new Student("Charlie", 91.3)
+ );
+ Student lowest = findMin(students);
+ lowest.print();
// TODO: 5 - Add a comment below explaining:
// (a) Why must a class bound come before interface bounds?
@@ -46,6 +86,11 @@ public static void main(String[] args) {
// but is NOT valid
// (b) Can you have multiple class bounds? Why or why not?
// (c) How many interface bounds can you have?
+ // (a) The class bound must come first because Java syntax requires it; the compiler
+ // uses the first bound as the erasure type, and it must be a class (or the first interface).
+ // (b) No, you cannot have multiple class bounds because Java does not support
+ // multiple class inheritance.
+ // (c) You can have as many interface bounds as you want (no limit).
}
}
diff --git a/src/main/java/com/amigoscode/generics/boundedtypes/UpperBound.java b/src/main/java/com/amigoscode/_5_generics/_5_boundedtypes/UpperBound.java
similarity index 52%
rename from src/main/java/com/amigoscode/generics/boundedtypes/UpperBound.java
rename to src/main/java/com/amigoscode/_5_generics/_5_boundedtypes/UpperBound.java
index d596899..30ee865 100644
--- a/src/main/java/com/amigoscode/generics/boundedtypes/UpperBound.java
+++ b/src/main/java/com/amigoscode/_5_generics/_5_boundedtypes/UpperBound.java
@@ -1,4 +1,4 @@
-package com.amigoscode.generics.boundedtypes;
+package com.amigoscode._5_generics._5_boundedtypes;
import java.util.Arrays;
import java.util.List;
@@ -18,25 +18,54 @@ public class UpperBound {
// TODO: 1 - Create a static generic method: double sum(List list)
// It should return the sum of all elements as a double.
// Use the doubleValue() method on each element (available because T extends Number).
-
+ public static double sum(List list) {
+ double total = 0;
+ for (T element : list) {
+ total += element.doubleValue();
+ }
+ return total;
+ }
// TODO: 2 - Create a static generic method: T findMax(List list)
// It should return the largest element in the list.
// Compare elements using doubleValue(). If the list is empty, return null.
-
+ public static T findMax(List list) {
+ if (list.isEmpty()) return null;
+ T max = list.get(0);
+ for (T element : list) {
+ if (element.doubleValue() > max.doubleValue()) {
+ max = element;
+ }
+ }
+ return max;
+ }
// TODO: 3 - Create a generic class NumberBox with a private T field
// called "number" and a constructor that takes T.
-
-
// TODO: 4 - In NumberBox, add an isPositive() method that returns true if the
// stored number's doubleValue() is greater than 0.
-
-
// TODO: 5 - In NumberBox, add toInt() and toDouble() conversion methods that
// return the stored number as an int (using intValue()) and as a double
// (using doubleValue()) respectively.
+ static class NumberBox {
+ private T number;
+
+ public NumberBox(T number) {
+ this.number = number;
+ }
+ public boolean isPositive() {
+ return number.doubleValue() > 0;
+ }
+
+ public int toInt() {
+ return number.intValue();
+ }
+
+ public double toDouble() {
+ return number.doubleValue();
+ }
+ }
public static void main(String[] args) {
@@ -46,13 +75,29 @@ public static void main(String[] args) {
// Print the results for each.
// Also create a NumberBox and NumberBox and test
// isPositive(), toInt(), and toDouble().
+ List intList = Arrays.asList(1, 2, 3, 4, 5);
+ System.out.println("Sum of integers: " + sum(intList));
+ System.out.println("Max of integers: " + findMax(intList));
+
+ List doubleList = Arrays.asList(1.5, 2.5, 3.5);
+ System.out.println("Sum of doubles: " + sum(doubleList));
+ System.out.println("Max of doubles: " + findMax(doubleList));
+
+ NumberBox intBox = new NumberBox<>(42);
+ System.out.println("isPositive: " + intBox.isPositive());
+ System.out.println("toInt: " + intBox.toInt());
+ System.out.println("toDouble: " + intBox.toDouble());
+ NumberBox doubleBox = new NumberBox<>(-3.14);
+ System.out.println("isPositive: " + doubleBox.isPositive());
// TODO: 7 - Uncomment the line below and observe the compile error.
// Then comment it back out and add a comment explaining why it fails.
//
// List strings = Arrays.asList("a", "b");
// double result = sum(strings); // Why does this not compile?
+ // It fails because String does not extend Number. The bound
+ // restricts T to Number and its subclasses only.
}
}
diff --git a/src/main/java/com/amigoscode/generics/wildcards/LowerBoundedWildcard.java b/src/main/java/com/amigoscode/_5_generics/_6_wildcards/LowerBoundedWildcard.java
similarity index 55%
rename from src/main/java/com/amigoscode/generics/wildcards/LowerBoundedWildcard.java
rename to src/main/java/com/amigoscode/_5_generics/_6_wildcards/LowerBoundedWildcard.java
index f415c28..b2af292 100644
--- a/src/main/java/com/amigoscode/generics/wildcards/LowerBoundedWildcard.java
+++ b/src/main/java/com/amigoscode/_5_generics/_6_wildcards/LowerBoundedWildcard.java
@@ -1,4 +1,4 @@
-package com.amigoscode.generics.wildcards;
+package com.amigoscode._5_generics._6_wildcards;
import java.util.ArrayList;
import java.util.Arrays;
@@ -22,7 +22,11 @@ public class LowerBoundedWildcard {
// It should add the integers 1, 2, and 3 to the list.
// This works because any list that holds Integer or a supertype of Integer
// can safely accept Integer values.
-
+ public static void addNumbers(List super Integer> list) {
+ list.add(1);
+ list.add(2);
+ list.add(3);
+ }
// TODO: 2 - Create a static method:
// void moveElements(List extends T> source, List super T> destination)
@@ -30,7 +34,11 @@ public class LowerBoundedWildcard {
// This is the PECS principle in action:
// source uses "extends" because it PRODUCES elements (we read from it)
// destination uses "super" because it CONSUMES elements (we write to it)
-
+ public static void moveElements(List extends T> source, List super T> destination) {
+ for (T element : source) {
+ destination.add(element);
+ }
+ }
public static void main(String[] args) {
@@ -39,7 +47,17 @@ public static void main(String[] args) {
// (b) List - Number is a supertype of Integer
// (c) List