├── Img ├── ROADMAP.png ├── types.png ├── collections.png └── simpleInterest.png ├── .gitignore ├── db ├── tasks │ ├── sqlite_install.MD │ ├── jdbc_connection.MD │ ├── sql_essentials.MD │ └── advance_database_operations.MD ├── lessons │ ├── procedures_triggers.MD │ ├── database_intro.MD │ ├── siud_sql.MD │ ├── sql_jdbc.MD │ ├── jdbc.MD │ ├── advance_jdbc_intro.MD │ ├── transactions.MD │ ├── table_keys.MD │ ├── crud.MD │ ├── sqllite_env.MD │ ├── db_normalization.MD │ └── joins_conditions.MD └── projects │ ├── atm_project.MD │ └── lms_project.MD ├── JavaCore └── lessons │ ├── hello_world.MD │ ├── linput_scanning.MD │ ├── atm_project.MD │ ├── final_blocks.MD │ ├── while.MD │ ├── javadoc.MD │ ├── treeset.MD │ ├── internal_class.MD │ ├── own_exception.MD │ ├── do_while.MD │ ├── static.MD │ ├── matrix.MD │ └── polymorphism.MD ├── spring ├── projects │ ├── project_1.MD │ ├── project_2.MD │ └── project_3.MD └── lessons │ ├── module_3.MD │ ├── module_1.MD │ └── module_5.MD └── readme.MD /Img/ROADMAP.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/temirlan100/javat/HEAD/Img/ROADMAP.png -------------------------------------------------------------------------------- /Img/types.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/temirlan100/javat/HEAD/Img/types.png -------------------------------------------------------------------------------- /Img/collections.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/temirlan100/javat/HEAD/Img/collections.png -------------------------------------------------------------------------------- /Img/simpleInterest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/temirlan100/javat/HEAD/Img/simpleInterest.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 2 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 3 | 4 | .idea 5 | 6 | # User-specific stuff 7 | .idea/**/workspace.xml 8 | .idea/**/tasks.xml 9 | .idea/**/usage.statistics.xml 10 | .idea/**/dictionaries 11 | .idea/**/shelf 12 | 13 | # AWS User-specific 14 | .idea/**/aws.xml 15 | 16 | # Generated files 17 | .idea/**/contentModel.xml 18 | 19 | # Sensitive or high-churn files 20 | .idea/**/dataSources/ 21 | .idea/**/dataSources.ids 22 | .idea/**/dataSources.local.xml 23 | .idea/**/sqlDataSources.xml 24 | .idea/**/dynamic.xml 25 | .idea/**/uiDesigner.xml 26 | .idea/**/dbnavigator.xml 27 | 28 | # Gradle 29 | .idea/**/gradle.xml 30 | .idea/**/libraries 31 | 32 | # Gradle and Maven with auto-import 33 | # When using Gradle or Maven with auto-import, you should exclude module files, 34 | # since they will be recreated, and may cause churn. Uncomment if using 35 | # auto-import. 36 | # .idea/artifacts 37 | # .idea/compiler.xml 38 | # .idea/jarRepositories.xml 39 | # .idea/modules.xml 40 | # .idea/*.iml 41 | # .idea/modules 42 | # *.iml 43 | # *.ipr 44 | 45 | # CMake 46 | cmake-build-*/ 47 | 48 | # Mongo Explorer plugin 49 | .idea/**/mongoSettings.xml 50 | 51 | # File-based project format 52 | *.iws 53 | 54 | # IntelliJ 55 | out/ 56 | 57 | # mpeltonen/sbt-idea plugin 58 | .idea_modules/ 59 | 60 | # JIRA plugin 61 | atlassian-ide-plugin.xml 62 | 63 | # Cursive Clojure plugin 64 | .idea/replstate.xml 65 | 66 | # SonarLint plugin 67 | .idea/sonarlint/ 68 | 69 | # Crashlytics plugin (for Android Studio and IntelliJ) 70 | com_crashlytics_export_strings.xml 71 | crashlytics.properties 72 | crashlytics-build.properties 73 | fabric.properties 74 | 75 | # Editor-based Rest Client 76 | .idea/httpRequests 77 | 78 | # Android studio 3.1+ serialized cache file 79 | .idea/caches/build_file_checksums.ser -------------------------------------------------------------------------------- /db/tasks/sqlite_install.MD: -------------------------------------------------------------------------------- 1 | **Task A: Set up a local SQL database environment using SQLite** 2 | 3 | **Description:** 4 | Welcome to your next challenge in the world of data management! In this task, you'll embark on a practical journey to 5 | set up your very own local SQL database environment using SQLite, a lightweight and highly efficient database software. 6 | 7 | **Objectives:** 8 | 1. **Understand the Basics:** Begin with a brief introduction to SQL databases. Learn what they are, why they're important, and how they're used in the tech industry. 9 | 2. **Install SQLite:** Follow step-by-step instructions to download and install SQLite on your computer. Don't worry, it's simple and we'll guide you through each step! 10 | 3. **Create Your First Database:** Once SQLite is up and running, you'll create your first database. This is where you'll store and manage data. 11 | 4. **Explore SQLite Features:** Learn about the different features and functionalities of SQLite. Understand how to create tables, insert data, and query your database to retrieve information. 12 | 5. **Hands-on Practice:** Put your knowledge to the test with a series of exercises. You'll be inserting, updating, and querying data like a pro in no time! 13 | 6. **Project Assignment:** As a capstone to your learning, you'll complete a mini-project where you'll design and manage a database for a hypothetical scenario. 14 | 15 | **Learning Outcomes:** 16 | - Gain foundational knowledge of SQL databases. 17 | - Develop practical skills in setting up and managing a local database. 18 | - Understand the importance and applications of databases in real-world scenarios. 19 | 20 | **Who is this for?** 21 | This task is perfect for students who are new to databases or those looking to strengthen their foundational skills 22 | in SQL. Whether you're a computer science major, a budding data analyst, or just curious about how databases work, 23 | this hands-on experience is a great way to learn! 24 | So, are you ready to dive into the world of databases? Let's get started with SQLite! 25 | -------------------------------------------------------------------------------- /db/tasks/jdbc_connection.MD: -------------------------------------------------------------------------------- 1 | ### Task Description 2 | #### **Objective:** 3 | Gain hands-on experience with JDBC by connecting to an SQLite database and performing basic SQL operations through a Java application. 4 | 5 | #### **Prerequisites:** 6 | - Ensure SQLite is installed on your system or accessible for your students. 7 | - Include the SQLite JDBC driver in your project's classpath. 8 | 9 | #### Part A: Establish a JDBC Connection to SQLite 10 | **Task:** 11 | Create a Java program that establishes a JDBC connection to an SQLite database named `students.db`. 12 | SQLite will create the database file if it does not exist, so there's no need to manually create the file. 13 | 14 | **Instructions:** 15 | 16 | 1. **Set Up the JDBC Driver:** Make sure the SQLite JDBC driver is correctly set up in your project. 17 | 2. **Establish Connection:** Write code to establish a connection to the `students.db` database. 18 | 3. **Connection Feedback:** The program should indicate whether the connection was successfully established. 19 | 20 | #### Part B: Execute Basic SQL Queries using JDBC 21 | **Task:** 22 | Extend your program to interact with a database table named `students`. 23 | The table should have columns for `id` (INTEGER), `name` (TEXT), and `grade` (INTEGER). 24 | Perform basic SQL operations on this table. 25 | 26 | **Instructions:** 27 | 1. **Table Setup:** Ensure your program checks for the existence of the `students` table and creates it if it doesn't exist. 28 | 2. **CRUD Operations:** Implement functionality to insert, select, update, and delete student records in the `students` table. Specifically, you should: 29 | - Insert at least three student records. 30 | - Select and display all student records. 31 | - Update the grade of at least one student. 32 | - Delete at least one student record. 33 | 3. **Transaction Management:** Apply transaction management techniques where appropriate, especially for operations that modify data (INSERT, UPDATE, DELETE). Ensure your program can roll back changes if an operation fails. 34 | 35 | **Deliverables:** 36 | Submit a Java program that demonstrates: 37 | - Connecting to an SQLite database. 38 | - Checking for and creating a necessary table if it doesn't exist. 39 | - Performing INSERT, SELECT, UPDATE, and DELETE operations on the table. 40 | - Managing transactions with commit and rollback mechanisms. 41 | 42 | **Evaluation Criteria:** 43 | 44 | Your submission will be evaluated based on: 45 | - Code clarity and organization. 46 | - Proper use of JDBC for database connection and operations. 47 | - Effective implementation of transaction management. 48 | - Handling of SQL exceptions and resource management (ensuring connections, statements, and result sets are closed properly). 49 | -------------------------------------------------------------------------------- /JavaCore/lessons/hello_world.MD: -------------------------------------------------------------------------------- 1 | ## Which PC and Operating System to choose for Java programming? 2 | - Q: I want to become a programmer. Should I buy MacBook Pro? 3 | - A: Not really, you can use any PC. But it's recommended to have at least 8GB RAM [see here](https://www.jetbrains.com/help/idea/installation-guide.html#requirements) 4 | 5 | - Q: Which OS should I have? Should I install Linux? 6 | - A: Linux is a good choice, and it's very popular, BUT all modern OS (Windows, MacOS, Linux) are also compatible with IntelliJ Idea (program where you will be writing your code). 7 | 8 | ## Linux operating system 9 | Linux is an open source and freely distributed operating system based on the Unix kernel. 10 | The system is popular in the field of servers, embedded systems and many other areas. 11 | 12 | ## History and Features of the Java Language 13 | Java is an object-oriented programming language that was developed in the early 1990s at Sun Microsystems. The main features are: 14 | - **Platform Independence**: Programs written in Java can be run on any platform using the Java Virtual Machine (JVM). 15 | - **Security**: Java offers a number of security mechanisms, including bytecode verification. 16 | - **Multithreading**: The language contains inbuilt support for multithreading, allowing efficient use of system resources. 17 | 18 | ## Installing the JDK (Java Development Kit) 19 | The JDK is a Java development kit that includes everything you need to create and run Java applications. 20 | 1. Go to [official Oracle website](https://www.oracle.com/java/technologies/downloads/#java21). 21 | 2. Select the **JDK Development Kit 21** version for your operating system and follow the installation instructions. 22 | 23 | ## Installing the IntelliJ IDEA development environment 24 | IntelliJ IDEA is a popular development environment for Java. 25 | 1. Go to [official JetBrains website](https://www.jetbrains.com/toolbox-app/) and download ToolBox. 26 | 2. Run the ToolBox application. 27 | 3. Select "Community Edition" (free version) and download. 28 | 3. Install by following the instructions of the installation wizard. 29 | 30 | ## "Hello World!" - Your first Java programme 31 | After installing everything you need, let's create your first programme: 32 | 33 | 1. Start IntelliJ IDEA and create a new project. 34 | 2. Select "Java" and click "Next". 35 | 3. Give your project a name, for example "HelloWorld". 36 | 4. In the editor that opens, enter the following code: 37 | 38 | ```java 39 | public class HelloWorld { 40 | public static void main(String[] args) { 41 | System.out.println("Hello, World!"); 42 | } 43 | } 44 | ``` 45 | Run the program by clicking on the green triangle next to the main method. 46 | You should see the "Hello, World!" output in the console. 47 | -------------------------------------------------------------------------------- /db/lessons/procedures_triggers.MD: -------------------------------------------------------------------------------- 1 | ### Stored Procedures and Triggers 2 | ### 1. Stored Procedures in Java+DB (SQL) 3 | 4 | **Definition and Use Cases:** 5 | - Stored procedures are precompiled SQL statements stored in a database. They are essential for encapsulating complex operations, enhancing performance, and ensuring data integrity. 6 | - Ideal for complex transactions, where multiple SQL statements must be executed atomically. They are also used for encapsulating the business logic as part of the database layer. 7 | 8 | **Real Business Cases:** 9 | - **Data Aggregation:** In banking systems, a stored procedure might be used to calculate the monthly interest for all accounts. 10 | - **Batch Processing:** In e-commerce, a stored procedure can handle bulk updates for product prices or inventory levels. 11 | - **Data Validation:** Insurance applications often use stored procedures to validate policy information before insertion or updates. 12 | 13 | **Calling Stored Procedures from Java:** 14 | - Utilize JDBC (Java Database Connectivity) API. 15 | - Code snippet for calling a procedure: 16 | ```java 17 | Connection conn = DriverManager.getConnection(url, username, password); 18 | CallableStatement statement = conn.prepareCall("{call procedureName(?, ?)}"); 19 | statement.setString(1, "param1"); 20 | statement.setInt(2, 100); 21 | ResultSet rs = statement.executeQuery(); 22 | // Handle ResultSet 23 | ``` 24 | 25 | ### 2. Triggers 26 | **Definition and Use Cases:** 27 | - Triggers are automated procedures executed in response to specific events on a particular table or view in a database. 28 | - They are useful for enforcing business rules, maintaining data integrity, and automatically updating related tables. 29 | 30 | **Real Business Cases:** 31 | - **Audit Logging:** In financial applications, triggers are used for maintaining audit logs. Any modification in transaction tables can automatically be logged for compliance and monitoring. 32 | - **Automatic Notifications:** In CRM systems, triggers can notify account managers when their client data is updated or changed. 33 | - **Data Integrity:** In healthcare systems, triggers ensure critical patient data is not inadvertently modified or deleted. 34 | 35 | **Integration with Java:** 36 | - Java applications can perform database operations (insert, update, delete) which in turn can activate triggers. 37 | - While triggers operate at the database level, their effects (such as data changes or logging) are observed and handled by Java applications. 38 | 39 | ### Real Business Case Integration 40 | - **Banking System:** 41 | - Stored Procedure: Automate the calculation of monthly interests or loan repayments. 42 | - Trigger: Detect and log any unauthorized access or modifications to sensitive customer data. 43 | - **E-Commerce Platform:** 44 | - Stored Procedure: Bulk update of product prices based on seasonal offers or stock levels. 45 | - Trigger: Automatically update the inventory count when a new sale is registered. 46 | - **Healthcare Application:** 47 | - Stored Procedure: Validate and process patient data before updating medical records. 48 | - Trigger: Create a backup of patient records before any critical updates. 49 | 50 | 51 | ### Recommended Resources 52 | - [Stored Procedures](https://www.w3schools.com/sql/sql_stored_procedures.asp) 53 | - [Trigger](https://www.geeksforgeeks.org/sql-trigger-student-database/) 54 | -------------------------------------------------------------------------------- /db/lessons/database_intro.MD: -------------------------------------------------------------------------------- 1 | # Understanding Databases: Types and Importance 2 | ## Introduction to Databases 3 | A database is like a digital filing cabinet where we store, organize, and retrieve data. In the modern digital world, databases are essential for managing the vast amounts of data generated daily, whether it's for a small business or a global social network. 4 | 5 | ## Importance of Databases 6 | - **Efficient Data Management**: Databases allow us to handle large volumes of data efficiently and securely. 7 | - **Accessibility**: They enable multiple users to access and work with data simultaneously. 8 | - **Data Integrity**: Databases help in maintaining the accuracy and consistency of data. 9 | 10 | ## Types of Databases 11 | 12 | ### 1. Relational Databases (RDBMS) 13 | - **What Are They?**: These databases store data in tables, which are connected to each other through relationships. 14 | - **SQL**: They use a language called SQL (Structured Query Language) for querying and manipulating data. 15 | - **Java Example**: 16 | ```java 17 | // Connect to MySQL database 18 | Connection con = DriverManager.getConnection("jdbc:mysql://localhost/db_name", "user", "password"); 19 | Statement stmt = con.createStatement(); 20 | ResultSet rs = stmt.executeQuery("SELECT * FROM tableName"); 21 | ``` 22 | 23 | ### 2. NoSQL Databases 24 | - **Different Types**: Includes document databases like MongoDB, key-value stores like Redis, and graph databases like Neo4j. 25 | - **Why Use Them?**: They are flexible and can handle a variety of data formats, making them suitable for big data and real-time web applications. 26 | - **Java Example with MongoDB**: 27 | ```java 28 | // Connect to MongoDB 29 | MongoClient mongoClient = MongoClients.create("mongodb://localhost"); 30 | MongoDatabase database = mongoClient.getDatabase("testDB"); 31 | MongoCollection collection = database.getCollection("testCollection"); 32 | ``` 33 | 34 | ### 3. In-Memory Databases 35 | - **Quick Access**: These databases store data in the main memory (RAM) for faster access. 36 | - **Use Cases**: Ideal for applications that require high-speed data processing. 37 | 38 | ## Database Design Concepts 39 | - **Data Modeling**: It's the process of creating a model for how the data will be stored in the database. 40 | - **Normalization**: This is a technique used to design a database that reduces redundancy and improves data integrity. 41 | 42 | ## SQL Basics 43 | - **Basic Commands**: 44 | - `SELECT`: To retrieve data from a database. 45 | - `INSERT`: To add new data. 46 | - `UPDATE`: To modify existing data. 47 | - `DELETE`: To remove data. 48 | - **Using SQL in Java**: 49 | ```java 50 | // Example of executing a SELECT query 51 | String query = "SELECT * FROM users"; 52 | ResultSet rs = stmt.executeQuery(query); 53 | ``` 54 | 55 | ## Conclusion 56 | Understanding databases is crucial in the world of programming and software development. As a Java developer, 57 | knowledge of how to interact with different types of databases and manipulate data is invaluable. 58 | 59 | 60 | ### Recommended Resources 61 | - [An Introduction to Databases](https://www.digitalocean.com/community/conceptual-articles/an-introduction-to-databases) 62 | - [Access - Introduction to Databases](https://edu.gcfglobal.org/en/access/introduction-to-databases/1/) 63 | - [What Is a Database?](https://www.oracle.com/in/database/what-is-database/) 64 | -------------------------------------------------------------------------------- /db/tasks/sql_essentials.MD: -------------------------------------------------------------------------------- 1 | ### Simplified Database Assignment for Beginners: Medical System Context 2 | 3 | #### Overview 4 | This assignment introduces you to database design and SQL in the context of a medical system. You will design 5 | a database schema relevant to a medical clinic, create the database, populate it with data, and perform basic SQL 6 | operations. 7 | 8 | #### Part A: Design a Simple Database Schema 9 | 1. **Objective**: Develop a basic schema for a Medical Clinic system. 10 | 2. **Schema Requirements**: 11 | - **Entities**: Patients, Doctors, Appointments, Medications, and Departments. 12 | - **Patients**: Attributes include PatientID (primary key), Name, DateOfBirth, and Gender. 13 | - **Doctors**: Attributes include DoctorID (primary key), Name, Specialty, and DepartmentID (foreign key). 14 | - **Appointments**: Attributes include AppointmentID (primary key), PatientID (foreign key), DoctorID (foreign key), AppointmentDate, and Issue. 15 | - **Medications**: Attributes include MedicationID (primary key), Name, and CommonUses. 16 | - **Departments**: Attributes include DepartmentID (primary key), DepartmentName, and Location. 17 | - Sketch a simple diagram showing these entities and their relationships (e.g., Patients to Appointments, Doctors to Departments). 18 | 19 | #### Part B: Create and Populate the Database 20 | 1. **Objective**: Construct the database using your schema and add sample data. 21 | 2. **Steps**: 22 | - Use SQL commands to create the five tables: Patients, Doctors, Appointments, Medications, and Departments. 23 | - Add at least 15 entries to each table. 24 | 25 | 26 | #### Part C: Advanced SQL Queries 27 | 1. **Objective**: Enhance your SQL proficiency by executing a variety of complex queries on your medical clinic database. 28 | 2. **Query Tasks**: 29 | 30 | - **Data Retrieval**: 31 | - **Find Appointments**: Write a query to find all appointments for a specific patient. 32 | - **Medication by Issue**: Write a query to list all medications commonly used for a specific issue mentioned in appointments. 33 | - **Doctor's Patient Count**: Write a query to display the total number of patients seen by each doctor. 34 | 35 | - **Data Update**: 36 | - **Reschedule Appointment**: Write a query to change the appointment date for a particular appointment. 37 | - **Update Patient Details**: Write a query to update a patient's information in case of change in their contact details or other relevant data. 38 | 39 | - **Join Operation**: 40 | - **Patient-Doctor Overview**: Write a query to show a list of patients along with their appointed doctor's name and specialty. 41 | - **Doctors and Patients by Department**: Write a query to display all doctors in a specific department along with their patients' names. 42 | - **Yearly Checkup Reminder**: Write a query to find any patients who have not had an appointment within the last year. 43 | 44 | - **Aggregate Data**: 45 | - **Average Daily Appointments**: Write a query to generate a report showing the average number of appointments per day. 46 | 47 | #### Deliverables 48 | - The same as previously listed, now including the enhanced SQL queries and their detailed explanations. 49 | 50 | #### Assessment Criteria 51 | - Accuracy and sophistication of SQL queries. 52 | - Demonstrated understanding of advanced SQL operations, particularly join and aggregate functions. 53 | - Clear and concise explanations of the purpose and expected results of each query. 54 | 55 | #### Deliverables 56 | - A diagram of your medical clinic database schema. 57 | - SQL commands used for creating and populating tables. 58 | - SQL queries for Part C with a brief explanation for each. 59 | 60 | -------------------------------------------------------------------------------- /db/tasks/advance_database_operations.MD: -------------------------------------------------------------------------------- 1 | ### Task Description: Kindergarten Management System 2 | This task involves developing a small Java application for managing children in a kindergarten. 3 | The system will be divided into two main parts: Part A focuses on implementing CRUD functionality, 4 | and Part B enhances the application with transaction management and error handling. This system aims to provide 5 | a basic framework for managing child records in a kindergarten setting, including their names, ages, and other 6 | relevant details. 7 | 8 | --- 9 | #### Part A: CRUD Functionality 10 | **Objective**: Implement basic CRUD operations to manage children's records in a kindergarten. Each child's record should include at least the child's ID, name, age, and a description of their favorite activities. 11 | **Requirements**: 12 | 1. **Model Creation**: Define a `Child` class that includes properties for the child's ID, name, age, and favorite activities. 13 | 2. **Database Setup**: Use a relational database (e.g., MySQL, H2) to store child records. Create a table named `children` with appropriate columns for the `Child` class properties. 14 | 3. **DAO Layer**: 15 | - Create a `ChildDAO` interface that defines methods for CRUD operations. 16 | - Implement the `ChildDAO` interface in a class named `ChildDAOImpl` using JDBC to perform database operations. 17 | 4. **Service Layer**: Implement a `ChildService` class that uses `ChildDAO` to perform CRUD operations. This layer will handle business logic, if any (e.g., age validation). 18 | 5. **View Layer**: Develop a simple console-based UI (`ChildView`) that allows users to interact with the system. The UI should offer options to add a new child, view all children, update a child's details, and delete a child's record. 19 | 20 | **Functionalities**: 21 | - **Create**: Add new child records to the database. 22 | - **Read**: List all children's records and view details of a specific child. 23 | - **Update**: Modify the details of an existing child's record. 24 | - **Delete**: Remove a child's record from the database. 25 | 26 | --- 27 | 28 | #### Part B: Transaction Management and Error Handling 29 | **Objective**: Enhance the kindergarten management system by incorporating transaction management and comprehensive error handling to ensure data integrity and robustness. 30 | **Requirements**: 31 | 1. **Transaction Management**: 32 | - Modify the `ChildService` to manage transactions, especially for operations that involve multiple steps or updates. Ensure that operations either complete fully or roll back in case of any failure, maintaining data integrity. 33 | - Use `Connection.setAutoCommit(false)` and manage commit/rollback manually in the service layer. 34 | 2. **Error Handling**: 35 | - Implement try-catch blocks around database operations in the DAO layer to catch SQL exceptions. 36 | - Propagate exceptions to the service layer, where appropriate error messages should be logged/displayed, and decide whether to commit or roll back transactions. 37 | - In the view layer (`ChildView`), handle exceptions gracefully to inform the user of any errors without exposing system internals or crashing the application. 38 | 39 | **Enhancements**: 40 | - **Data Validation**: Before performing any CRUD operation, validate the input data (e.g., ensure age is within a reasonable range) in the service layer. 41 | - **Logging**: Implement logging throughout the application to record key events, especially at the start and end of transactions, and when exceptions occur. 42 | - **User Feedback**: Ensure the console UI provides clear feedback for successful operations as well as descriptive error messages when something goes wrong. 43 | 44 | --- 45 | 46 | **Deliverables**: 47 | - Source code for all parts of the application, including the model, DAO, service, and view layers. 48 | - SQL scripts for creating and setting up the database schema. 49 | - Documentation on how to set up and run the application, including any required dependencies. 50 | -------------------------------------------------------------------------------- /JavaCore/lessons/linput_scanning.MD: -------------------------------------------------------------------------------- 1 | # Scanner Class 2 | 3 | The standard input is like a data stream that enters a program, and it's managed by the operating system. By default, it takes data from keyboard input, but it's also possible to redirect it from a file. 4 | 5 | Not all programs require standard input, but it's essential for many programming tasks. It follows a common pattern: 6 | 7 | 1. **Read Data**: Get data from standard input (System.in). 8 | 2. **Process Data**: Manipulate the data to obtain the desired outcome. 9 | 3. **Output Result**: Display the result to standard output (System.out). 10 | 11 | This approach makes it easy to test code with different input formats, which is why we use it frequently. 12 | 13 | ## 1. Using the Scanner Class 14 | 15 | The Scanner class simplifies reading data from standard input. It can handle various data types, such as strings and numbers. Let's explore its usage: 16 | 17 | 1.1. **Import the Scanner**: Start by adding this import statement at the top of your source code file: 18 | ```java 19 | import java.util.Scanner; 20 | ``` 21 | 1.2. **Create a Scanner Object**: After the import, create a Scanner object for standard input: 22 | ```java 23 | Scanner scanner = new Scanner(System.in); 24 | ``` 25 | 26 | This line initializes the Scanner, allowing you to use its methods. You'll learn more about creating objects in other topics. **System.in** indicates that the program will read text from the standard input. 27 | 28 | ## 2. Reading Strings 29 | You can read strings using two Scanner methods. If your input is an integer or a single word, use the **next()** method. For example, this code reads a user's name and greets them: 30 | ```java 31 | String name = scanner.next(); 32 | System.out.println("Hello, " + name + "!"); 33 | ``` 34 | For instance, if the user's name is James, the output will be "Hello, James!" 35 | 36 | If the input is an integer, like 123, the program will output it as a string: 37 | ```java 38 | Hello, 123! 39 | ``` 40 | If the user enters a compound name like "Erich Maria," the program only captures the first word: 41 | ```java 42 | Hello, Erich! 43 | ``` 44 | For multi-word input, use the **nextLine()** method, which reads and outputs the entire line: 45 | ```java 46 | Hello, Erich Maria! 47 | ``` 48 | Note that **next()** reads only one word, excluding spaces, while **nextLine()** includes all encountered spaces. 49 | 50 | ## 3. Handling Multiline Input 51 | Reading multiline input requires attention to the cursor's position and the behavior of reading methods. Here's an example: 52 | ```java 53 | |This is a simple 54 | multiline input, 55 | that is being read 56 | ``` 57 | The cursor is initially marked with "|". When you use **next()**, the program reads until the next space, shown in blue: 58 | ```java 59 | This| is a simple 60 | multiline input, 61 | that is being read 62 | ``` 63 | With **nextLine()**, the program reads from the cursor position to the end of the line, indicated in green: 64 | ```java 65 | This is a simple 66 | |multiline input, 67 | that is being read 68 | ``` 69 | Using **next()** twice reads two words, as shown in orange: 70 | ```java 71 | This is a simple 72 | multiline| input, 73 | that is being read 74 | ``` 75 | Another **next()** reads the second word without spaces, no matter how many there are, as indicated in light blue: 76 | ```java 77 | This is a simple 78 | multiline input,| 79 | that is being read 80 | ``` 81 | **nextLine()** behaves differently, returning an empty line if it starts right before a new line: 82 | ```java 83 | This is a simple 84 | multiline input, 85 | |that is being read 86 | ``` 87 | To summarize, we've explored how to use the Scanner class to read data from standard input and differentiate between **next()** and **nextLine()** for different input types. 88 | ## Conclusion 89 | Utilizing the Scanner class simplifies reading data from standard input. The **next()** and **nextLine()** methods are crucial for reading strings. They have distinct behaviors: **next()** reads until the next space, while **nextLine()** reads until the end of the line. 90 | 91 | We recommend using the Scanner class when tackling programming challenges, as it's one of the easiest ways to obtain values from standard input. More advanced data reading techniques will be covered in future topics. -------------------------------------------------------------------------------- /db/lessons/siud_sql.MD: -------------------------------------------------------------------------------- 1 | ### Introduction to SQLFiddle: Online SQL Practice 2 | 3 | **What is SQLFiddle?** 4 | - SQLFiddle is an online SQL compiler that allows you to write and test SQL queries without the need for installing a database system. 5 | - It supports various database systems, including SQLite, MySQL, PostgreSQL, and others. 6 | 7 | **How to Use SQLFiddle for Practice:** 8 | 1. **Access the Tool**: Visit [SQLFiddle](https://sqlfiddle.com/sqlite/online-compiler) to start practicing. 9 | 2. **Choose a Database System**: For beginners, SQLite is a good start due to its simplicity. 10 | 3. **Create Your Schema**: Use the left pane to define tables and insert data. For example: 11 | ```sql 12 | CREATE TABLE Students ( 13 | StudentID int, 14 | Name varchar(100), 15 | Age int, 16 | Grade char(1) 17 | ); 18 | 19 | INSERT INTO Students (StudentID, Name, Age, Grade) 20 | VALUES (1, 'Alice', 20, 'A'); 21 | ``` 22 | 4. **Write and Run Queries**: Use the right pane to write SQL queries and see the results. For example: 23 | ```sql 24 | SELECT * FROM Students; 25 | ``` 26 | 5. **Experiment and Learn**: Try various SQL commands and observe the outcomes. 27 | **Benefits of Using SQLFiddle:** 28 | - **No Setup Required**: It’s a web-based tool, so there’s no need to install database software. 29 | - **Instant Feedback**: Execute queries and immediately see results or errors, which is excellent for learning. 30 | - **Shareable**: You can share your SQLFiddle setup with others, making it useful for collaborative learning or troubleshooting. 31 | 32 | Now that you know how to practice SQL online with SQLFiddle, let's move on to learning the key SQL statements. 33 | 34 | ### 1. SQL Essentials 35 | **Introduction to SQL**: 36 | - SQL (Structured Query Language) is a standard language for accessing and manipulating databases. 37 | - SQL allows you to query, insert, update, and delete data, as well as create and manage database structures. 38 | 39 | ### 2. Key SQL Statements 40 | #### 2.1 SELECT Statement 41 | - **Purpose**: Used to select data from a database. 42 | - **Syntax**: 43 | ```sql 44 | SELECT column1, column2, ... 45 | FROM table_name; 46 | ``` 47 | - **Example**: Suppose we have a table `Students` with columns `StudentID`, `Name`, `Age`, and `Grade`. 48 | ```sql 49 | SELECT Name, Grade 50 | FROM Students; 51 | ``` 52 | - **Description**: This statement retrieves all records from the `Name` and `Grade` columns of the `Students` table. 53 | 54 | #### 2.2 INSERT Statement 55 | - **Purpose**: Used to insert new records into a table. 56 | - **Syntax**: 57 | ```sql 58 | INSERT INTO table_name (column1, column2, column3, ...) 59 | VALUES (value1, value2, value3, ...); 60 | ``` 61 | - **Example**: To add a new student record: 62 | ```sql 63 | INSERT INTO Students (StudentID, Name, Age, Grade) 64 | VALUES (123, 'John Doe', 20, 'A'); 65 | ``` 66 | - **Description**: This statement adds a new row to the `Students` table with the provided values. 67 | 68 | #### 2.3 UPDATE Statement 69 | - **Purpose**: Used to modify existing records in a table. 70 | - **Syntax**: 71 | ```sql 72 | UPDATE table_name 73 | SET column1 = value1, column2 = value2, ... 74 | WHERE condition; 75 | ``` 76 | - **Example**: Updating the grade of a specific student: 77 | ```sql 78 | UPDATE Students 79 | SET Grade = 'B' 80 | WHERE StudentID = 123; 81 | ``` 82 | - **Description**: This statement updates the `Grade` of the student with `StudentID` 123 to 'B'. 83 | 84 | #### 2.4 DELETE Statement 85 | - **Purpose**: Used to delete existing records from a table. 86 | - **Syntax**: 87 | ```sql 88 | DELETE FROM table_name 89 | WHERE condition; 90 | ``` 91 | - **Example**: Deleting a student record: 92 | ```sql 93 | DELETE FROM Students 94 | WHERE StudentID = 123; 95 | ``` 96 | - **Description**: This statement deletes the record of the student with `StudentID` 123 from the `Students` table. 97 | 98 | ### Recommended Resources 99 | - [SELECT](https://www.w3schools.com/sql/sql_select.asp) 100 | - [INSERT INTO](https://www.w3schools.com/sql/sql_insert.asp) 101 | - [UPDATE](https://www.w3schools.com/sql/sql_update.asp) 102 | - [DELETE](https://www.w3schools.com/sql/sql_delete.asp) 103 | -------------------------------------------------------------------------------- /JavaCore/lessons/atm_project.MD: -------------------------------------------------------------------------------- 1 | ### ATM Simulator 2 | 3 | #### Project Goals: 4 | 1. **Understanding Transactions and Security**: Mastery of handling financial transactions and data security fundamentals. 5 | 2. **Working with Interfaces and Polymorphism**: Application of interfaces and polymorphism to create a flexible and scalable architecture. 6 | 3. **Mastery of Java Basics**: Utilizing collections, exceptions, multithreading, and file systems. 7 | 8 | #### Project Description: 9 | Create a console application that simulates the operation of an ATM, allowing users to: 10 | - Check balances, withdraw and deposit cash. 11 | - Transfer money between accounts. 12 | - Change PIN codes. 13 | - Maintain a transaction log. 14 | - Handle various user scenarios and errors. 15 | 16 | #### Technical Requirements: 17 | 1. **Security**: User data encryption and secure storage of PIN codes. 18 | 2. **Transaction Handling**: Management of transactions and their sequencing. 19 | 3. **Multithreading**: Processing simultaneous requests in a multi-user environment. 20 | 21 | #### Tasks: 22 | 1. Implementation of core account and user classes. 23 | 2. Creation of interfaces and their implementations for managing accounts, user interfaces, and transaction logging. 24 | 3. Implementation of security, including data encryption and secure PIN code storage. 25 | 4. Exception handling and creation of a reliable and robust system. 26 | 5. (Optional) Development of multithreaded processing to support concurrent operations. 27 | 28 | ### Structure 29 | #### Overall Interaction Scheme: 30 | 1. **View**: Receives user input and delegates the execution of operations to the `service` layer. 31 | 2. **Service**: Contains all the application's business logic. 32 | 3. **DAO (Data Access Object)**: Interacts with the file system retrieval. 33 | 34 | #### 1. View 35 | - Responsibility: Interacting with the user, displaying menus, and obtaining user input. 36 | - Classes: 37 | - `ATMConsoleView`: Manages the entire console-based user interface. 38 | - `UserInputHandler`: Processes user input and calls the corresponding methods in the `service` layer. 39 | 40 | #### 2. Service 41 | - Responsibility: Contains all the application's business logic. 42 | - Classes: 43 | - `AccountService`: Manages account operations such as balance checking, deposits, cash withdrawals, and transfers. 44 | - `UserService`: Manages user information, including authentication and PIN code changes. 45 | - `TransactionService`: Handles and logs transactions. 46 | 47 | #### 3. DAO (Data Access Object) 48 | - Responsibility: Interacts with the data storage system (files, databases, etc.). 49 | - Classes: 50 | - `AccountDAO`: Manages the storage and retrieval of account data. 51 | - `UserDAO`: Manages the storage and retrieval of user data. 52 | - `TransactionDAO`: Manages the storage and retrieval of transaction data. 53 | 54 | #### Example Interactions: 55 | - When a user wants to check their balance: 56 | - `ATMConsoleView` receives the request and calls `AccountService`. 57 | - `AccountService` requests account data through `AccountDAO` and returns the information to `ATMConsoleView`. 58 | - During a transaction: 59 | - `ATMConsoleView` forwards the request to `TransactionService`. 60 | - `TransactionService` processes the transaction and uses `TransactionDAO` to store transaction details. 61 | 62 | #### Interfaces and Their Implementations: 63 | 1. **Account Management Interface (`AccountManager`)**: 64 | - Methods: `checkBalance`, `deposit`, `withdraw`, `transferFunds`, `changePin`. 65 | - Implementations: `SimpleAccountManager` for basic functionality and `SecureAccountManager` with additional security measures. 66 | 67 | 2. **User Interaction Interface (`UserInterface`)**: 68 | - Methods: `displayMainMenu`, `handleUserActions`. 69 | - Implementations: `ConsoleUserInterface` and optionally, `GraphicalUserInterface` as an extension. 70 | 71 | 3. **Transaction Logging Interface (`TransactionLogger`)**: 72 | - Methods: `logTransaction`. 73 | - Implementations: `SimpleTransactionLogger` for file-based logging or `DatabaseTransactionLogger` for database interaction. 74 | 75 | #### Additional Notes: 76 | - **Security and Validation**: All necessary validation and security measures (e.g., PIN code verification) are performed in the `service` layer. 77 | - **Separation of Responsibilities**: Each layer has well-defined responsibilities, making code management and testing easier. 78 | -------------------------------------------------------------------------------- /db/lessons/sql_jdbc.MD: -------------------------------------------------------------------------------- 1 | Executing SQL queries through Java using JDBC involves several steps that allow a Java application to communicate with a database. This process includes establishing a connection with the database, creating a statement, executing SQL queries, and processing the results. Here's a detailed breakdown of each step: 2 | 3 | ### 1. Establishing a Database Connection 4 | To execute SQL queries, the first step is to establish a connection with the database. This requires loading the appropriate JDBC driver and using `DriverManager.getConnection()` with the appropriate database URL, username, and password: 5 | 6 | ```java 7 | Connection connection = DriverManager.getConnection("jdbc:subprotocol:subname", "user", "password"); 8 | ``` 9 | Replace `"jdbc:subprotocol:subname"`, `"user"`, and `"password"` with your actual database connection details. 10 | 11 | ### 2. Creating a Statement 12 | Once a connection is established, you can create a `Statement` or `PreparedStatement` object to send SQL commands to the database. A `Statement` is suitable for simple, static SQL queries, while a `PreparedStatement` is preferred for queries that are executed multiple times or require parameterization for security and efficiency. 13 | 14 | - **Statement**: 15 | ```java 16 | Statement statement = connection.createStatement(); 17 | ``` 18 | 19 | - **PreparedStatement**: 20 | ```java 21 | PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM tableName WHERE column = ?"); 22 | preparedStatement.setString(1, "value"); 23 | ``` 24 | 25 | ### 3. Executing SQL Queries 26 | With a `Statement` or `PreparedStatement` object, you can execute SQL queries or updates on the database. 27 | 28 | - **Executing a query** (for retrieving data): 29 | ```java 30 | ResultSet resultSet = statement.executeQuery("SELECT * FROM tableName"); 31 | ``` 32 | 33 | - **Executing an update** (for INSERT, UPDATE, DELETE, etc.): 34 | ```java 35 | int rowsAffected = statement.executeUpdate("UPDATE tableName SET column = 'value' WHERE condition"); 36 | ``` 37 | 38 | ### 4. Processing the Results 39 | After executing a query, the results can be processed. For a query that returns data, a `ResultSet` object is used to iterate through the results: 40 | 41 | ```java 42 | while (resultSet.next()) { 43 | String data = resultSet.getString("columnName"); 44 | // Process each row 45 | } 46 | ``` 47 | 48 | ### 5. Closing Resources 49 | It's critical to close all JDBC resources after use to prevent resource leaks. This includes the `ResultSet`, `Statement`/`PreparedStatement`, and `Connection` objects. Ideally, use a try-with-resources statement or ensure they are closed in a `finally` block: 50 | 51 | ```java 52 | if (resultSet != null) resultSet.close(); 53 | if (statement != null) statement.close(); 54 | if (connection != null) connection.close(); 55 | ``` 56 | 57 | Or using try-with-resources: 58 | 59 | ```java 60 | try (Connection connection = DriverManager.getConnection(url, user, password); 61 | Statement statement = connection.createStatement(); 62 | ResultSet resultSet = statement.executeQuery("SELECT * FROM tableName")) { 63 | while (resultSet.next()) { 64 | // Process results 65 | } 66 | } // AutoCloseable resources are automatically closed here 67 | ``` 68 | 69 | ### Example: Complete JDBC Query Execution 70 | Here's a full example combining the steps above: 71 | 72 | ```java 73 | public class JdbcQueryExecutionExample { 74 | public static void main(String[] args) { 75 | String url = "jdbc:sqlite:path_to_your_database.db"; 76 | String user = "username"; 77 | String password = "password"; 78 | 79 | try (Connection connection = DriverManager.getConnection(url, user, password); 80 | Statement statement = connection.createStatement(); 81 | ResultSet resultSet = statement.executeQuery("SELECT * FROM tableName")) { 82 | 83 | while (resultSet.next()) { 84 | System.out.println(resultSet.getString("columnName")); 85 | // Process each row 86 | } 87 | } catch (SQLException e) { 88 | e.printStackTrace(); 89 | } 90 | } 91 | } 92 | ``` 93 | 94 | This example demonstrates connecting to a MySQL database, executing a SELECT query, processing the results, and properly closing resources. 95 | 96 | ### Best Practices 97 | - **Use `PreparedStatement`** for parameterized queries to prevent SQL injection. 98 | - **Manage transactions** explicitly for operations that involve multiple steps or updates for data consistency. 99 | - **Close resources** promptly to free up database connections and other resources. 100 | - **Handle exceptions** gracefully to manage errors such as connection failures or query issues. 101 | -------------------------------------------------------------------------------- /db/lessons/jdbc.MD: -------------------------------------------------------------------------------- 1 | ### Introduction to JDBC 2 | JDBC is an API in Java for connecting and executing queries with databases. It provides a standard method for Java programs to interact with databases, ranging from relational databases like MySQL, PostgreSQL, and Oracle to NoSQL databases such as MongoDB and Cassandra, though JDBC is predominantly used with relational databases. The primary advantage of JDBC is its ability to execute SQL statements across different databases, making Java applications portable across platforms and database systems. 3 | 4 | ### JDBC Architecture 5 | The JDBC API supports both two-tier and three-tier processing models for database access but is commonly used in a two-tier model where Java applications directly communicate with the database. In a three-tier model, commands are sent to a "middle tier," allowing various adjustments before the command is sent to the database. 6 | 7 | The JDBC architecture comprises several key components: 8 | 1. **JDBC API**: Provides the application-to-JDBC Manager connection. 9 | 2. **JDBC Driver Manager**: Responsible for determining the database-specific drivers to initiate connections. 10 | 3. **JDBC Test Suite**: Helps to verify a JDBC driver's compatibility. 11 | 4. **JDBC-ODBC Bridge**: Provides JDBC API access via ODBC drivers. Note that this is less commonly used now, especially with JDBC 4.0 and newer versions eliminating the need for an ODBC bridge. 12 | 5. **JDBC Drivers**: These are types of drivers that vary based on how they work. Common types include: 13 | - Type 1: JDBC-ODBC bridge 14 | - Type 2: Native-API driver 15 | - Type 3: Network Protocol driver 16 | - Type 4: Thin driver (pure Java driver for database middleware) 17 | 18 | ### Establishing a Connection 19 | To connect to a database using JDBC, you need to: 20 | 1. **Load the JDBC driver**: This step involves initializing the driver so you can open a communication channel with the database. 21 | 2. **Establish a connection**: Use the `DriverManager` to create a connection to the database. 22 | 3. **Create a statement**: Once connected, you can create a `Statement`, `PreparedStatement`, or `CallableStatement` to send SQL commands. 23 | 4. **Execute queries**: Execute SQL queries using the statement object. 24 | 5. **Process results**: Process the results received from the database in response to your query. 25 | 6. **Close connections**: It's vital to close database connections to free up resources. 26 | 27 | ### Example: Connecting to a Database 28 | Here's a simple example of connecting to a MySQL database and executing a query: 29 | 30 | ```java 31 | import java.sql.Connection; 32 | import java.sql.DriverManager; 33 | import java.sql.ResultSet; 34 | import java.sql.Statement; 35 | 36 | public class JdbcExample { 37 | public static void main(String[] args) { 38 | try { 39 | // Step 1: Load the JDBC driver 40 | Class.forName("org.sqlite.JDBC"); 41 | 42 | // Step 2: Establish a connection 43 | Connection con = DriverManager.getConnection("jdbc:sqlite:path_to_your_database.db"); 44 | 45 | // Step 3: Create a statement 46 | Statement stmt = con.createStatement(); 47 | 48 | // Step 4: Execute a query 49 | ResultSet rs = stmt.executeQuery("select * from mytable"); 50 | 51 | // Step 5: Process the results 52 | while (rs.next()) 53 | System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3)); 54 | 55 | // Step 6: Close connections 56 | rs.close(); 57 | stmt.close(); 58 | con.close(); 59 | } catch (Exception e) { 60 | System.out.println(e); 61 | } 62 | } 63 | } 64 | ``` 65 | This example demonstrates the basic steps to connect to a MySQL database, execute a `SELECT` query, and iterate through the results. Replace `"mydb"`, `"user"`, and `"password"` with your actual database name, username, and password. 66 | 67 | ### Tips for Effective JDBC Usage 68 | - **Use `PreparedStatement`**: For executing SQL queries multiple times, `PreparedStatement` improves performance and security. 69 | - **Transaction Management**: Utilize JDBC's support for transaction management to ensure data integrity. 70 | - **Resource Management**: Always close JDBC resources (`ResultSet`, `Statement`, `Connection`) to prevent resource leaks. 71 | - **Error Handling**: Implement comprehensive error handling to manage SQL exceptions. 72 | 73 | 74 | ### Recommended Resources 75 | - [Lesson: JDBC Basics](https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) 76 | - [JDBC Examples](https://www.tutorialspoint.com/jdbc/index.htm) 77 | - [JDBC Tutorial](https://www.geeksforgeeks.org/jdbc-tutorial) 78 | - [Introduction to JDBC](https://www.baeldung.com/java-jdbc) 79 | -------------------------------------------------------------------------------- /db/lessons/advance_jdbc_intro.MD: -------------------------------------------------------------------------------- 1 | Advanced JDBC techniques and optimizations can significantly enhance the performance and scalability of Java 2 | applications that interact with databases. JDBC, being a low-level API, offers various ways to fine-tune database 3 | interactions. Here's an overview of some advanced techniques and best practices for using JDBC effectively: 4 | 5 | ### 1. Batch Processing 6 | Batch processing allows you to execute multiple SQL statements in a single batch, reducing the number of round trips 7 | between the application and the database. This is particularly useful for inserting, updating, or deleting multiple 8 | records simultaneously. 9 | 10 | ```java 11 | try (Connection conn = DBConnection.getConnection(); 12 | PreparedStatement pstmt = conn.prepareStatement("INSERT INTO users (name, email) VALUES (?, ?)")) { 13 | for (User user : users) { 14 | pstmt.setString(1, user.getName()); 15 | pstmt.setString(2, user.getEmail()); 16 | pstmt.addBatch(); 17 | } 18 | pstmt.executeBatch(); 19 | } catch (SQLException e) { 20 | e.printStackTrace(); 21 | } 22 | ``` 23 | 24 | ### 2. Connection Pooling 25 | Connection pooling is a technique used to minimize the overhead of establishing connections to the database. 26 | Instead of opening and closing a connection for each database operation, connections are reused from a pool of 27 | available connections. Libraries like HikariCP, Apache Commons DBCP, and C3P0 provide connection pooling capabilities. 28 | 29 | ```java 30 | HikariConfig config = new HikariConfig(); 31 | config.setJdbcUrl("jdbc:mysql://localhost:3306/mydatabase"); 32 | config.setUsername("username"); 33 | config.setPassword("password"); 34 | config.addDataSourceProperty("cachePrepStmts", "true"); 35 | config.addDataSourceProperty("prepStmtCacheSize", "250"); 36 | config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); 37 | 38 | HikariDataSource ds = new HikariDataSource(config); 39 | ``` 40 | 41 | ### 3. Prepared Statements and Parameterized Queries 42 | Prepared statements not only help in preventing SQL injection attacks but also improve performance by pre-compiling 43 | SQL statements. When the same statement is executed multiple times with different parameters, using a prepared 44 | statement reduces processing time. 45 | 46 | ```java 47 | String sql = "SELECT * FROM users WHERE email = ?"; 48 | try (Connection conn = DBConnection.getConnection(); 49 | PreparedStatement pstmt = conn.prepareStatement(sql)) { 50 | pstmt.setString(1, email); 51 | try (ResultSet rs = pstmt.executeQuery()) { 52 | while (rs.next()) { 53 | // Process the result 54 | } 55 | } 56 | } catch (SQLException e) { 57 | e.printStackTrace(); 58 | } 59 | ``` 60 | 61 | ### 4. Statement Caching 62 | Many JDBC drivers and databases support statement caching, which reuses database cursors and execution plans for repeated SQL statements. This can significantly reduce the execution time for repeated queries. Statement caching can be configured at the datasource level in connection pool settings or enabled in the JDBC URL or connection properties. 63 | 64 | ### 5. Fetch Size 65 | The fetch size determines the number of rows returned in each network round trip. Adjusting the fetch size can improve the performance of reading large result sets by reducing the number of network round trips. 66 | 67 | ```java 68 | PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM large_table"); 69 | pstmt.setFetchSize(500); 70 | ResultSet rs = pstmt.executeQuery(); 71 | ``` 72 | 73 | ### 6. Transaction Management 74 | Proper transaction management ensures data integrity and can improve performance by reducing the overhead of 75 | transaction commits. Batch operations, when combined with transactions, can significantly enhance performance. 76 | 77 | ```java 78 | try (Connection conn = DBConnection.getConnection()) { 79 | conn.setAutoCommit(false); 80 | // Perform batch operations 81 | conn.commit(); 82 | } catch (SQLException e) { 83 | e.printStackTrace(); 84 | } 85 | ``` 86 | 87 | ### 7. Use of Specific Database Features 88 | Databases often offer unique features and extensions that can improve performance, such as custom functions, stored procedures, or advanced indexing techniques. Leveraging these features through JDBC can provide significant performance benefits. 89 | 90 | ### Conclusion 91 | By employing these advanced JDBC techniques and optimizations, developers can build more efficient, faster, and 92 | scalable Java applications that interact with databases. It's important to measure and monitor the performance 93 | impact of these optimizations to ensure they provide the desired benefits in your specific application context. 94 | 95 | ### Recommended Resources 96 | - [Introduction to HikariCP](https://www.baeldung.com/hikaricp) 97 | - [HikariCP](https://github.com/brettwooldridge/HikariCP) -------------------------------------------------------------------------------- /JavaCore/lessons/final_blocks.MD: -------------------------------------------------------------------------------- 1 | ## Java Basics: `final`, Code Blocks, and Variable Scope 2 | 3 | ### 1. Constants with `final` 4 | 5 | #### What is `final`? 6 | In Java, the `final` keyword is used to declare that something cannot be changed. When applied to variables, it means the variable becomes a constant, and its value cannot be modified once assigned. 7 | 8 | #### Code Example: 9 | ```java 10 | public class FinalExample { 11 | public static final double PI = 3.141592653589793; 12 | 13 | public static void main(String[] args) { 14 | System.out.println("Value of PI: " + PI); 15 | // Uncommenting the next line will cause a compile error 16 | // PI = 3.14; 17 | } 18 | } 19 | ``` 20 | 21 | #### Deep Dive: 22 | - A `final` variable must be initialized when it's declared if it's an instance or static variable. 23 | - Local `final` variables (inside methods) can be assigned later but only once. 24 | - The `final` keyword can also be used with classes to prevent inheritance and with methods to prevent overriding. 25 | 26 | ### 2. Code Blocks and Variable Scope 27 | 28 | #### What is a Code Block? 29 | In Java, a code block is a section of code enclosed by curly braces `{}`. It can define the body of a method, constructor, or a local block within methods. 30 | 31 | #### What is Variable Scope? 32 | The scope of a variable refers to the region of the code where the variable can be accessed or modified. 33 | 34 | #### Code Example: 35 | ```java 36 | public class ScopeExample { 37 | private int classLevelVariable = 5; 38 | 39 | public void demonstrateScope() { 40 | int methodLevelVariable = 10; 41 | System.out.println("Class Level: " + classLevelVariable); 42 | System.out.println("Method Level: " + methodLevelVariable); 43 | 44 | { 45 | int blockLevelVariable = 15; 46 | System.out.println("Block Level: " + blockLevelVariable); 47 | } 48 | 49 | // Uncommenting the next line will cause a compile error 50 | // System.out.println(blockLevelVariable); 51 | } 52 | 53 | public static void main(String[] args) { 54 | ScopeExample example = new ScopeExample(); 55 | example.demonstrateScope(); 56 | } 57 | } 58 | ``` 59 | 60 | #### Deep Dive in future: 61 | - **Class-Level Scope (Instance Variables):** Variables declared inside a class but outside any method. They can be accessed by any method within the class. 62 | - **Method-Level Scope (Local Variables):** Variables declared within a method. They're accessible only within that method. 63 | - **Block-Level Scope:** Variables declared inside a specific block of code. Their scope is limited to that block. 64 | 65 | ### Recommended Resources 66 | - [Final keyword](https://www.geeksforgeeks.org/final-keyword-in-java/) 67 | - [Final keyword](https://www.javatpoint.com/final-keyword) 68 | - [Java final keyword](https://www.w3schools.com/java/ref_keyword_final.asp) 69 | - [Java variable scope](https://coderslegacy.com/java/java-variable-scope/) 70 | - [Java scope](https://www.w3schools.com/java/java_scope.asp) 71 | 72 | ## Tasks 73 |
74 | Task 1 75 |
 76 | 
 77 | # **Final Value Holder**
 78 | ## **Description:**
 79 | Write a Java program that stores a `final` value for the speed of light (299,792,458 meters per second). The program should display this value when run.
 80 | ### _Input:_
 81 | None (since the value is a constant).
 82 | ### _Output:_
 83 | Speed of Light: 299,792,458 m/s
 84 | 
 85 | 
86 |
87 | 88 | --- 89 | 90 |
91 | Task 2 92 |
 93 | 
 94 | # **Block Scope Identifier**
 95 | ## **Description:**
 96 | Write a Java program that has a main method with a variable called `outsideBlock`. Inside the main method, define a code block with a variable named `insideBlock`. Display both variables before and after the code block.
 97 | ### _Input:_
 98 | None (you're simply initializing and displaying variables).
 99 | ### _Output:_
100 | Outside Variable (before block): [value]
101 | Inside Block Variable: [value]
102 | Outside Variable (after block): [value]
103 | 
104 | 
105 |
106 | 107 | --- 108 | 109 |
110 | Task 3 111 |
112 | 
113 | # **Temperature Converter**
114 | ## **Description:**
115 | Write a Java program that converts a given temperature in Fahrenheit to Celsius. Use a `final` variable to store the conversion factor.
116 | ### _Input:_
117 | 98.6 (Fahrenheit value)
118 | ### _Output:_
119 | Body temperature in Celsius: 37°C
120 | 
121 | 
122 |
123 | -------------------------------------------------------------------------------- /spring/projects/project_1.MD: -------------------------------------------------------------------------------- 1 | ### Title: Automated Teller Machine (ATM) System 2 | ### Description: 3 | The objective of this project is to develop a secure and efficient Automated Teller Machine (ATM) System using 4 | Java and Spring technologies. The system will simulate common ATM functionalities such as account access, balance 5 | inquiries, deposits, withdrawals, and transfers between accounts. The project should demonstrate the capability to 6 | handle user authentication, session management, and secure transaction processing. 7 | 8 | #### Business Case: 9 | With banking customers increasingly relying on electronic banking services for daily transactions, ATMs play a critical 10 | role in the banking ecosystem. A robust ATM system enhances customer satisfaction by providing quick and secure access 11 | to banking services outside of traditional banking hours. This project will allow students to understand and implement 12 | essential features of banking systems, emphasizing security, data integrity, and user interaction. 13 | 14 | #### Suggested Architecture & Database Description: 15 | - **Database Schema:** 16 | - **Users**: `id`, `account_number`, `pin`, `balance` 17 | - **Transactions**: `id`, `type`, `amount`, `date`, `account_number` 18 | - **Backend Framework**: Spring Boot 19 | - **Security**: Spring Security for authentication and securing transaction endpoints 20 | - **Data Handling**: Spring Data JPA for transaction and user management 21 | - **API**: RESTful services using Spring Web for transaction processing 22 | 23 | ### User Stories: 24 | 1. **As a bank customer, I want to:** 25 | - Insert my card (simulate by entering an account number and PIN). 26 | - View my current account balance. 27 | - Withdraw cash from my account. 28 | - Deposit money into my account. 29 | - Transfer funds to another account. 30 | - Log out securely from the ATM. 31 | 2. **As a bank administrator, I want to:** 32 | - Monitor and log all ATM transactions. 33 | - Manage ATM system issues such as replenishing cash or addressing transaction errors. 34 | - Update account information and PINs securely. 35 | 3. **As a system, I need to:** 36 | - Validate user credentials. 37 | - Handle sessions to ensure that customers’ operations are secure and personal information is protected. 38 | - Process transactions accurately and securely, updating account balances in real-time. 39 | - Provide timely feedback to the user about the status of their transactions. 40 | 41 | ### API Requirements: 42 | - **Authentication and Session Management:** 43 | - `POST /auth/login`: Authenticate user and create a session. 44 | - `POST /auth/logout`: Terminate the session. 45 | - **Account Operations:** 46 | - `GET /accounts/balance`: Check the current balance. 47 | - `POST /accounts/deposit`: Deposit an amount to the user's account. 48 | - `POST /accounts/withdraw`: Withdraw an amount from the user's account. 49 | - `POST /accounts/transfer`: Transfer amount to another account. 50 | - **Admin Functions:** 51 | - `GET /admin/transactions`: View all transactions processed by the ATM. 52 | 53 | ### Acceptance Criteria: 54 | 1. **Spring Boot Application Setup:** 55 | - Properly configure and initialize a Spring Boot application using Gradle as the build tool. Include dependencies for Spring Boot, Spring Data JPA, Spring Security, and Spring Web. 56 | 2. **Database and Entity Configuration:** 57 | - Define JPA entities corresponding to the database schema for Users and Transactions. 58 | - Set up a PostgreSQL database and configure Spring Data JPA to interact with it. 59 | - Create repositories for each entity with necessary custom methods to support CRUD operations beyond the basic functionalities provided by Spring Data. 60 | 3. **User Authentication:** 61 | - Implement a secure login system that authenticates users by account number and PIN. 62 | - Ensure that all account transactions require user authentication. 63 | - Sessions must expire automatically after a period of inactivity or explicitly upon user logout. 64 | 4. **Transaction Processing:** 65 | - Develop endpoints to handle deposit, withdrawal, and balance inquiries. These must update and fetch account balances accurately. 66 | - Implement a transfer service that allows users to transfer funds between accounts securely and update both accounts' balances accordingly. 67 | - All transactional operations must handle errors gracefully and return meaningful error messages to the user. 68 | 5. **Admin Functions:** 69 | - Provide endpoints for administrators to view all transactions. 70 | - Implement functionality for administrators to intervene in case of transaction discrepancies or system errors. 71 | 6. **Testing and Documentation:** 72 | - Write integration tests for all critical functionalities such as login, withdrawal, deposit, and transfer. 73 | - Document the API using Swagger or Spring Rest Docs, including all request and response models, expected error messages, and status codes. 74 | 75 | -------------------------------------------------------------------------------- /db/projects/atm_project.MD: -------------------------------------------------------------------------------- 1 | 2 | ### Introduction to the Automated Teller Machine (ATM) Management System Project 3 | The banking sector has always been at the forefront of adopting technological innovations to enhance customer 4 | service and operational efficiency. Among these innovations, Automated Teller Machines (ATMs) have revolutionized 5 | the way banking services are delivered to customers, providing convenient, round-the-clock access to financial 6 | transactions. The Automated Teller Machine (ATM) Management System project aims to delve into the technological 7 | underpinnings of ATM operations, focusing on the integration of software development practices with banking services. 8 | 9 | This educational project is designed to bridge theoretical knowledge with practical application, allowing students 10 | to develop a simulated ATM management system. Through this project, students will apply their Java programming 11 | expertise and database management skills to create a system that simulates real-world financial transactions and 12 | ATM operations. 13 | 14 | #### The Essence of the ATM Management System Project 15 | The ATM Management System encompasses a wide range of banking operations, including account management, 16 | cash withdrawal, deposits, balance inquiries, and fund transfers. This system is crucial for ensuring secure 17 | and efficient transaction processing, managing customer accounts, and maintaining cash inventories within ATMs. 18 | The project provides a simulated environment for students to explore the complexities of financial software development. 19 | 20 | #### Project Goals 21 | The primary goal of the ATM Management System project is to develop a software solution that simulates the core 22 | functionalities of an ATM, ensuring security, reliability, and user-friendliness. Students will navigate through 23 | the complete software development lifecycle, enhancing their problem-solving, software design, and development 24 | skills, crucial for a career in software engineering within the financial sector. 25 | 26 | #### Learning Through Doing 27 | Engaging with the ATM Management System project, students will gain hands-on experience in implementing secure 28 | transactions, managing databases for account information, and integrating Java applications with database systems 29 | using JDBC. This project represents a unique opportunity to understand the challenges and solutions in financial 30 | software development. 31 | 32 | ### Functional Requirements for the Automated Teller Machine (ATM) Management System 33 | 1. **Account Management** 34 | - **FR1.1:** Secure login and authentication for ATM access using a card number and PIN. 35 | - **FR1.2:** Enable users to view account balances, recent transactions, and account details. 36 | - **FR1.3:** Support for changing PIN and updating personal information. 37 | 2. **Cash Withdrawal and Deposits** 38 | - **FR2.1:** Allow users to withdraw cash, automatically updating the account balance and cash inventory in the ATM. 39 | - **FR2.2:** Enable cash and check deposits, crediting the account accordingly and updating the ATM's cash inventory. 40 | 3. **Balance Inquiry and Fund Transfer** 41 | - **FR3.1:** Provide balance inquiry services, displaying the current balance and pending transactions. 42 | - **FR3.2:** Facilitate fund transfers between user accounts, requiring recipient account validation. 43 | 4. **ATM Maintenance and Cash Management** 44 | - **FR4.1:** Monitor and report the cash inventory levels in the ATM, alerting bank personnel for replenishment. 45 | - **FR4.2:** Log maintenance activities and system errors for administrative review. 46 | 47 | ### Tips for Application Architecture (View-Service-DAO) and Database Design 48 | - **Layered Architecture:** Emphasize the critical importance of security and transactional integrity in the financial domain, applying the View-Service-DAO model to separate user interactions, business logic, and data access. 49 | - **Optimal Number of Tables:** A minimal set might include tables for User Accounts, Transactions, ATM Cash Inventory, and System Logs, ensuring comprehensive coverage of ATM operations while maintaining simplicity. 50 | - **Security Considerations:** Highlight the importance of encryption for sensitive data, secure authentication mechanisms, and rigorous validation to prevent unauthorized access and ensure data protection. 51 | 52 | ### General Advice 53 | - **Security First:** Given the sensitive nature of banking operations, stress the paramount importance of security in every aspect of the system, from database transactions to user interface design. 54 | - **Real-World Simulation:** Encourage students to consider real-world scenarios, such as network failures, multi-currency transactions, and regulatory compliance, to enhance the realism and utility of their projects. 55 | - **Comprehensive Testing:** Advocate for thorough testing strategies, including unit tests, integration tests, and security audits, to ensure the reliability and security of the ATM Management System. 56 | -------------------------------------------------------------------------------- /spring/projects/project_2.MD: -------------------------------------------------------------------------------- 1 | ### Telemedicine System 2 | ### Description: 3 | The objective of this project is to develop a Telemedicine System using Java and Spring technologies. 4 | The system will facilitate online consultations, manage patient health records, handle prescription management, 5 | and provide a platform for doctors and patients to communicate. 6 | 7 | #### Business Case: 8 | Telemedicine is transforming the healthcare industry by making healthcare more accessible and efficient. 9 | This project will allow developers to understand and implement essential features of telemedicine systems, 10 | emphasizing security, data integrity, and user interaction. 11 | 12 | #### Suggested Architecture & Database Description: 13 | - **Database Schema:** 14 | - **Patients**: `id`, `name`, `email`, `phone`, `medical_history` 15 | - **Doctors**: `id`, `name`, `specialization`, `schedule` 16 | - **Appointments**: `id`, `patient_id`, `doctor_id`, `date`, `time`, `status` 17 | - **Prescriptions**: `id`, `patient_id`, `doctor_id`, `medication`, `dosage`, `duration` 18 | - **Backend Framework**: Spring Boot 19 | - **Security**: Spring Security for authentication and securing endpoints 20 | - **Data Handling**: Spring Data JPA for data management 21 | - **API**: RESTful services using Spring Web for data processing 22 | 23 | ### User Stories: 24 | 1. **As a patient, I want to:** 25 | - Register and log in to the system. 26 | - View available doctors and their schedules. 27 | - Book an online consultation. 28 | - Communicate with the doctor during the consultation. 29 | - Receive prescriptions from the doctor. 30 | - View my medical records and prescriptions. 31 | 2. **As a doctor, I want to:** 32 | - Log in to the system. 33 | - View my schedule. 34 | - Conduct online consultations with patients. 35 | - View patient medical history before a consultation. 36 | - Write prescriptions during or after a consultation. 37 | - Update patient medical records after a consultation. 38 | 3. **As a system, I need to:** 39 | - Validate user credentials. 40 | - Handle sessions to ensure that users' operations are secure and personal information is protected. 41 | - Process appointments accurately and securely, updating schedules in real-time. 42 | - Provide timely feedback to the user about the status of their appointments and prescriptions. 43 | 44 | ### API Requirements: 45 | - **Authentication and Session Management:** 46 | - `POST /auth/register`: Register a new user. 47 | - `POST /auth/login`: Authenticate user and create a session. 48 | - `POST /auth/logout`: Terminate the session. 49 | - **Appointment Operations:** 50 | - `GET /doctors`: List all doctors and their schedules. 51 | - `POST /appointments`: Book a new online consultation. 52 | - `PUT /appointments/{id}`: Reschedule an existing consultation. 53 | - `DELETE /appointments/{id}`: Cancel a consultation. 54 | - `GET /appointments`: View consultation history. 55 | - **Medical Records and Prescriptions:** 56 | - `GET /patients/{id}/records`: View patient's medical records. 57 | - `PUT /patients/{id}/records`: Update patient's medical records. 58 | - `GET /patients/{id}/prescriptions`: View patient's prescriptions. 59 | - `POST /patients/{id}/prescriptions`: Create a new prescription. 60 | 61 | ### Acceptance Criteria: 62 | 1. **Spring Boot Application Setup:** 63 | - Properly configure and initialize a Spring Boot application using Gradle as the build tool. Include dependencies for Spring Boot, Spring Data JPA, Spring Security, and Spring Web. 64 | 2. **Database and Entity Configuration:** 65 | - Define JPA entities corresponding to the database schema for Patients, Doctors, Appointments, and Prescriptions. 66 | - Set up a PostgreSQL database and configure Spring Data JPA to interact with it. 67 | - Create repositories for each entity with necessary custom methods to support CRUD operations beyond the basic functionalities provided by Spring Data. 68 | 3. **User Authentication:** 69 | - Implement a secure login system that authenticates users by email and password. 70 | - Ensure that all operations require user authentication. 71 | - Sessions must expire automatically after a period of inactivity or explicitly upon user logout. 72 | 4. **Appointment and Prescription Processing:** 73 | - Develop endpoints to handle booking, rescheduling, and cancelling consultations. These must update and fetch schedules accurately. 74 | - Implement a system that allows doctors to view and update patient medical records and write prescriptions. 75 | - All operations must handle errors gracefully and return meaningful error messages to the user. 76 | 5. **API Documentation:** 77 | - Set up Swagger for API documentation. 78 | - Document all API endpoints with Swagger, including all request and response models, expected error messages, and status codes. 79 | - Ensure that the Swagger UI is accessible and correctly displays all API endpoints. 80 | 6. **Testing:** 81 | - Write integration tests for all critical functionalities such as login, booking, rescheduling, cancelling consultations, and managing prescriptions. -------------------------------------------------------------------------------- /db/lessons/transactions.MD: -------------------------------------------------------------------------------- 1 | Managing database transactions in Java with JDBC is a critical aspect of building reliable and consistent database applications. Transactions ensure that a series of SQL operations are executed atomically, meaning either all operations succeed or none do, thereby maintaining data integrity. Here's an overview of how to manage database transactions using JDBC. 2 | 3 | ### Understanding Transactions 4 | A transaction is a sequence of one or more SQL statements that are executed as a single unit of work. The primary properties of transactions are often summarized by the acronym ACID, which stands for Atomicity, Consistency, Isolation, and Durability: 5 | 6 | - **Atomicity**: Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted. 7 | - **Consistency**: Ensures that the database properly changes states upon a successfully committed transaction. 8 | - **Isolation**: Ensures that transactions are securely and independently processed at the same time without interference. 9 | - **Durability**: Ensures that the result or effect of a committed transaction is permanently stored in the database. 10 | 11 | ### Enabling Transactions in JDBC 12 | By default, a JDBC connection operates in auto-commit mode, meaning each SQL statement is treated as a transaction and is automatically committed right after it is executed. To manage transactions manually, you must disable auto-commit mode and control the transaction flow using commit and rollback operations. Here's how you can do it: 13 | 14 | #### 1. Disable Auto-Commit Mode 15 | Upon establishing a connection, disable the auto-commit mode: 16 | 17 | ```java 18 | connection.setAutoCommit(false); 19 | ``` 20 | 21 | #### 2. Execute SQL Statements 22 | Execute your SQL statements using `Statement` or `PreparedStatement` objects. These could be SELECT, INSERT, UPDATE, or DELETE operations. 23 | 24 | ```java 25 | try { 26 | // Example of executing a SQL statement 27 | Statement statement = connection.createStatement(); 28 | String updateSql = "UPDATE accounts SET balance = balance - 100 WHERE account_id = 1"; 29 | statement.executeUpdate(updateSql); 30 | 31 | // You can execute more statements here as part of the transaction 32 | 33 | // If all operations are successful, commit the transaction 34 | connection.commit(); 35 | } catch (SQLException e) { 36 | // If there is any error, rollback the transaction 37 | try { 38 | if (connection != null) connection.rollback(); 39 | } catch (SQLException ex) { 40 | ex.printStackTrace(); 41 | } 42 | e.printStackTrace(); 43 | } 44 | ``` 45 | 46 | #### 3. Commit the Transaction 47 | If all the SQL operations execute successfully, commit the transaction to make all changes permanent: 48 | 49 | ```java 50 | connection.commit(); 51 | ``` 52 | 53 | #### 4. Rollback on Error 54 | If an error occurs during any of the SQL operations, rollback the transaction to undo all changes made since the transaction began: 55 | 56 | ```java 57 | connection.rollback(); 58 | ``` 59 | 60 | #### 5. Re-enable Auto-Commit Mode (Optional) 61 | After completing the transaction, you can re-enable auto-commit mode if needed: 62 | 63 | ```java 64 | connection.setAutoCommit(true); 65 | ``` 66 | 67 | ### Handling Transactions 68 | Proper error handling is crucial when managing transactions. Use try-catch blocks to catch `SQLExceptions`, and ensure that rollback is called in the catch block if any operation within the transaction fails. This prevents partial updates to the database that could lead to data inconsistency. 69 | 70 | ### Best Practices 71 | - **Use `try-with-resources`** to ensure that resources like `Connection`, `Statement`, and `ResultSet` objects are closed properly. 72 | - **Test transactions** thoroughly under various scenarios to ensure data integrity is maintained. 73 | - **Be mindful of database locks** that might occur during transactions, as they can impact performance and concurrency. Optimize transaction logic to minimize lock contention. 74 | 75 | ### Example: Complete Transaction Management 76 | Here's a complete example that demonstrates managing a simple transaction: 77 | 78 | ```java 79 | String url = "jdbc:sqlite:path_to_your_database.db"; 80 | String user = "myuser"; 81 | String password = "mypassword"; 82 | 83 | try (Connection connection = DriverManager.getConnection(url, user, password)) { 84 | // Disable auto-commit mode 85 | connection.setAutoCommit(false); 86 | 87 | try { 88 | // Execute SQL operations 89 | // ... 90 | 91 | // Commit the transaction 92 | connection.commit(); 93 | } catch (SQLException e) { 94 | // Attempt to rollback the transaction if something goes wrong 95 | try { 96 | connection.rollback(); 97 | } catch (SQLException ex) { 98 | ex.printStackTrace(); 99 | } 100 | e.printStackTrace(); 101 | } 102 | } catch (SQLException e) { 103 | e.printStackTrace(); 104 | } 105 | ``` 106 | 107 | This example demonstrates establishing a connection, disabling auto-commit, executing SQL operations, handling exceptions, committing the transaction, or rolling it back in case of errors, and finally ensuring that resources are properly closed. 108 | -------------------------------------------------------------------------------- /db/lessons/table_keys.MD: -------------------------------------------------------------------------------- 1 | ### Understanding Tables, Keys, and Relationships in a Medical System 2 | #### 1. Database Tables in a Medical System 3 | - **Definition & Example**: Tables in a medical database might represent entities like `Patients`, `Doctors`, and `Appointments`. Here's an example of creating a `Patients` table: 4 | 5 | ```sql 6 | CREATE TABLE Patients ( 7 | PatientID int PRIMARY KEY, 8 | Name varchar(255), 9 | DateOfBirth date, 10 | Gender varchar(50) 11 | ); 12 | ``` 13 | 14 | #### 2. Keys in a Medical Database 15 | - **Primary Key Example**: `PatientID` in the `Patients` table uniquely identifies each patient. 16 | 17 | ```sql 18 | ALTER TABLE Patients 19 | ADD PRIMARY KEY (PatientID); 20 | ``` 21 | 22 | - **Foreign Key Example**: In an `Appointments` table, `DoctorID` and `PatientID` might be foreign keys. 23 | 24 | ```sql 25 | CREATE TABLE Doctors ( 26 | DoctorID int PRIMARY KEY, 27 | Name varchar(255), 28 | Specialty varchar(255) 29 | ); 30 | 31 | CREATE TABLE Appointments ( 32 | AppointmentID int PRIMARY KEY, 33 | Date date, 34 | Time time, 35 | PatientID int, 36 | DoctorID int, 37 | FOREIGN KEY (PatientID) REFERENCES Patients(PatientID), 38 | FOREIGN KEY (DoctorID) REFERENCES Doctors(DoctorID) 39 | ); 40 | ``` 41 | 42 | #### 3. Relationships in a Medical Database 43 | - **One-to-One Relationship**: 44 | - Example: Each `Patient` has one `MedicalRecord`. 45 | - SQL: 46 | 47 | ```sql 48 | CREATE TABLE MedicalRecords ( 49 | RecordID int PRIMARY KEY, 50 | Details text, 51 | PatientID int UNIQUE, 52 | FOREIGN KEY (PatientID) REFERENCES Patients(PatientID) 53 | ); 54 | ``` 55 | 56 | Certainly! Let's delve deeper into the SQL examples for One-to-Many and Many-to-Many relationships within the context of a medical system. 57 | 58 | ### One-to-Many Relationship Example 59 | 60 | In a medical system, a common One-to-Many relationship is between doctors and appointments. A single doctor can have multiple appointments with different patients. 61 | 62 | #### SQL Example for One-to-Many Relationship 63 | 64 | 1. **Doctors Table**: 65 | ```sql 66 | CREATE TABLE Doctors ( 67 | DoctorID int PRIMARY KEY, 68 | Name varchar(255), 69 | Specialty varchar(255) 70 | ); 71 | ``` 72 | 73 | 2. **Appointments Table**: 74 | ```sql 75 | CREATE TABLE Appointments ( 76 | AppointmentID int PRIMARY KEY, 77 | Date date, 78 | Time time, 79 | PatientID int, 80 | DoctorID int, 81 | FOREIGN KEY (DoctorID) REFERENCES Doctors(DoctorID) 82 | ); 83 | ``` 84 | 85 | In this scenario, `DoctorID` in the `Appointments` table is a foreign key that references `DoctorID` in the `Doctors` table. This creates a One-to-Many relationship where one doctor can have many appointments. 86 | 87 | ### Many-to-Many Relationship Example 88 | 89 | A Many-to-Many relationship in a medical system might be between patients and treatments. A patient can receive multiple treatments, and each treatment can be applied to many patients. 90 | 91 | #### SQL Example for Many-to-Many Relationship 92 | 93 | 1. **Patients Table**: 94 | ```sql 95 | CREATE TABLE Patients ( 96 | PatientID int PRIMARY KEY, 97 | Name varchar(255), 98 | DateOfBirth date 99 | ); 100 | ``` 101 | 102 | 2. **Treatments Table**: 103 | ```sql 104 | CREATE TABLE Treatments ( 105 | TreatmentID int PRIMARY KEY, 106 | TreatmentName varchar(255) 107 | ); 108 | ``` 109 | 110 | 3. **PatientTreatments Junction Table**: 111 | ```sql 112 | CREATE TABLE PatientTreatments ( 113 | PatientID int, 114 | TreatmentID int, 115 | PRIMARY KEY (PatientID, TreatmentID), 116 | FOREIGN KEY (PatientID) REFERENCES Patients(PatientID), 117 | FOREIGN KEY (TreatmentID) REFERENCES Treatments(TreatmentID) 118 | ); 119 | ``` 120 | 121 | In this example, the `PatientTreatments` table is a junction table that holds foreign keys from both the `Patients` and `Treatments` tables. This setup facilitates a Many-to-Many relationship where a patient can have multiple treatments, and each treatment can be associated with multiple patients. 122 | 123 | #### 4. Advanced SQL Concepts in Medical Relationships 124 | - **Self-Join Relationship Example**: 125 | - For a `Doctors` table, a senior `Doctor` might supervise junior `Doctors`. 126 | - SQL: 127 | 128 | ```sql 129 | ALTER TABLE Doctors 130 | ADD SupervisorID int, 131 | ADD FOREIGN KEY (SupervisorID) REFERENCES Doctors(DoctorID); 132 | ``` 133 | 134 | - **Cascade Operations**: 135 | - Automatically deleting `Appointments` if a `Patient` is removed from the system. 136 | - SQL: 137 | 138 | ```sql 139 | ALTER TABLE Appointments 140 | ADD ON DELETE CASCADE; 141 | ``` 142 | - **Normalization Example**: 143 | - Separating detailed `MedicalRecords` from the `Patients` table to reduce data redundancy. 144 | - **Denormalization Example**: 145 | - Combining patient details and medical records in one table for faster access in critical situations (at the cost of some redundancy). 146 | 147 | 148 | ### Recommended Resources 149 | - [CREATE TABLE](https://www.w3schools.com/sql/sql_create_table.asp) 150 | - [PRIMARY KEY](https://www.w3schools.com/sql/sql_primarykey.asp) 151 | - [FOREIGN KEY](https://www.w3schools.com/sql/sql_foreignkey.asp) 152 | - [Relationships in SQL – Complete Guide With Examples](https://blog.devart.com/types-of-relationships-in-sql-server-database.html) -------------------------------------------------------------------------------- /JavaCore/lessons/while.MD: -------------------------------------------------------------------------------- 1 | ## **`while` loop in Java** 2 | In Java, a `while` loop is used to repeatedly execute a block of code as long as a particular condition remains true. It's similar to the `do-while` loop, but the key difference is in the condition-checking sequence. In a `do-while` loop, the code block is executed at least once before checking the condition. On the other hand, in a `while` loop, the condition is checked before the loop body is executed. 3 | 4 | ### **Syntax:** 5 | ```java 6 | while(condition) { 7 | // code to be executed 8 | } 9 | ``` 10 | 11 | ### **Example:** 12 | Here is a simple example of a `while` loop that prints numbers from 1 to 5: 13 | 14 | ```java 15 | int i = 1; 16 | while(i <= 5) { 17 | System.out.println(i); 18 | i++; 19 | } 20 | ``` 21 | 22 | **Output:** 23 | ``` 24 | 1 25 | 2 26 | 3 27 | 4 28 | 5 29 | ``` 30 | 31 | ### Sum of Natural Numbers 32 | This program calculates the sum of the first `n` natural numbers: 33 | 34 | ```java 35 | int n = 10; // You can change this value 36 | int sum = 0; 37 | int i = 1; 38 | 39 | while(i <= n) { 40 | sum += i; 41 | i++; 42 | } 43 | 44 | System.out.println("The sum of first " + n + " natural numbers is: " + sum); 45 | ``` 46 | 47 | **Output:** 48 | ``` 49 | The sum of first 10 natural numbers is: 55 50 | ``` 51 | 52 | ### Checking for a Prime Number 53 | 54 | This program checks if a given number is prime: 55 | 56 | ```java 57 | int num = 29; // You can change this value 58 | boolean isPrime = true; 59 | int i = 2; 60 | 61 | while(i <= num/2) { 62 | if(num % i == 0) { 63 | isPrime = false; 64 | break; 65 | } 66 | i++; 67 | } 68 | 69 | if(isPrime) { 70 | System.out.println(num + " is a prime number."); 71 | } else { 72 | System.out.println(num + " is not a prime number."); 73 | } 74 | ``` 75 | 76 | **Output:** 77 | ``` 78 | 29 is a prime number. 79 | ``` 80 | 81 | ### **Key Points:** 82 | 1. The loop condition is checked before the loop body is executed. If the condition is false initially, the loop body may never execute. 83 | 2. It's crucial to ensure that the loop condition changes during the iterations to avoid an infinite loop. 84 | 85 | ### Recommended Resources 86 | - [Java while loop](https://www.w3schools.com/java/java_while_loop.asp) 87 | - [While loop with examples](https://www.geeksforgeeks.org/java-while-loop-with-examples) 88 | - [while and do-while](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html) 89 | 90 | ## Tasks 91 | 92 |
93 | Task 1: Counter Challenge 94 |
 95 | 
 96 | # **Counter Challenge**
 97 | ## **Description:**
 98 | Write a Java program that counts how many times the user inputs a positive number using a `while` loop. The program should stop when the user inputs a negative number and then display the total count of positive numbers entered.
 99 | 
100 | ### _Inputs & Outputs:_
101 | #### _Sample Input 1:_
102 | Enter a number: 5  
103 | Enter a number: 9  
104 | Enter a number: 2  
105 | Enter a number: 6  
106 | Enter a number: -1
107 | 
108 | #### _Sample Output 1:_
109 | You entered 4 positive numbers.
110 | 
111 | #### _Sample Input 2:_
112 | Enter a number: 8  
113 | Enter a number: -5
114 | 
115 | #### _Sample Output 2:_
116 | You entered 1 positive number.
117 | 
118 | 
119 |
120 | 121 | --- 122 | 123 |
124 | Task 2: Number Guesser 125 |
126 | 
127 | # **Number Guesser**
128 | ## **Description:**
129 | Write a Java program where the computer randomly selects a number between 1 and 10. Ask the user to guess this number. After each guess, the program should inform the user whether their guess was too high, too low, or correct. The program should continue until the user guesses the correct number.
130 | 
131 | ### _Inputs & Outputs:_
132 | #### _Sample Input:_
133 | Guess the number: 5  
134 | Guess the number: 8
135 | 
136 | #### _Sample Output:_
137 | Too low!  
138 | Correct!
139 | 
140 | 
141 |
142 | 143 | --- 144 | 145 |
146 | Task 3: Sum of Digits 147 |
148 | 
149 | # **Sum of Digits**
150 | ## **Description:**
151 | Write a Java program that calculates the sum of the digits of an integer. If the sum is a single-digit number, the program should display it. However, if the sum results in a multiple-digit number, it should continue adding the digits until a single-digit number is obtained.
152 | 
153 | ### _Inputs & Outputs:_
154 | #### _Sample Input:_
155 | Enter a number: 9875
156 | 
157 | #### _Sample Output:_
158 | Single-digit sum is: 2
159 | 
160 | _Reasoning: 9 + 8 + 7 + 5 = 29, then 2 + 9 = 11, and finally 1 + 1 = 2._
161 | 
162 | 
163 |
164 | 165 | --- 166 | 167 |
168 | Task 4: Collatz Sequence 169 |
170 | 
171 | # **Collatz Sequence**
172 | ## **Description:**
173 | The Collatz sequence is defined for a positive integer as:
174 | - If the number is even, divide it by 2.
175 | - If the number is odd, multiply it by 3 and add 1.
176 | 
177 | Continue this process until the number becomes 1. Write a Java program that takes a positive integer as input and displays its Collatz sequence. Also, count the number of steps taken to reach 1.
178 | 
179 | ### _Inputs & Outputs:_
180 | #### _Sample Input:_
181 | Enter a number: 6
182 | 
183 | #### _Sample Output:_
184 | Collatz sequence: 6 3 10 5 16 8 4 2 1  
185 | Number of steps to reach 1: 8
186 | 
187 | 
188 |
189 | -------------------------------------------------------------------------------- /db/lessons/crud.MD: -------------------------------------------------------------------------------- 1 | ### Using JDBC for CRUD Operations 2 | JDBC provides a low-level API for executing SQL statements against a database, allowing for direct control over the 3 | CRUD operations. Here's how you can implement these operations using JDBC: 4 | 5 | #### 1. Setup Database Connection 6 | First, ensure you have a JDBC driver for your database. Then, establish a connection: 7 | 8 | ```java 9 | import java.sql.Connection; 10 | import java.sql.DriverManager; 11 | 12 | public class DBConnection { 13 | private static final String URL = "jdbc:mysql://localhost:3306/mydatabase"; 14 | private static final String USER = "username"; 15 | private static final String PASSWORD = "password"; 16 | 17 | public static Connection getConnection() throws Exception { 18 | Class.forName("com.mysql.jdbc.Driver"); 19 | return DriverManager.getConnection(URL, USER, PASSWORD); 20 | } 21 | } 22 | ``` 23 | 24 | #### 2. Create (Insert) 25 | To insert a new record into the database: 26 | 27 | ```java 28 | public void createUser(User user) { 29 | String sql = "INSERT INTO users (name, email) VALUES (?, ?)"; 30 | try (Connection conn = DBConnection.getConnection(); 31 | PreparedStatement pstmt = conn.prepareStatement(sql)) { 32 | pstmt.setString(1, user.getName()); 33 | pstmt.setString(2, user.getEmail()); 34 | pstmt.executeUpdate(); 35 | } catch (Exception e) { 36 | e.printStackTrace(); 37 | } 38 | } 39 | ``` 40 | 41 | #### 3. Read (Select) 42 | To retrieve users from the database: 43 | 44 | ```java 45 | public List getAllUsers() { 46 | List users = new ArrayList<>(); 47 | String sql = "SELECT * FROM users"; 48 | try (Connection conn = DBConnection.getConnection(); 49 | PreparedStatement pstmt = conn.prepareStatement(sql); 50 | ResultSet rs = pstmt.executeQuery()) { 51 | while (rs.next()) { 52 | User user = new User(rs.getInt("id"), rs.getString("name"), rs.getString("email")); 53 | users.add(user); 54 | } 55 | } catch (Exception e) { 56 | e.printStackTrace(); 57 | } 58 | return users; 59 | } 60 | ``` 61 | 62 | #### 4. Update 63 | To update existing user details: 64 | 65 | ```java 66 | public void updateUser(User user) { 67 | String sql = "UPDATE users SET name = ?, email = ? WHERE id = ?"; 68 | try (Connection conn = DBConnection.getConnection(); 69 | PreparedStatement pstmt = conn.prepareStatement(sql)) { 70 | pstmt.setString(1, user.getName()); 71 | pstmt.setString(2, user.getEmail()); 72 | pstmt.setInt(3, user.getId()); 73 | pstmt.executeUpdate(); 74 | } catch (Exception e) { 75 | e.printStackTrace(); 76 | } 77 | } 78 | ``` 79 | 80 | #### 5. Delete 81 | To delete a user from the database: 82 | 83 | ```java 84 | public void deleteUser(int id) { 85 | String sql = "DELETE FROM users WHERE id = ?"; 86 | try (Connection conn = DBConnection.getConnection(); 87 | PreparedStatement pstmt = conn.prepareStatement(sql)) { 88 | pstmt.setInt(1, id); 89 | pstmt.executeUpdate(); 90 | } catch (Exception e) { 91 | e.printStackTrace(); 92 | } 93 | } 94 | ``` 95 | 96 | ### Using ORM (Hibernate) for CRUD Operations 97 | ORM tools like Hibernate abstract away the boilerplate JDBC code and provide a more object-oriented approach 98 | to interacting with the database. With Hibernate, you map Java classes to database tables and use these classes 99 | to interact with the database. 100 | 101 | #### Setup 102 | First, configure Hibernate with an `hibernate.cfg.xml` file, and annotate your Java classes with JPA annotations 103 | to define the mapping. 104 | 105 | #### Create (Persist) 106 | ```java 107 | Session session = sessionFactory.openSession(); 108 | session.beginTransaction(); 109 | session.save(user); 110 | session.getTransaction().commit(); 111 | session.close(); 112 | ``` 113 | 114 | #### Read (Find or Query) 115 | ```java 116 | Session session = sessionFactory.openSession(); 117 | User user = session.get(User.class, userId); 118 | session.close(); 119 | return user; 120 | ``` 121 | 122 | #### Update (Merge) 123 | ```java 124 | Session session = sessionFactory.openSession(); 125 | session.beginTransaction(); 126 | session.update(user); 127 | session.getTransaction().commit(); 128 | session.close(); 129 | ``` 130 | 131 | #### Delete (Remove) 132 | ```java 133 | Session session = sessionFactory.openSession(); 134 | session.beginTransaction(); 135 | User user = session.get(User.class, userId); 136 | if (user != null) { 137 | session.delete(user); 138 | } 139 | session.getTransaction().commit(); 140 | session.close(); 141 | ``` 142 | 143 | ### Conclusion 144 | Whether you choose the low-level control of JDBC or the abstraction provided by an ORM like Hibernate, implementing 145 | CRUD operations is a crucial skill for Java developers working with databases. JDBC offers more control and is 146 | lightweight, while Hibernate reduces boilerplate and provides a rich set of features for object-relational mapping, 147 | caching, and more. The choice between them depends on your application's specific requirements and your preference 148 | for low-level control versus ease of development. 149 | 150 | ### Recommended Resources 151 | - [Simplifying CRUD Operation with JDBC](https://www.geeksforgeeks.org/simplifying-crud-operation-with-jdbc/) 152 | - [Java JDBC CRUD Tutorial: SQL Insert, Select, Update, and Delete Examples](https://www.codejava.net/java-se/jdbc/jdbc-tutorial-sql-insert-select-update-and-delete-examples) 153 | - [Hibernate Tutorial For Beginners](https://www.digitalocean.com/community/tutorials/hibernate-tutorial-for-beginners) 154 | - [Hibernate Tutorial](https://www.geeksforgeeks.org/hibernate-tutorial/) -------------------------------------------------------------------------------- /db/lessons/sqllite_env.MD: -------------------------------------------------------------------------------- 1 | ### Introduction to SQL Databases 2 | #### 1. Overview of SQL Databases 3 | - **Definition and Purpose**: SQL (Structured Query Language) databases are systems used for managing and manipulating relational data. They use SQL as the primary language for interacting with the data. SQL databases are essential in many applications for storing, retrieving, and manipulating data efficiently. 4 | - **Role of SQL in Software Development**: SQL plays a crucial role in almost all database-driven applications. Understanding SQL is essential for backend development, data analysis, and even fields like data science. 5 | - **SQL vs. NoSQL Differences**: SQL databases are table-based and ideal for complex queries, while NoSQL databases (like MongoDB) are document, key-value, or wide-column stores and are better for unstructured data and scalability. 6 | 7 | #### 2. Understanding SQL Database Structure 8 | - **Tables, Rows, and Columns**: A SQL database is made up of one or more tables. Each table has rows (records) and columns (attributes). For instance, a `Users` table might have columns like `UserID`, `Name`, and `Email`. 9 | - **Primary Keys and Foreign Keys**: A primary key is a unique identifier for each record in a table. A foreign key is a field in one table that links to the primary key in another, establishing relationships between tables. 10 | - **Indexes and Normalization**: Indexes improve the speed of data retrieval. Normalization is the process of organizing data to reduce redundancy and improve data integrity. 11 | 12 | #### 3. Introduction to SQL (Structured Query Language) 13 | - **Basic SQL Syntax and Commands**: Covering the basic structure of SQL commands - `SELECT`, `INSERT`, `UPDATE`, `DELETE`. 14 | - **CRUD Operations**: Demonstrating how to create, read, update, and delete data in a database using SQL commands. 15 | - **Querying Data**: Explaining how to use `SELECT` statements to retrieve data, including filtering (`WHERE` clause), sorting (`ORDER BY`), and joining tables. 16 | 17 | ### Setting up a SQL Database Environment (SQLite) 18 | #### 1. Introduction to SQLite 19 | - **What is SQLite?**: SQLite is a lightweight, disk-based database that doesn't require a separate server process. It’s ideal for small to medium-sized applications. 20 | - **Advantages**: It's portable, easy to set up, requires minimal configuration, and is embedded into the end program. 21 | - **Use Cases**: Common in mobile applications, small to medium web applications, and as an embedded database for application software. 22 | 23 | ### 2. Setting up SQLite 24 | #### Installing SQLite 25 | 1. **Download SQLite**: 26 | - Visit the SQLite official website [sqlite.org](https://www.sqlite.org/download.html) 27 | - Under the "Precompiled Binaries for Windows" (or a relevant OS), download the zip file for SQLite tools. 28 | - Extract the downloaded zip file into a folder on your computer, for example, `C:\sqlite`. 29 | 2. **Set Up the Environment Variable** (Optional, for easier command line access): 30 | - Right-click on 'This PC' or 'My Computer' and select 'Properties'. 31 | - Click on 'Advanced system settings' and then 'Environment Variables'. 32 | - Under 'System Variables', find and select 'Path', then click 'Edit'. 33 | - Add the path to your SQLite folder (e.g., `C:\sqlite`). 34 | - Click 'OK' to save and exit out of the dialogs. 35 | 36 | #### SQLite Tools and Interfaces 37 | 1. **SQLite CLI (Command Line Interface)**: 38 | - Accessed through the command prompt or terminal. 39 | - Ideal for executing quick commands and scripts. 40 | 2. **SQLite GUI Tools**: 41 | - Tools like DB Browser for SQLite or SQLiteStudio provide a graphical interface for interacting with SQLite databases. 42 | - Useful for visualizing data and schema, as well as executing SQL queries. 43 | To use a GUI tool: 44 | - Download and install a tool like [DB Browser for SQLite](https://sqlitebrowser.org/dl/) 45 | - Open the tool and you can either open an existing database or create a new one through the interface. 46 | 47 | #### Creating a New Database 48 | 1. **Using SQLite CLI**: 49 | - Open your command prompt or terminal. 50 | - Navigate to the SQLite directory if it's not added to your PATH. 51 | - Type `sqlite3 [YourDatabaseName].db` and press Enter. For example, `sqlite3 Library.db`. This command creates a new SQLite database named 'Library.db'. 52 | - You are now in the SQLite command-line interface where you can execute further SQL commands. 53 | 2. **Creating Tables**: 54 | - In the SQLite CLI, use the `CREATE TABLE` SQL command to create a new table. 55 | - For example, to create a table named 'Books', type: 56 | ```sql 57 | CREATE TABLE Books ( 58 | BookID INTEGER PRIMARY KEY, 59 | Title TEXT NOT NULL, 60 | Author TEXT NOT NULL, 61 | PublishedYear INTEGER 62 | ); 63 | ``` 64 | - Press Enter to execute the command. This creates a table with columns for book ID, title, author, and the year of publication. 65 | 3. **Using a GUI Tool**: 66 | - Open your SQLite GUI tool. 67 | - Go to 'File' and select 'New Database'. 68 | - Name your database (e.g., 'Library.db') and choose where to save it. 69 | - Once created, use the GUI's interface to create new tables, add columns, and define data types and constraints. 70 | 71 | 72 | ### Conclusion 73 | - **Recap and Summary**: Summarizing the key concepts covered. 74 | - **Project Ideas**: Suggesting potential projects using SQLite for practical experience. 75 | 76 | ### Recommended Resources 77 | - [SQLite Tutorial](https://www.sqlitetutorial.net/) 78 | - [How To Install SQLite on Windows](https://www.youtube.com/watch?v=dcfh5iQ_-3s) 79 | - [SQLite Java: Connect To SQLite Database Using SQLite JDBC Driver](https://www.sqlitetutorial.net/sqlite-java/sqlite-jdbc-driver/) 80 | - [SQLite Java: Create a New SQLite Database](https://www.sqlitetutorial.net/sqlite-java/create-database/) 81 | - [SQLite Java: Create a New Table](https://www.sqlitetutorial.net/sqlite-java/create-table/) 82 | -------------------------------------------------------------------------------- /JavaCore/lessons/javadoc.MD: -------------------------------------------------------------------------------- 1 | ### JavaDoc Overview 2 | - **Purpose**: JavaDoc is a documentation tool provided by Oracle for the Java programming language. It is used for writing API documentation in HTML format from Java source code. 3 | - **Usage**: JavaDoc comments are placed above classes, interfaces, methods, and fields. These comments are then processed by the JavaDoc tool to generate documentation. 4 | - **Format**: JavaDoc comments begin with `/**` and end with `*/`. They can include a variety of tags to describe different aspects of code. 5 | 6 | ### Basic Structure 7 | ```java 8 | /** 9 | * Class description here 10 | * 11 | * @author Your Name 12 | * @version 1.0 13 | */ 14 | public class MyClass { 15 | /** 16 | * Method description here. 17 | * 18 | * @param param1 Description of param1 19 | * @return Description of return value 20 | */ 21 | public int myMethod(int param1) { 22 | // method body 23 | } 24 | } 25 | ``` 26 | 27 | ### Key Tags 28 | - `@param`: Describes a parameter of a method or constructor. 29 | - `@return`: Describes what a method returns. 30 | - `@exception` or `@throws`: Describes an exception thrown by a method. 31 | - `@see`: Creates a link to another element in the documentation. 32 | - `@since`: Marks when a part of the API was first added. 33 | - `@deprecated`: Marks a part of the API as outdated or replaced. 34 | 35 | ### Example 36 | ```java 37 | /** 38 | * This class represents a simple calculator. 39 | * 40 | * @author Your Name 41 | * @version 1.0 42 | */ 43 | public class Calculator { 44 | 45 | /** 46 | * Adds two integers. 47 | * 48 | * @param a the first operand 49 | * @param b the second operand 50 | * @return the sum of a and b 51 | */ 52 | public int add(int a, int b) { 53 | return a + b; 54 | } 55 | 56 | /** 57 | * Subtracts two integers. 58 | * 59 | * @param a the first operand 60 | * @param b the second operand 61 | * @return the difference between a and b 62 | */ 63 | public int subtract(int a, int b) { 64 | return a - b; 65 | } 66 | } 67 | ``` 68 | 69 | ### **Maintainability** 70 | - **Long-term Upkeep**: In large systems, the original developers might not always be available. Comprehensive documentation allows new developers to understand and maintain the system without relying solely on the original authors. 71 | - **Complexity Management**: Large systems often have complex codebases. Good documentation serves as a guide, making it easier to navigate and understand the intricate relationships between different parts of the system. 72 | 73 | ### **Collaboration and Team Efficiency** 74 | - **Team Communication**: In a team setting, not every member works on every part of the system. Documentation provides a common reference, ensuring all team members have a clear understanding of each component. 75 | - **Onboarding New Developers**: New team members can get up to speed more quickly if they have access to well-written documentation. This reduces the ramp-up time and improves overall productivity. 76 | 77 | ### **Quality Assurance and Bug Tracking** 78 | - **Identifying Issues**: Well-documented code makes it easier to pinpoint where and why a bug occurs. This is especially important in large systems where bugs can have wide-ranging impacts. 79 | - **Code Reviews**: Documentation aids in code reviews by providing reviewers with context, helping them to understand the purpose and functionality of the code they are examining. 80 | 81 | ### **Future Development and Scalability** 82 | - **Guiding Future Changes**: Documentation helps in planning future development. It gives a clear picture of how current functionalities are implemented and how new features can be integrated. 83 | - **API and Library Usage**: In large systems, different teams or external users might use certain libraries or APIs. Proper documentation, like JavaDoc for API methods, is essential for others to use these components effectively. 84 | 85 | ### **Standardization and Best Practices** 86 | - **Consistent Coding Standards**: Documentation enforces standardization in coding practices, which is vital for the coherence and reliability of a large system. 87 | - **Encouraging Best Practices**: Well-documented code serves as a reference for best practices within an organization, promoting a culture of quality and thoroughness. 88 | 89 | ### **Legal and Compliance Reasons** 90 | - **Meeting Regulatory Requirements**: Certain industries require comprehensive documentation for legal or regulatory compliance, especially for systems that impact public safety, health, or privacy. 91 | - **Audits and Certifications**: For audits and obtaining certifications, having detailed documentation can expedite the process and demonstrate the system's integrity and reliability. 92 | 93 | ### Conclusion 94 | In essence, documentation in large systems is about creating a blueprint of the system that aids in its maintenance, 95 | evolution, and use. It's not just about what the code does, but also about how it fits into the larger picture, how it 96 | should be used, and how it can be maintained and evolved over time. This is why tools like JavaDoc are invaluable in 97 | large-scale software development. 98 | 99 | 100 | ### Tips for Writing Good JavaDoc 101 | 1. **Be Concise**: Provide enough information to understand the functionality, but avoid unnecessary details. 102 | 2. **Consistency**: Keep a consistent style in the way you document classes, methods, and fields. 103 | 3. **Regular Updates**: Update documentation when updating code to ensure it remains relevant. 104 | 105 | 106 | ### Recommended Resources 107 | - [How to Write Doc Comments for the Javadoc Tool](https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html) 108 | - [Introduction to Javadoc](https://www.baeldung.com/javadoc) 109 | - [What is JavaDoc tool and how to use it?](https://www.geeksforgeeks.org/what-is-javadoc-tool-and-how-to-use-it) 110 | -------------------------------------------------------------------------------- /db/lessons/db_normalization.MD: -------------------------------------------------------------------------------- 1 | ### Basics of Database Design 2 | 1. **Understanding the Purpose of the Database:** 3 | - Determine what information needs to be stored and how it will be used. 4 | - Example: A student database might need to store details like student ID, name, course enrollments, and grades. 5 | 2. **Identifying Entities and Relationships:** 6 | - Entities represent objects or concepts (like 'Student', 'Course'). 7 | - Relationships show how entities interact (e.g., a student 'enrolls in' a course). 8 | - Example: Entity 'Student' has a relationship with entity 'Course' through 'Enrollment'. 9 | 3. **Designing a Schema:** 10 | - Create a diagram that outlines entities, their attributes, and relationships. 11 | - Example: A schema diagram showing 'Students', 'Courses', and 'Enrollments' as entities with their attributes. 12 | 13 | ### Basics of Normalization 14 | Normalization is the process of organizing a database to reduce redundancy and improve data integrity. 15 | 1. **First Normal Form (1NF):** 16 | - Ensure each table column contains atomic, indivisible values. 17 | - Example: Splitting a 'FullName' column into 'FirstName' and 'LastName'. 18 | 2. **Second Normal Form (2 NF):** 19 | - Meet all requirements of 1NF. 20 | - Ensure that all non-key attributes are fully functional dependent on the primary key. 21 | - Example: If a table contains student data and course data, separate it into two tables, one for each entity. 22 | 3. **Third Normal Form (3NF):** 23 | - Meet all requirements of 2NF. 24 | - Ensure that all the attributes are only dependent on the primary key, not on other non-key attributes. 25 | - Example: If a table contains 'StudentID', 'CourseID', and 'CourseInstructor', where 'CourseInstructor' depends on 'CourseID' and not 'StudentID', move 'CourseInstructor' to the course table. 26 | 4. **Boyce-Codd Normal Form (BCNF):** 27 | - A stronger version of 3NF. 28 | - Ensures that no non-trivial functional dependencies violate the primary key. 29 | - Example: Address any remaining anomalies not covered by 3NF. 30 | 31 | ### Case example 32 | ### 1. First Normal Form (1NF) 33 | **Problem:** A table containing student information where the `Courses` column contains multiple values. 34 | 35 | ```sql 36 | CREATE TABLE Students ( 37 | StudentID int, 38 | StudentName varchar(100), 39 | Courses varchar(100) -- Courses column has multiple values (e.g., 'Math, Science') 40 | ); 41 | ``` 42 | 43 | **Solution:** Modify the table so that each column has atomic values. 44 | 45 | ```sql 46 | CREATE TABLE Students ( 47 | StudentID int, 48 | StudentName varchar(100) 49 | ); 50 | 51 | CREATE TABLE Enrollments ( 52 | StudentID int, 53 | CourseName varchar(100) 54 | ); 55 | ``` 56 | 57 | ### 2. Second Normal Form (2NF) 58 | **Problem:** A table not in 2NF, where non-key attributes don't fully depend on the primary key. 59 | 60 | ```sql 61 | CREATE TABLE Enrollments ( 62 | StudentID int, 63 | CourseID int, 64 | EnrollmentDate date, 65 | InstructorName varchar(100) -- Depends only on CourseID, not on StudentID 66 | ); 67 | ``` 68 | 69 | **Solution:** Separate the data into two tables to ensure all non-key attributes are fully dependent on the primary key. 70 | 71 | ```sql 72 | CREATE TABLE Enrollments ( 73 | StudentID int, 74 | CourseID int, 75 | EnrollmentDate date 76 | ); 77 | 78 | CREATE TABLE Courses ( 79 | CourseID int, 80 | InstructorName varchar(100) 81 | ); 82 | ``` 83 | 84 | ### 3. Third Normal Form (3NF) 85 | **Problem:** A table not in 3NF, containing transitive dependencies (non-key attribute depending on another non-key attribute). 86 | 87 | ```sql 88 | CREATE TABLE Courses ( 89 | CourseID int, 90 | InstructorID int, 91 | InstructorOffice varchar(100) -- InstructorOffice depends on InstructorID, not CourseID 92 | ); 93 | ``` 94 | 95 | **Solution:** Remove transitive dependencies by creating separate tables. 96 | 97 | ```sql 98 | CREATE TABLE Courses ( 99 | CourseID int, 100 | InstructorID int 101 | ); 102 | 103 | CREATE TABLE Instructors ( 104 | InstructorID int, 105 | InstructorOffice varchar(100) 106 | ); 107 | ``` 108 | 109 | ### 4. Boyce-Codd Normal Form (BCNF) 110 | **Problem:** A table where a non-trivial functional dependency violates the primary key. 111 | 112 | ```sql 113 | CREATE TABLE CourseAssignments ( 114 | CourseID int, 115 | InstructorID int, 116 | RoomNumber varchar(50), 117 | PRIMARY KEY (CourseID, InstructorID) 118 | -- RoomNumber is functionally dependent on Course 119 | 120 | ID, which is part of the composite primary key but not on the entire key. 121 | ); 122 | 123 | **Solution:** Reorganize the table to ensure that every determinant is a candidate key. 124 | 125 | ```sql 126 | CREATE TABLE CourseAssignments ( 127 | CourseID int, 128 | RoomNumber varchar(50), 129 | PRIMARY KEY (CourseID) 130 | ); 131 | 132 | CREATE TABLE Instructors ( 133 | InstructorID int, 134 | CourseID int, 135 | PRIMARY KEY (InstructorID, CourseID) 136 | ); 137 | ``` 138 | 139 | In this BCNF example, the original `CourseAssignments` table had a situation where `RoomNumber` was dependent on 140 | `CourseID` but not on the entire composite primary key (`CourseID`, `InstructorID`). By splitting the table, 141 | each attribute in both tables is now functionally dependent only on the entire primary key of its respective table, 142 | which satisfies the requirements of BCNF. 143 | 144 | ### Recommended Resources 145 | - [Description of the database normalization basics](https://learn.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description) 146 | - [What is Normalization in DBMS (SQL)? 1NF, 2NF, 3NF Example](https://www.guru99.com/database-normalization.html) 147 | - [database normalization](https://www.techtarget.com/searchdatamanagement/definition/normalization) 148 | - [Database Normalization – Normal Forms 1nf 2nf 3nf Table Examples](https://www.freecodecamp.org/news/database-normalization-1nf-2nf-3nf-table-examples) 149 | 150 | -------------------------------------------------------------------------------- /db/lessons/joins_conditions.MD: -------------------------------------------------------------------------------- 1 | ### Advanced SQL Concepts: Joins, Conditions, Subqueries, Views, and Indexes 2 | #### 1. Joins 3 | Joins are used to combine rows from two or more tables. 4 | **Example**: 5 | Tables: `Patients`, `Doctors`, and `Appointments`. 6 | 7 | - To list all appointments along with patient and doctor names: 8 | 9 | ```sql 10 | SELECT Patients.PatientName, Doctors.DoctorName, Appointments.Date 11 | FROM Appointments 12 | JOIN Patients ON Appointments.PatientID = Patients.PatientID 13 | JOIN Doctors ON Appointments.DoctorID = Doctors.DoctorID; 14 | ``` 15 | 16 | ### 2. Conditions (WHERE, HAVING) 17 | 18 | These clauses are used in SQL to filter records based on specific conditions. 19 | 20 | #### WHERE Clause 21 | The `WHERE` clause is used to filter records before any grouping, making it useful for setting conditions on individual rows. 22 | 23 | **Examples**: 24 | 1. **Find Appointments for a Specific Doctor**: 25 | - If you want to get a list of all appointments for 'Dr. Smith': 26 | ```sql 27 | SELECT * 28 | FROM Appointments 29 | WHERE DoctorID = (SELECT DoctorID FROM Doctors WHERE DoctorName = 'Dr. Smith'); 30 | ``` 31 | 32 | 2. **Find Patients with Appointments on a Specific Date**: 33 | - To retrieve all patients who have an appointment on '2023-01-21': 34 | ```sql 35 | SELECT Patients.PatientName 36 | FROM Patients 37 | JOIN Appointments ON Patients.PatientID = Appointments.PatientID 38 | WHERE Appointments.Date = '2023-01-21'; 39 | ``` 40 | 41 | 3. **Find Doctors who have Appointments in a Specific Department (e.g., 'Cardiology')**: 42 | - Assuming there's a `Department` column in `Doctors` table: 43 | ```sql 44 | SELECT DoctorName 45 | FROM Doctors 46 | WHERE Department = 'Cardiology'; 47 | ``` 48 | 49 | #### HAVING Clause 50 | The `HAVING` clause is used to filter groups of rows after `GROUP BY` has been applied. It's especially useful for working with aggregate functions like `COUNT`, `SUM`, `AVG`, etc. 51 | **Examples**: 52 | 1. **Find Doctors with More Than a Certain Number of Appointments**: 53 | - If you want to find doctors who have more than 10 appointments: 54 | ```sql 55 | SELECT Doctors.DoctorName, COUNT(Appointments.AppointmentID) AS NumberOfAppointments 56 | FROM Doctors 57 | JOIN Appointments ON Doctors.DoctorID = Appointments.DoctorID 58 | GROUP BY Doctors.DoctorName 59 | HAVING COUNT(Appointments.AppointmentID) > 10; 60 | ``` 61 | 62 | 2. **Find Departments with Average Appointment Duration Exceeding a Certain Threshold**: 63 | - Assuming there's a `Duration` column in `Appointments` table: 64 | ```sql 65 | SELECT Doctors.Department, AVG(Appointments.Duration) AS AverageDuration 66 | FROM Doctors 67 | JOIN Appointments ON Doctors.DoctorID = Appointments.DoctorID 68 | GROUP BY Doctors.Department 69 | HAVING AVG(Appointments.Duration) > 30; -- for example, if the duration is in minutes 70 | ``` 71 | 72 | 3. **Find Days with a Number of Appointments Above Average**: 73 | - To find dates with an above-average number of appointments: 74 | ```sql 75 | SELECT Date, COUNT(AppointmentID) AS NumberOfAppointments 76 | FROM Appointments 77 | GROUP BY Date 78 | HAVING COUNT(AppointmentID) > (SELECT AVG(NumberOfAppointments) FROM (SELECT Date, COUNT(AppointmentID) AS NumberOfAppointments FROM Appointments GROUP BY Date) AS AverageAppointments); 79 | ``` 80 | These examples should provide a deeper understanding of how to use `WHERE` and `HAVING` clauses effectively in SQL, especially in scenarios related to the medical field. They are crucial for querying databases efficiently and are widely used in real-world applications. 81 | 82 | #### 3. Subqueries 83 | A subquery is a nested query. 84 | 85 | **Example**: 86 | - To find doctors who have appointments with a patient named 'John Doe': 87 | 88 | ```sql 89 | SELECT DoctorName 90 | FROM Doctors 91 | WHERE DoctorID IN (SELECT DoctorID FROM Appointments WHERE PatientID = (SELECT PatientID FROM Patients WHERE PatientName = 'John Doe')); 92 | ``` 93 | 94 | #### 4. Views 95 | A view is a virtual table. 96 | **Example**: 97 | - Creating a view for appointment details: 98 | 99 | ```sql 100 | CREATE VIEW AppointmentDetails AS 101 | SELECT Patients.PatientName, Doctors.DoctorName, Appointments.Date 102 | FROM Appointments 103 | JOIN Patients ON Appointments.PatientID = Patients.PatientID 104 | JOIN Doctors ON Appointments.DoctorID = Doctors.DoctorID; 105 | ``` 106 | 107 | Then query the view: 108 | 109 | ```sql 110 | SELECT * FROM AppointmentDetails; 111 | ``` 112 | 113 | #### 5. Indexes 114 | Indexes improve the speed of data retrieval. 115 | 116 | **Example**: 117 | - Creating an index on the `PatientID` in the `Appointments` table: 118 | 119 | ```sql 120 | CREATE INDEX idx_patient 121 | ON Appointments (PatientID); 122 | ``` 123 | 124 | ### Integrating with Java and SQLite 125 | To use these SQL concepts in Java with SQLite, here’s a basic structure: 126 | 127 | ```java 128 | import java.sql.*; 129 | 130 | public class MedicalDatabaseExample { 131 | public static void main(String[] args) { 132 | try { 133 | // Establishing connection to SQLite database 134 | Connection con = DriverManager.getConnection("jdbc:sqlite:path_to_your_database.db"); 135 | 136 | // Creating a statement 137 | Statement stmt = con.createStatement(); 138 | 139 | // Executing a query with WHERE condition 140 | ResultSet rs = stmt.executeQuery("SELECT * FROM AppointmentDetails WHERE DoctorName = 'Dr. Smith'"); 141 | 142 | // Iterating through the result set 143 | while (rs.next()) { 144 | System.out.println(rs.getString("PatientName") + " - " + rs.getString("DoctorName") + " - " + rs.getString("Date")); 145 | } 146 | 147 | // Closing connections 148 | rs.close(); 149 | stmt.close(); 150 | con.close(); 151 | } catch (SQLException e) { 152 | e.printStackTrace(); 153 | } 154 | } 155 | } 156 | ``` 157 | This example retrieves data from the `AppointmentDetails` view for appointments with 'Dr. Smith'. 158 | 159 | 160 | ### Recommended Resources 161 | - [JOINS](https://www.w3schools.com/sql/sql_join.asp) 162 | - [WHERE Clause](https://www.w3schools.com/sql/sql_where.asp) 163 | - [VIEWS](https://www.w3schools.com/sql/sql_view.asp) 164 | - [CREATE INDEX](https://www.w3schools.com/sql/sql_create_index.asp) 165 | -------------------------------------------------------------------------------- /JavaCore/lessons/treeset.MD: -------------------------------------------------------------------------------- 1 | ## Introduction to `TreeSet` in Java 2 | 3 | `TreeSet` is a member of the Java Collections Framework and implements the `Set` and `NavigableSet` interfaces. 4 | It's backed by a Red-Black Tree (a type of self-balancing binary search tree). The elements are ordered using their 5 | natural ordering, or by a comparator provided at set creation time, depending on which constructor is used. 6 | 7 | ### Features: 8 | 1. **Ordered**: Elements are stored in ascending order. 9 | 2. **No duplicates**: Just like any other set, it doesn’t allow duplicates. 10 | 3. **Non-synchronized**: Operations on `TreeSet` are not synchronized. 11 | 4. **Performance**: Operations like add, remove, and search take O(log n) time. 12 | 5. **Allows null initially**: However, if you try to add another null, it will throw an exception. 13 | 14 | ### Basic Operations: 15 | #### 1. Adding Elements 16 | ```java 17 | TreeSet numbers = new TreeSet<>(); 18 | numbers.add(10); 19 | numbers.add(5); 20 | numbers.add(15); 21 | System.out.println(numbers); // Outputs: [5, 10, 15] 22 | ``` 23 | 24 | #### 2. Removing Elements 25 | ```java 26 | numbers.remove(10); 27 | System.out.println(numbers); // Outputs: [5, 15] 28 | ``` 29 | 30 | #### 3. Checking if a Set Contains a Value 31 | ```java 32 | boolean hasValueFive = numbers.contains(5); // true 33 | ``` 34 | 35 | ### NavigableSet Methods: 36 | Since `TreeSet` implements `NavigableSet`, it provides some powerful navigation methods: 37 | 38 | 1. `first()`: Returns the first (lowest) element. 39 | 2. `last()`: Returns the last (highest) element. 40 | 3. `ceiling(E e)`: Returns the least element that is greater than or equal to the given element. 41 | 4. `floor(E e)`: Returns the greatest element that is less than or equal to the given element. 42 | 5. `higher(E e)`: Returns the least element that is strictly greater than the given element. 43 | 6. `lower(E e)`: Returns the greatest element that is strictly less than the given element. 44 | 45 | ```java 46 | System.out.println(numbers.ceiling(7)); // Outputs: 15 47 | System.out.println(numbers.floor(7)); // Outputs: 5 48 | ``` 49 | 50 | ### Custom Ordering: 51 | You can define a custom ordering for the elements in the `TreeSet` by providing a comparator. 52 | 53 | ```java 54 | TreeSet names = new TreeSet<>(Comparator.reverseOrder()); 55 | names.add("Alice"); 56 | names.add("Bob"); 57 | names.add("Charlie"); 58 | System.out.println(names); // Outputs: [Charlie, Bob, Alice] 59 | ``` 60 | 61 | ### Limitations: 62 | 1. All elements that are added to a `TreeSet` must implement the `Comparable` interface, unless you provide a custom comparator. This is because the `TreeSet` needs to know how to order the elements. 63 | 2. Adding null to a `TreeSet` which has already some elements will throw `NullPointerException`. 64 | 65 | ### Conclusion: 66 | `TreeSet` is a powerful collection class in Java, which not only ensures no duplicates but also maintains the 67 | elements in a sorted order. This makes it a good choice when you want to store unique values in a sorted manner. 68 | Whether it's navigating the set in a particular order, or maintaining a custom sort order, `TreeSet` provides the 69 | necessary methods to make these tasks easy. 70 | 71 | ### Recommended Resources 72 | - [A Guide to TreeSet in Java](https://www.baeldung.com/java-tree-set) 73 | - [TreeSet in Java](https://www.geeksforgeeks.org/treeset-in-java-with-examples) 74 | - [Java TreeSet](https://www.programiz.com/java-programming/treeset#google_vignette) 75 | 76 | ## Tasks 77 | 78 |
79 | Task 1: Create and Display 80 |
 81 | 
 82 | # Create and Display
 83 | ## Description:
 84 | Create a TreeSet, add some integers to it and then display them.
 85 | 
 86 | ### _Inputs & Outputs:_
 87 | #### _Sample Input 1:_
 88 | 5, 3, 8, 1
 89 | 
 90 | #### _Sample Output 1:_
 91 | 1, 3, 5, 8
 92 | 
 93 | #### _Sample Input 2:_
 94 | 10, 7, 12, 5
 95 | 
 96 | #### _Sample Output 2:_
 97 | 5, 7, 10, 12
 98 | 
 99 | 
100 |
101 | 102 | --- 103 | 104 |
105 | Task 2: Remove Element 106 |
107 | 
108 | # Remove Element
109 | ## Description:
110 | Given a TreeSet and an integer, remove that integer from the TreeSet and display the resultant TreeSet.
111 | 
112 | ### _Inputs & Outputs:_
113 | #### _Sample Input 1:_
114 | TreeSet: [2, 4, 6, 8, 10]
115 | Remove: 6
116 | 
117 | #### _Sample Output 1:_
118 | 2, 4, 8, 10
119 | 
120 | #### _Sample Input 2:_
121 | TreeSet: [5, 10, 15, 20]
122 | Remove: 5
123 | 
124 | #### _Sample Output 2:_
125 | 10, 15, 20
126 | 
127 | 
128 |
129 | 130 | --- 131 | 132 |
133 | Task 3: Retrieve Ceiling and Floor 134 |
135 | 
136 | # Retrieve Ceiling and Floor
137 | ## Description:
138 | Given a TreeSet and an integer, retrieve and display the ceiling and floor of that integer from the TreeSet.
139 | 
140 | ### _Inputs & Outputs:_
141 | #### _Sample Input 1:_
142 | TreeSet: [5, 10, 15, 20, 25]
143 | Integer: 18
144 | 
145 | #### _Sample Output 1:_
146 | Ceiling: 20
147 | Floor: 15
148 | 
149 | #### _Sample Input 2:_
150 | TreeSet: [10, 30, 50, 70, 90]
151 | Integer: 45
152 | 
153 | #### _Sample Output 2:_
154 | Ceiling: 50
155 | Floor: 30
156 | 
157 | 
158 |
159 | 160 | --- 161 | 162 |
163 | Task 4: Custom Ordering with Strings 164 |
165 | 
166 | # Custom Ordering with Strings
167 | ## Description:
168 | Create a TreeSet with a custom comparator to store strings in reverse alphabetical order. Add some strings to it and then display them.
169 | 
170 | ### _Inputs & Outputs:_
171 | #### _Sample Input 1:_
172 | "Apple", "Banana", "Cherry"
173 | 
174 | #### _Sample Output 1:_
175 | Cherry, Banana, Apple
176 | 
177 | #### _Sample Input 2:_
178 | "Mango", "Peach", "Kiwi"
179 | 
180 | #### _Sample Output 2:_
181 | Peach, Mango, Kiwi
182 | 
183 | 
184 |
185 | 186 | --- 187 | 188 |
189 | Task 5: First and Last Elements 190 |
191 | 
192 | # First and Last Elements
193 | ## Description:
194 | Given a TreeSet, retrieve and display the first and last elements from it.
195 | 
196 | ### _Inputs & Outputs:_
197 | #### _Sample Input 1:_
198 | TreeSet: [5, 10, 15, 20, 25]
199 | 
200 | #### _Sample Output 1:_
201 | First: 5
202 | Last: 25
203 | 
204 | #### _Sample Input 2:_
205 | TreeSet: [10, 30, 50, 70, 90]
206 | 
207 | #### _Sample Output 2:_
208 | First: 10
209 | Last: 90
210 | 
211 | 
212 |
213 | 214 | -------------------------------------------------------------------------------- /readme.MD: -------------------------------------------------------------------------------- 1 | # Course on Java back-end developer from JAVAT 2 | Hi, my name is **Temirlan**. This course is created for those who want to learn programming in **Java**, 3 | but don't know anything about programming yet. 4 | 5 | ## About me 6 | I am a developer with experience in IT and teaching beginner programmers. Want to learn more about me or get in touch 7 | directly for mentorship or partnership? Visit my [LinkedIn profile](https://www.linkedin.com/in/temirlan100). 8 | 9 | ## Why Java? 10 | Java is one of the most popular programming languages in the world. It is used in many projects of different 11 | scale - from mobile applications to large corporate systems. Java allows you to develop solutions for various 12 | domains: finance, medicine, games, science and many others. Learning Java will open doors to the fascinating world of IT 13 | and many exciting opportunities 14 | 15 | ## Course Benefits 16 | - **Mentor support**: after completing the 'Java Core' module, each student will have the opportunity to receive support from a mentor. 17 | - **Collaborative project defence**: you will work on projects and present them for defence with other course participants or on your own. 18 | - **Mock interviews**: mock interviews are conducted to better prepare you for real interviews. 19 | - **Community Developer Meetings**: Meetings are organised with professional developers and other IT professionals to broaden your understanding of the industry and provide networking opportunities. 20 | 21 | # RoadMAP of the course 22 | ![roadmap](Img/ROADMAP.png) 23 | 24 | ## Course Structure 25 | ## **Java Core** 26 | ##### [Introduction to Java](JavaCore/lessons/hello_world.MD) 27 | - History and features of the Java language 28 | - Installing the JDK (Java Development Kit) 29 | - Installing IntelliJ IDEA 30 | - "Hello World!" - Your first Java programme 31 | 32 | ##### Basic language elements 33 | - [Scanning the input](JavaCore/lessons/linput_scanning.MD) 34 | - [Data types and Operators](JavaCore/lessons/data_types_operators.MD) 35 | - [Constants with `final` and code blocks and variable scope](JavaCore/lessons/final_blocks.MD) 36 | 37 | ##### Conditional operators 38 | - [`if-else` operator](JavaCore/lessons/if_else.MD) 39 | - [`switch` operator](JavaCore/lessons/switch.MD) 40 | 41 | ##### Loops 42 | - [Cycle `do-while`](JavaCore/lessons/do_while.MD) 43 | - [Cycle `while`](JavaCore/lessons/while.MD) 44 | - [Loop `for`](JavaCore/lessons/for_loop.MD) 45 | 46 | ##### Arrays 47 | - [Basics of working with arrays and the foreach loop](JavaCore/lessons/array.MD) 48 | - [Multidimensional Arrays](JavaCore/lessons/matrix.MD) 49 | 50 | ##### Collections 51 | - [Class `ArrayList`](JavaCore/lessons/list_arraylist.MD) 52 | - [Class `HashSet`](JavaCore/lessons/set_hashset.MD) 53 | - [Class `HashMap`](JavaCore/lessons/map_hashmap.MD) 54 | - [Class `TreeSet`](JavaCore/lessons/treeset.MD) 55 | - [Class `TreeMap`](JavaCore/lessons/treemap.MD) 56 | 57 | ##### Reading files 58 | - [Basic file operations](JavaCore/lessons/file_io.MD) 59 | 60 | ##### OOP Basics 61 | - [Introduction to OOP (Objects, Classes)](JavaCore/lessons/intro_oop.MD) 62 | - [Access modifiers](JavaCore/lessons/access_modifiers.MD) 63 | - [Inheritance](JavaCore/lessons/inheritance.MD) 64 | - [Abstract class and Interfaces](JavaCore/lessons/abstract_class_interface.MD) 65 | - [Polymorphism](JavaCore/lessons/polymorphism.MD) 66 | - [Encapsulation](JavaCore/lessons/encapsulation.MD) 67 | - [Static class elements](JavaCore/lessons/static.MD) 68 | - [Internal classes](JavaCore/lessons/internal_class.MD) 69 | - [Lambda expressions](JavaCore/lessons/lambda.MD) 70 | - [What is Enum class? How to use it and when to use it](JavaCore/lessons/enum.MD) 71 | 72 | ##### Exception Handling 73 | - [`try-catch` and `finally` blocks](JavaCore/lessons/try_catch_finally.MD) 74 | - [Creating your own exceptions](JavaCore/lessons/own_exception.MD) 75 | 76 | ##### Streams 77 | - [Streams in Java](JavaCore/lessons/streams.MD) 78 | 79 | ##### JavaDoc 80 | - [About JavaDoc](JavaCore/lessons/javadoc.MD) 81 | 82 | ##### Java Core module final projects 83 | - [ATM Simulator](JavaCore/lessons/atm_project.MD) 84 | 85 | 86 | ## **Java App + DB** 87 | ##### Introduction to Databases 88 | - [Understanding Databases: Types and Importance](db/lessons/database_intro.MD) 89 | - [Introduction to SQL Databases and setting Up a SQL Database Environment (SQLite)](db/lessons/sqllite_env.MD) 90 | - [Basics of Database Design and Normalization](db/lessons/db_normalization.MD) 91 | - [Task A: Set up a local SQL database environment using SQLite](db/tasks/sqlite_install.MD) 92 | 93 | ##### SQL Essentials 94 | - [Key SQL Statements: SELECT, INSERT, UPDATE, DELETE](db/lessons/siud_sql.MD) 95 | - [Understanding Tables, Keys, and Relationships](db/lessons/table_keys.MD) 96 | - [Advanced SQL Concepts: Joins, Conditions, Subqueries, Views, and Indexes](db/lessons/joins_conditions.MD) 97 | - [Stored Procedures and Triggers](db/lessons/procedures_triggers.MD) 98 | - [Task: Healthcare Database Management: A Practical SQL Learning Experience](db/tasks/sql_essentials.MD) 99 | 100 | ##### Java and Database Connectivity 101 | - [Introduction to JDBC (Java Database Connectivity)](db/lessons/jdbc.MD) 102 | - [Executing SQL Queries through Java](db/lessons/sql_jdbc.MD) 103 | - [Managing Database Transactions in Java](db/lessons/transactions.MD) 104 | - [Task: Establish a JDBC connection to the database created in SQLite with CRUD](db/tasks/jdbc_connection.MD) 105 | 106 | ##### Advanced Database Operations in Java 107 | - [Design Patterns for Database Access in Java (e.g., DAO Pattern)](db/lessons/view_service_dao.MD) 108 | - [Implementing CRUD Operations in Java Applications](db/lessons/crud.MD) 109 | - [Advanced JDBC Techniques and Optimizations](db/lessons/advance_jdbc_intro.MD) 110 | - [Task: Kindergarten Management System](db/tasks/advance_database_operations.MD) 111 | 112 | ##### Java App + DB module final projects 113 | - [LMS - Logistics Management System](db/projects/lms_project.MD) 114 | - [Automated Teller Machine (ATM) Management System](db/projects/atm_project.MD) 115 | 116 | 117 | ## **Spring** 118 | - [Module 1: Introduction to Spring Framework](spring/lessons/module_1.MD) 119 | - [Module 2: Spring Core Concepts](spring/lessons/module_2.MD) 120 | - [Module 3: Introduction to Spring Boot](spring/lessons/module_3.MD) 121 | - [Module 4: Building RESTFull Web Services with Spring Boot](spring/lessons/module_4.MD) 122 | - [Module 5: Data Access with Spring Data](spring/lessons/module_5.MD) 123 | - [Module 6: Securing Spring Applications with Spring Security](spring/lessons/module_6.MD) 124 | - [Module 7: Testing Spring Applications](spring/lessons/module_7.MD) 125 | 126 | ## **Spring module final projects** 127 | - [Automated Teller Machine (ATM)](spring/projects/project_1.MD) 128 | - [Telemedicine System](spring/projects/project_2.MD) 129 | - [Advanced Financial Services Management System](spring/projects/project_3.MD) 130 | 131 | ## Additional Opportunities 132 | In addition to learning the basics of programming, you will have the opportunity to get: 133 | - Test interview support. 134 | - Opportunities to participate in internships for those who successfully complete the course. 135 | - Leading graduates to an JO, on full completion of the course. 136 | 137 | ## Community 138 | We have a [Telegram group](https://t.me/javatgroup) where you can ask questions, 139 | discuss course material, and meet other enthusiasts. -------------------------------------------------------------------------------- /JavaCore/lessons/internal_class.MD: -------------------------------------------------------------------------------- 1 | ### Overview of Inner Classes in Java 2 | 3 | Inner classes in Java are defined within the scope of another class. They are useful for logically grouping classes that are only used in one place, increasing encapsulation, and creating more readable and maintainable code. 4 | 5 | There are four types of inner classes in Java: 6 | 7 | 1. **Member Inner Class:** A non-static class that is created inside a class but outside a method. 8 | 2. **Static Inner Class:** Similar to the member inner class but is static and cannot access non-static members of the outer class directly. 9 | 3. **Local Inner Class:** Class defined within a block or method. 10 | 4. **Anonymous Inner Class:** An inner class without a name and for which only a single object is created. 11 | 12 | ### Educational Material with Examples 13 | 14 | #### 1. Member Inner Class 15 | 16 | ```java 17 | class OuterClass { 18 | private String message = "Hello from Outer Class"; 19 | 20 | class InnerClass { 21 | void display() { 22 | System.out.println(message); // Accessing outer class member 23 | } 24 | } 25 | 26 | public void callInner() { 27 | InnerClass inner = new InnerClass(); 28 | inner.display(); 29 | } 30 | } 31 | 32 | public class Main { 33 | public static void main(String[] args) { 34 | OuterClass outer = new OuterClass(); 35 | outer.callInner(); // Displays: Hello from Outer Class 36 | } 37 | } 38 | ``` 39 | 40 | #### 2. Static Inner Class 41 | 42 | ```java 43 | class OuterClass { 44 | private static String staticMessage = "Hello from Static Inner Class"; 45 | 46 | static class StaticInner { 47 | void display() { 48 | System.out.println(staticMessage); // Accessing static member of outer class 49 | } 50 | } 51 | } 52 | 53 | public class Main { 54 | public static void main(String[] args) { 55 | OuterClass.StaticInner inner = new OuterClass.StaticInner(); 56 | inner.display(); // Displays: Hello from Static Inner Class 57 | } 58 | } 59 | ``` 60 | 61 | #### 3. Local Inner Class 62 | 63 | ```java 64 | class OuterClass { 65 | 66 | void outerMethod() { 67 | class LocalInner { 68 | void display() { 69 | System.out.println("Inside local inner class"); 70 | } 71 | } 72 | LocalInner localInner = new LocalInner(); 73 | localInner.display(); // Inside local inner class 74 | } 75 | } 76 | 77 | public class Main { 78 | public static void main(String[] args) { 79 | OuterClass outer = new OuterClass(); 80 | outer.outerMethod(); 81 | } 82 | } 83 | ``` 84 | 85 | #### 4. Anonymous Inner Class 86 | 87 | ```java 88 | interface Message { 89 | void display(); 90 | } 91 | 92 | class OuterClass { 93 | 94 | public void method() { 95 | Message message = new Message() { 96 | public void display() { 97 | System.out.println("Hello from Anonymous Inner Class"); 98 | } 99 | }; 100 | message.display(); // Hello from Anonymous Inner Class 101 | } 102 | } 103 | 104 | public class Main { 105 | public static void main(String[] args) { 106 | OuterClass outer = new OuterClass(); 107 | outer.method(); 108 | } 109 | } 110 | ``` 111 | 112 | ### Usage Tips 113 | - Inner classes are useful when a class is only useful to one other class. They help to logically group classes and control the visibility of variables and methods. 114 | - They can lead to more readable and maintainable code by encapsulating the functionality within the outer class. 115 | - However, overusing them can make the code more complex and harder to read, so it's important to use them judiciously. 116 | 117 | 118 | ### Recommended Resources 119 | - [Nested Classes](https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html#:~:text=it%20is%20used.-,Inner%20Classes,define%20any%20static%20members%20itself.) 120 | - [Java Inner Classes](https://www.w3schools.com/java/java_inner_classes.asp) 121 | - [Inner Classes (Nested Classes)](https://www.javatpoint.com/java-inner-class) 122 | - [Java - Inner classes](https://www.tutorialspoint.com/java/java_innerclasses.htm) 123 | - [Inner Class in Java](https://www.geeksforgeeks.org/inner-class-java) 124 | 125 | 126 | ## Tasks 127 | 128 |
129 | Task 1: Create a Member Inner Class 130 |
131 | 
132 | # Create a Member Inner Class
133 | ## Description:
134 | Create a member inner class named 'Inner' within a public class 'Outer'. The inner class should have a method `display()` that prints "Inner class called." Create an instance of the inner class within the outer class and call `display()` method.
135 | 
136 | ### _Inputs & Outputs:_
137 | #### _Sample Input 1:_
138 | No input required.
139 | 
140 | #### _Sample Output 1:_
141 | Inner class called.
142 | 
143 | 
144 |
145 | 146 | --- 147 | 148 |
149 | Task 2: Static Inner Class with Static Method 150 |
151 | 
152 | # Static Inner Class with Static Method
153 | ## Description:
154 | Create a static inner class named 'StaticInner' inside a class 'Outer'. The static inner class should contain a static method `sayHello()` that returns "Hello from Static Inner Class!" Access this method from a main method without creating an instance of 'Outer'.
155 | 
156 | ### _Inputs & Outputs:_
157 | #### _Sample Input 1:_
158 | No input required.
159 | 
160 | #### _Sample Output 1:_
161 | Hello from Static Inner Class!
162 | 
163 | 
164 |
165 | 166 | --- 167 | 168 |
169 | Task 3: Local Inner Class in a Method 170 |
171 | 
172 | # Local Inner Class in a Method
173 | ## Description:
174 | In a class 'LocalOuter', define a method 'localInnerDemo()' which contains a local inner class named 'LocalInner'. The local inner class should have a method `showMessage()` that prints "Local Inner Class Message." Call this method from within 'localInnerDemo()'.
175 | 
176 | ### _Inputs & Outputs:_
177 | #### _Sample Input 1:_
178 | No input required.
179 | 
180 | #### _Sample Output 1:_
181 | Local Inner Class Message.
182 | 
183 | 
184 |
185 | 186 | --- 187 | 188 |
189 | Task 4: Anonymous Inner Class Implementing an Interface 190 |
191 | 
192 | # Anonymous Inner Class Implementing an Interface
193 | ## Description:
194 | Create an interface 'Greeting' with a method `sayHello()`. In a class 'AnonymousDemo', create an anonymous inner class that implements 'Greeting', overriding `sayHello()` to return "Hello from Anonymous Inner Class!" Print the result of `sayHello()` in the main method.
195 | 
196 | ### _Inputs & Outputs:_
197 | #### _Sample Input 1:_
198 | No input required.
199 | 
200 | #### _Sample Output 1:_
201 | Hello from Anonymous Inner Class!
202 | 
203 | 
204 |
205 | 206 | --- 207 | 208 |
209 | Task 5: Accessing Outer Class Variables 210 |
211 | 
212 | # Accessing Outer Class Variables
213 | ## Description:
214 | Create a class 'Outer' with a private variable `privateString` initialized to "Accessed from Inner Class". Inside it, create a member inner class 'Inner' with a method `accessOuter()` which prints the value of `privateString` from the outer class.
215 | 
216 | ### _Inputs & Outputs:_
217 | #### _Sample Input 1:_
218 | No input required.
219 | 
220 | #### _Sample Output 1:_
221 | Accessed from Inner Class.
222 | 
223 | 
224 |
225 | 226 | --- 227 | 228 | -------------------------------------------------------------------------------- /db/projects/lms_project.MD: -------------------------------------------------------------------------------- 1 | ### Introduction to the Logistics Management System (LMS) Project 2 | In the modern world, logistics and supply chain efficiency are the backbones of businesses across the globe. 3 | As e-commerce continues to grow, the demand for sophisticated logistics solutions has never been higher. 4 | This presents a unique opportunity for technology and software development to play a pivotal role in transforming 5 | the logistics industry. The Logistics Management System (LMS) project is conceived as an educational venture into 6 | this dynamic and crucial sector. 7 | 8 | The LMS project aims to bridge the gap between theoretical knowledge and practical application by providing students 9 | with a hands-on experience in developing a real-world application. This project is designed to apply Java programming 10 | skills and database management concepts in a cohesive and practical manner, focusing on the challenges and needs of 11 | the logistics domain. 12 | 13 | #### The Essence of the LMS Project 14 | The logistics sector is characterized by its vast and intricate operations, involving inventory management, 15 | order processing, shipment tracking, and route optimization. These operations are critical for ensuring timely 16 | delivery of goods and services, maintaining inventory accuracy, and optimizing transportation routes for 17 | cost-effectiveness and efficiency. The LMS project encapsulates these core functions, providing a simulated 18 | yet realistic environment for students to explore and innovate. 19 | 20 | #### Project Goals 21 | The primary goal of the LMS project is to develop a system that is not only functional but also efficient, 22 | user-friendly, and adaptable to the changing demands of the logistics industry. Students will embark on a journey 23 | through the complete software development lifecycle, from requirements analysis and system design to implementation, 24 | testing, and deployment. This project is structured to encourage creative problem-solving, critical thinking, and 25 | collaboration, essential skills in the field of software development. 26 | 27 | #### Learning Through Doing 28 | By engaging with the LMS project, students will gain valuable insights into the practical aspects of database design, 29 | SQL query optimization, Java Database Connectivity (JDBC), and advanced Java programming techniques. The project is 30 | an opportunity to apply theoretical knowledge to real-world scenarios, preparing students for future challenges they 31 | may face in their careers. 32 | 33 | ### Functional Requirements for the Logistics Management System (LMS) 34 | 1. **Inventory Management** 35 | - **FR1.1:** The system must allow users to add, update, and delete product information, including name, description, quantity, and location (warehouse). 36 | - **FR1.2:** The system must automatically update inventory levels upon order processing (both incoming and outgoing orders). 37 | - **FR1.3:** The system should provide alerts for low stock levels based on predefined thresholds to trigger reorder processes. 38 | 39 | 2. **Order Processing** 40 | - **FR2.1:** The system must enable the creation of new customer orders, capturing customer details, order items, quantities, and delivery preferences. 41 | - **FR2.2:** The system should allow users to update order status through various stages: received, processed, shipped, and delivered. 42 | - **FR2.3:** The system must support the processing of returns and exchanges, including inventory adjustments and customer notifications. 43 | 44 | 3. **Shipment Tracking** 45 | - **FR3.1:** The system must provide real-time tracking of shipments, including current status and location, using unique tracking IDs. 46 | - **FR3.2:** The system should offer estimated delivery times based on the shipment's current location, destination, and historical data. 47 | - **FR3.3:** Customers should be able to access shipment tracking information through a web interface or API, using their order ID or tracking number. 48 | 49 | 4. **Route Optimization** 50 | - **FR4.1:** The system must analyze delivery routes and suggest the most efficient paths based on distance, expected traffic, and delivery urgency. 51 | - **FR4.2:** The system should allow manual override of suggested routes by logistics managers for flexibility in operations. 52 | - **FR4.3:** The system must update estimated delivery times based on the chosen route and real-time factors affecting delivery times. 53 | 54 | These functional requirements outline the core capabilities of the Logistics Management System, focusing on 55 | inventory management, order processing, shipment tracking, and route optimization. Implementing these features 56 | will require a robust database design, efficient SQL queries, and effective Java-JDBC integration for a seamless 57 | and user-friendly logistics management solution. 58 | 59 | ### Tips for Application Architecture (View-Service-DAO) 60 | 1. **Layered Architecture:** Emphasize the importance of separating concerns by using a layered architecture. This design principle enhances code maintainability, scalability, and ease of testing. 61 | 2. **View Layer:** The view layer should be responsible for user interaction only. In a console application, this would involve displaying menus, taking user inputs, and showing results. Tips for the view layer include keeping it simple and separate from the business logic and data access layers. 62 | 3. **Service Layer:** The service layer acts as a bridge between the view and DAO layers. It contains business logic and transaction management. Encourage students to: 63 | - Implement validation logic in the service layer. 64 | - Use this layer to manage transactions, ensuring data consistency and integrity. 65 | - Keep services focused on specific functionalities to promote reusability. 66 | 4. **DAO (Data Access Object) Layer:** The DAO layer is where the application interacts with the database. Tips for the DAO layer include: 67 | - Use DAOs to abstract and encapsulate all access to the data source. 68 | - DAOs should be responsible for performing CRUD operations, keeping them distinct from the business logic. 69 | - Encourage the use of prepared statements to prevent SQL injection attacks. 70 | 5. **Design Patterns:** Introduce design patterns relevant to each layer, such as Singleton for DAO implementations (to ensure only one instance accesses the database at a time) and the Facade pattern for the service layer (to provide a simplified interface to complex subsystems). 71 | 72 | ### Tips for Database Design 73 | 1. **Normalization:** Guide students to design a normalized database schema to eliminate data redundancy and ensure data integrity. However, also discuss when denormalization might be beneficial for performance reasons. 74 | 2. **Optimal Number of Tables:** For the LMS project, the optimal number of tables depends on the project scope but generally should include tables for: 75 | - Products/Items: To store information about the goods being managed. 76 | - Warehouses: To keep track of different storage locations. 77 | - Orders: To record customer orders, including order details and status. 78 | - Shipments: To manage shipment information, including tracking. 79 | - Additional tables for managing relationships (e.g., product-to-warehouse mappings) and other entities like customers or suppliers as needed. 80 | 3. **Foreign Keys and Indexes:** Use foreign keys to enforce referential integrity between tables. Indexes should be used judiciously to improve query performance, especially on columns that are frequently used in search conditions. 81 | 4. **Scalability Considerations:** While the project may start with a simple schema, discuss strategies for scaling the database as requirements grow, such as partitioning, indexing strategies, and the use of caching. 82 | 83 | ### General Advice 84 | - **Modularity:** Encourage students to keep their code modular. This approach simplifies understanding, debugging, and testing the application. 85 | - **Documentation:** Stress the importance of documenting the design and code. Good documentation is invaluable for maintenance and future development. 86 | - **Security:** Highlight the importance of considering security at every layer, especially when handling user input and managing database operations. 87 | -------------------------------------------------------------------------------- /JavaCore/lessons/own_exception.MD: -------------------------------------------------------------------------------- 1 | ### Introduction to Custom Exceptions in Java 2 | - **What are Exceptions?** 3 | - Briefly recap standard exceptions in Java, highlighting the importance of exception handling for robust software. 4 | 5 | - **Why Create Custom Exceptions?** 6 | - Discuss the need for more specific error handling. 7 | - Custom exceptions can make code more readable and maintainable. 8 | 9 | ### Understanding Exception Hierarchy 10 | - **Throwable Class**: The superclass of all errors and exceptions. 11 | - **Two Main Subclasses**: `Error` (used by JVM) and `Exception` (used by applications). 12 | - **Checked vs. Unchecked Exceptions**: Explain the difference and when to use each. 13 | 14 | ### Creating a Custom Exception 15 | 16 | - **Extending the Exception Class** 17 | - Show how to create a new class that extends either `Exception` (for checked exceptions) or `RuntimeException` (for unchecked exceptions). 18 | 19 | #### Example 1: A Simple Custom Exception 20 | ```java 21 | public class MyCustomException extends Exception { 22 | public MyCustomException(String message) { 23 | super(message); 24 | } 25 | } 26 | 27 | // Usage 28 | throw new MyCustomException("This is a custom message"); 29 | ``` 30 | 31 | #### Example 2: Adding Extra Functionality 32 | ```java 33 | public class DatabaseException extends Exception { 34 | private int errorCode; 35 | 36 | public DatabaseException(String message, int errorCode) { 37 | super(message); 38 | this.errorCode = errorCode; 39 | } 40 | 41 | public int getErrorCode() { 42 | return errorCode; 43 | } 44 | } 45 | 46 | // Usage 47 | throw new DatabaseException("Database connection failed", 500); 48 | ``` 49 | 50 | ### Integrating Custom Exceptions in Code 51 | - **Example Scenarios**: Provide a few scenarios or case studies where custom exceptions would be beneficial. 52 | - **Code Integration**: Show how to integrate these exceptions into existing code, including try-catch blocks. 53 | 54 | ### Further Reading 55 | - Suggest books or online resources for deeper understanding. 56 | - Link to official Java documentation on exceptions. 57 | 58 | ### Example: Custom Exception for Input Validation 59 | 60 | #### Scenario 61 | Imagine you have an application where you need to validate user input. If the input doesn't meet certain criteria, you want to throw an exception that specifically handles this scenario. 62 | 63 | #### Creating the Custom Exception 64 | First, create a custom exception class. In this case, we'll call it `InvalidInputException`. This exception is a checked exception, so it extends `Exception`. 65 | 66 | ```java 67 | public class InvalidInputException extends Exception { 68 | public InvalidInputException(String message) { 69 | super(message); 70 | } 71 | } 72 | ``` 73 | 74 | #### Explanation 75 | - `InvalidInputException` extends `Exception`, making it a checked exception. 76 | - The constructor accepts a `String` message, which can be used to provide detailed information about the validation error. 77 | 78 | #### Using the Custom Exception 79 | Now, let's use this exception in a method that validates a user's age. 80 | 81 | ```java 82 | public class UserInputValidator { 83 | 84 | public void validateAge(int age) throws InvalidInputException { 85 | if (age < 18) { 86 | throw new InvalidInputException("Age must be 18 or above."); 87 | } 88 | System.out.println("Age is valid."); 89 | } 90 | 91 | public static void main(String[] args) { 92 | UserInputValidator validator = new UserInputValidator(); 93 | try { 94 | validator.validateAge(16); 95 | } catch (InvalidInputException e) { 96 | System.err.println("Validation error: " + e.getMessage()); 97 | } 98 | } 99 | } 100 | ``` 101 | 102 | #### Explanation 103 | - The `validateAge` method throws `InvalidInputException` when the age is below 18. 104 | - In the `main` method, we create an instance of `UserInputValidator` and call `validateAge`. 105 | - We use a try-catch block to handle `InvalidInputException`. 106 | 107 | ### Best Practices and Integration 108 | - **Use Meaningful Names**: Name exceptions clearly to indicate their specific purpose. 109 | - **Avoid Overuse**: Only create custom exceptions when necessary. 110 | - **Documentation**: Always document custom exceptions to explain their purpose and usage. 111 | - Use this exception to enforce input validation rules throughout your application. 112 | - Ensure that the exception is caught and handled appropriately, providing meaningful feedback to the user or the calling method. 113 | 114 | ### Recommended Resources 115 | - [Java Custom Exception](https://www.javatpoint.com/custom-exception#:~:text=In%20order%20to%20create%20custom,belongs%20to%20java.lang%20package.&text=Consider%20the%20following%20example%2C%20where,public%20WrongFileNameException(String%20errorMessage)%20%7B) 116 | - [Create a Custom Exception in Java](https://www.baeldung.com/java-new-custom-exception) 117 | - [How can we create a custom exception in Java?](https://www.tutorialspoint.com/how-can-we-create-a-custom-exception-in-java) 118 | - [User-defined Custom Exception in Java](https://www.geeksforgeeks.org/user-defined-custom-exception-in-java) 119 | 120 | 121 | ## Tasks 122 | 123 |
124 | Task 1: Simple Custom Exception 125 |
126 | 
127 | # Simple Custom Exception
128 | ## Description:
129 | Create a custom exception called `SimpleException` that extends `Exception`. It should take a string message as its constructor argument.
130 | 
131 | ### _Inputs & Outputs:_
132 | #### _Sample Input 1:_
133 | Throw `SimpleException` with the message "Simple error occurred"
134 | 
135 | #### _Sample Output 1:_
136 | Exception message: "Simple error occurred"
137 | 
138 | 
139 |
140 | 141 | --- 142 | 143 |
144 | Task 2: Parameter Validation Exception 145 |
146 | 
147 | # Parameter Validation Exception
148 | ## Description:
149 | Create a custom exception named `ParameterValidationException`. Use this exception in a method `validateNumber` that takes an integer. If the number is negative, throw `ParameterValidationException`.
150 | 
151 | ### _Inputs & Outputs:_
152 | #### _Sample Input 1:_
153 | validateNumber(5)
154 | 
155 | #### _Sample Output 1:_
156 | No exception thrown
157 | 
158 | #### _Sample Input 2:_
159 | validateNumber(-3)
160 | 
161 | #### _Sample Output 2:_
162 | Exception message: "Negative numbers are not allowed."
163 | 
164 | 
165 |
166 | 167 | --- 168 | 169 |
170 | Task 3: Advanced Custom Exception 171 |
172 | 
173 | # Advanced Custom Exception
174 | ## Description:
175 | Create a custom exception `AdvancedException` that includes a constructor to pass a message and an error code. Write a method `processData` that throws `AdvancedException` with different messages and error codes based on various conditions.
176 | 
177 | ### _Inputs & Outputs:_
178 | #### _Sample Input 1:_
179 | processData(1)
180 | 
181 | #### _Sample Output 1:_
182 | Exception message: "Data is insufficient", Error Code: 100
183 | 
184 | #### _Sample Input 2:_
185 | processData(2)
186 | 
187 | #### _Sample Output 2:_
188 | Exception message: "Data is invalid", Error Code: 200
189 | 
190 | 
191 |
192 | 193 | --- 194 | 195 |
196 | Task 4: Custom Unchecked Exception 197 |
198 | 
199 | # Custom Unchecked Exception
200 | ## Description:
201 | Create a custom unchecked exception called `MyRuntimeException` that extends `RuntimeException`. Demonstrate its use in a scenario where it's thrown and caught.
202 | 
203 | ### _Inputs & Outputs:_
204 | #### _Sample Input 1:_
205 | A scenario where `MyRuntimeException` is thrown due to invalid user input.
206 | 
207 | #### _Sample Output 1:_
208 | Runtime exception caught with message: "Invalid user input."
209 | 
210 | 
211 |
212 | -------------------------------------------------------------------------------- /JavaCore/lessons/do_while.MD: -------------------------------------------------------------------------------- 1 | ## **do-while Loop in Java** 2 | 3 | ### **Introduction** 4 | The `do-while` loop is one of the looping constructs available in Java. It is similar to the `while` loop but with a key difference: the condition is evaluated **after** the loop body executes. This guarantees that the loop will execute its body at least once. 5 | 6 | ### **Syntax** 7 | ```java 8 | do { 9 | // code to be executed 10 | } while (condition); 11 | ``` 12 | 13 | ### **How It Works** 14 | 1. The code inside the loop executes once. 15 | 2. The condition is checked. 16 | 3. If the condition is `true`, the loop will execute again. If the condition is `false`, the loop will exit and the program will continue with the statements following the loop. 17 | 18 | ### **Key Point** 19 | The `do-while` loop will **always execute the loop body at least once**, regardless of the condition. This is because the condition is checked **after** the loop body has been executed. 20 | 21 | ### **Example** 22 | Consider a scenario where you want to prompt a user to enter a positive number. Using a `do-while` loop ensures that the user is prompted at least once: 23 | 24 | ```java 25 | import java.util.Scanner; 26 | 27 | public class DoWhileExample { 28 | 29 | public static void main(String[] args) { 30 | Scanner scanner = new Scanner(System.in); 31 | int number; 32 | 33 | do { 34 | System.out.println("Enter a positive number:"); 35 | number = scanner.nextInt(); 36 | } while (number <= 0); 37 | 38 | System.out.println("You entered: " + number); 39 | } 40 | } 41 | ``` 42 | 43 | In the above code: 44 | 45 | - We prompt the user to enter a positive number. 46 | - If the user enters a non-positive number, they are prompted again. 47 | - This continues until the user enters a positive number. 48 | 49 | ### **When to Use the do-while Loop** 50 | You should use the `do-while` loop when you want the loop body to execute at least once, regardless of the initial condition. It is especially useful in situations where an initial action is required before a condition can be evaluated (like reading user input). 51 | 52 | --- 53 | 54 | ### **Example 1: Simple Counter with if Condition** 55 | 56 | In this example, we'll increment a counter and print its value. If the counter reaches a certain value, we'll break out of the loop using an `if` condition: 57 | 58 | ```java 59 | public class DoWhileWithIfExample { 60 | 61 | public static void main(String[] args) { 62 | int counter = 1; 63 | 64 | do { 65 | System.out.println("Counter value: " + counter); 66 | 67 | if (counter >= 5) { 68 | System.out.println("Counter reached 5. Exiting loop."); 69 | break; 70 | } 71 | 72 | counter++; 73 | } while (true); 74 | } 75 | } 76 | ``` 77 | 78 | Here, the loop will keep executing indefinitely (`while(true)`), but we use the `if` condition to break out of it once the counter reaches or exceeds the value of 5. 79 | 80 | --- 81 | 82 | ### **Example 2: Menu Selection** 83 | 84 | In this example, we present a simple menu to the user and prompt them for a choice. If the user chooses to exit, the loop will terminate. Otherwise, the user will be shown the menu again: 85 | 86 | ```java 87 | import java.util.Scanner; 88 | 89 | public class MenuSelectionExample { 90 | 91 | public static void main(String[] args) { 92 | Scanner scanner = new Scanner(System.in); 93 | int choice; 94 | 95 | do { 96 | System.out.println("---- Menu ----"); 97 | System.out.println("1. Option One"); 98 | System.out.println("2. Option Two"); 99 | System.out.println("3. Exit"); 100 | System.out.print("Enter your choice: "); 101 | 102 | choice = scanner.nextInt(); 103 | 104 | switch(choice) { 105 | case 1: 106 | System.out.println("You selected Option One."); 107 | break; 108 | case 2: 109 | System.out.println("You selected Option Two."); 110 | break; 111 | case 3: 112 | System.out.println("Exiting..."); 113 | break; 114 | default: 115 | System.out.println("Invalid choice. Please select again."); 116 | } 117 | 118 | } while (choice != 3); 119 | 120 | System.out.println("Program terminated."); 121 | } 122 | } 123 | ``` 124 | 125 | In this example, the `do-while` loop ensures that the menu is displayed at least once. If the user doesn't choose to exit, they are shown the menu again, ensuring that invalid choices won't terminate the program prematurely. 126 | 127 | ### Recommended Resources 128 | - [Java do-while Loop](https://www.javatpoint.com/java-do-while-loop) 129 | - [Java do-while loop with Examples](https://www.geeksforgeeks.org/java-do-while-loop-with-examples) 130 | - [Java do while loop](https://www.digitalocean.com/community/tutorials/java-do-while-loop) 131 | 132 | ## Tasks 133 | 134 |
135 | Task 1 136 |
137 | 
138 | # **Temperature Converter**
139 | ## **Description:**
140 | Write a Java program that converts temperatures between Fahrenheit and Celsius using a `do-while` loop. The formulas to convert between the two are:
141 | - Fahrenheit to Celsius: \( C = (F - 32) \times \frac{5}{9} \)
142 | - Celsius to Fahrenheit: \( F = C \times \frac{9}{5} + 32 \)
143 | 
144 | The user should be able to choose the conversion direction (from Fahrenheit to Celsius or from Celsius to Fahrenheit) and then input the temperature value. The program should then display the converted temperature. The user should be prompted to make conversions as many times as they want until they decide to exit.
145 | 
146 | ### _Inputs & Outputs:_
147 | #### _Sample Input 1:_
148 | Choose conversion direction (FtoC/CtoF): FtoC  
149 | Enter the temperature in Fahrenheit: 98.6
150 | #### _Sample Output 1:_
151 | The temperature in Celsius is 37.00°C.
152 | 
153 | #### _Sample Input 2:_
154 | Choose conversion direction (FtoC/CtoF): CtoF  
155 | Enter the temperature in Celsius: 100
156 | #### _Sample Output 2:_
157 | The temperature in Fahrenheit is 212.00°F.
158 | 
159 |
160 | 161 | --- 162 | 163 |
164 | Task 2 165 |
166 | 
167 | # **Password Validator**
168 | ## **Description:**
169 | Write a Java program that prompts users to enter a password using a `do-while` loop.
170 | The password should have at least 8 characters, one uppercase letter, one lowercase letter, and one number.
171 | If the password doesn't meet these criteria, inform the user about the shortcomings and prompt them again.
172 | Continue this process until the user enters a valid password.
173 | ### _Input:_
174 | password123
175 | ### _Output:_
176 | Password should contain at least one uppercase letter.
177 | ### _Input:_
178 | Password
179 | ### _Output:_
180 | Password should contain at least one number.
181 | ### _Input:_
182 | Password123
183 | ### _Output:_
184 | Password accepted.
185 | 
186 |
187 | 188 | --- 189 | 190 |
191 | Task 3 192 |
193 | 
194 | # **Number Summation**
195 | ## **Description:**
196 | Using a `do-while` loop, create a Java program that prompts the user to enter numbers continuously. The program should sum all the numbers entered by the user. The process should continue until the user enters a negative number. Once a negative number is entered, the program should display the sum of all previously entered numbers (excluding the negative number) and then terminate.
197 | 
198 | Remember: The loop should ensure that the user is prompted at least once.
199 | 
200 | ### _Inputs & Outputs:_
201 | #### _Sample Input 1:_
202 | Enter a number: 5  
203 | Enter a number: 6  
204 | Enter a number: 7  
205 | Enter a number: -1
206 | #### _Sample Output 1:_
207 | The sum of the numbers is 18.
208 | 
209 | #### _Sample Input 2:_
210 | Enter a number: 10  
211 | Enter a number: -5
212 | #### _Sample Output 2:_
213 | The sum of the numbers is 10.
214 | 
215 |
216 | -------------------------------------------------------------------------------- /spring/lessons/module_3.MD: -------------------------------------------------------------------------------- 1 | 2 | # Module 3: Introduction to Spring Boot 3 | 4 | ## 3.1 Overview of Spring Boot 5 | 6 | Spring Boot simplifies the development of Spring applications by providing defaults and auto-configuration options. It's designed to get you up and running quickly with minimal configuration. 7 | 8 | ### Key Features of Spring Boot 9 | - **Convention over Configuration:** Defaults and assumptions to reduce setup complexity. 10 | - **Embedded Servers:** Inbuilt servers like Tomcat for easy web development. 11 | - **Auto-configuration:** Automatic setup based on included dependencies. 12 | - **Standalone Applications:** Directly run applications without deploying to a web server. 13 | 14 | ## 3.2 Setting Up Spring Boot 15 | 16 | ### Getting Started with Spring Boot 17 | Use [Spring Initializr](https://start.spring.io/) to create a new Spring Boot project with Java and Maven or Gradle. Import this project into your IDE to begin development. 18 | 19 | #### Project Structure 20 | - `src/main/java/`: Contains Java code. 21 | - `src/main/resources/`: Holds resources (properties files, static contents). 22 | - `pom.xml` or `build.gradle`: Manages project dependencies and configurations. 23 | 24 | ### Hello World Application 25 | Create a basic application to display "Hello, World!" in the console. 26 | 27 | ```java 28 | import org.springframework.boot.SpringApplication; 29 | import org.springframework.boot.autoconfigure.SpringBootApplication; 30 | 31 | @SpringBootApplication 32 | public class ConsoleApplication { 33 | 34 | public static void main(String[] args) { 35 | SpringApplication.run(ConsoleApplication.class, args); 36 | System.out.println("Hello, World!"); 37 | } 38 | } 39 | ``` 40 | 41 | ## 3.3 Spring Boot Core Concepts 42 | 43 | ### Auto-configuration 44 | Spring Boot auto-configures the setup based on the dependencies you include, streamlining application development. 45 | 46 | ### Spring Boot Starters 47 | Starters are pre-configured sets of dependencies that cater to specific development needs. 48 | 49 | ## 3.4 Practical Task: In-Memory Medical Record Management 50 | 51 | Create a simple console application to manage medical records using in-memory data storage. 52 | 53 | ### Task Description 54 | Develop a console-based Java application using Spring Boot, which allows adding, viewing, and deleting patient records stored in-memory. 55 | 56 | ### Implementation Steps 57 | 58 | 1. **Define a Patient Model:** 59 | Create a `Patient` class to represent patient records. 60 | 61 | ```java 62 | public class Patient { 63 | private String id; 64 | private String name; 65 | private int age; 66 | 67 | // Constructor, getters, and setters 68 | } 69 | ``` 70 | 71 | 2. **Create a Patient Service:** 72 | Implement business logic for managing patient records. 73 | 74 | ```java 75 | import java.util.HashMap; 76 | import java.util.Map; 77 | 78 | public class PatientService { 79 | private final Map patients = new HashMap<>(); 80 | 81 | public void addPatient(Patient patient) { 82 | patients.put(patient.getId(), patient); 83 | System.out.println("Added patient: " + patient.getName()); 84 | } 85 | 86 | public void listPatients() { 87 | patients.values().forEach(patient -> 88 | System.out.println(patient.getId() + " - " + patient.getName())); 89 | } 90 | 91 | // Methods for updating and deleting patients 92 | } 93 | ``` 94 | 95 | 3. **Create Application Runner:** 96 | Use `CommandLineRunner` to interact with the console. 97 | 98 | ```java 99 | import org.springframework.boot.CommandLineRunner; 100 | import org.springframework.stereotype.Component; 101 | 102 | @Component 103 | public class AppRunner implements CommandLineRunner { 104 | 105 | private final PatientService patientService = new PatientService(); 106 | 107 | @Override 108 | public void run(String... args) { 109 | // Add some patients 110 | patientService.addPatient(new Patient("1", "John Doe", 30)); 111 | patientService.addPatient(new Patient("2", "Jane Roe", 25)); 112 | 113 | // List all patients 114 | patientService.listPatients(); 115 | } 116 | } 117 | ``` 118 | 119 | ### Conclusion 120 | This task helps understand basic Spring Boot concepts and Java programming by developing a simple in-memory application for medical record management. 121 | 122 | ### Recommended Resources 123 | - [spring-boot-docs](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#getting-started) 124 | - [What is Java Spring Boot?](https://www.ibm.com/topics/java-spring-boot) 125 | 126 | ### Practical Exercise: In-Memory Patient Management System 127 | #### Objective: 128 | Develop a console-based Java application using Spring Boot that manages patient records in-memory. The application should allow adding, updating, viewing, and deleting patient information. 129 | 130 | #### Tools and Technologies: 131 | - Java 132 | - Spring Boot 133 | - Maven or Gradle 134 | 135 | #### Requirements: 136 | 1. **Patient Model:** 137 | Create a `Patient` class with the following properties: 138 | - `id` (String) 139 | - `name` (String) 140 | - `age` (int) 141 | - `condition` (String) – describes the patient's medical condition 142 | 143 | 2. **Patient Service:** 144 | Implement a service class (`PatientService`) that manages the in-memory storage and manipulation of patient records. It should support the following operations: 145 | - Add a new patient 146 | - Update an existing patient's information 147 | - View a patient's details 148 | - Delete a patient record 149 | - List all patients 150 | 151 | 3. **Console Interface:** 152 | Use `CommandLineRunner` to interact with the user through the console. Provide a simple menu-driven interface to perform the following actions: 153 | - Add a new patient record 154 | - Update an existing patient record 155 | - View a patient's details 156 | - Delete a patient record 157 | - List all patients 158 | - Exit the program 159 | 160 | #### Implementation Steps: 161 | 1. **Set up a Spring Boot Project:** 162 | - Use Spring Initializr to generate a new Spring Boot project. 163 | - Choose appropriate dependencies (Spring Boot Starter). 164 | 2. **Implement the Patient Model:** 165 | - Create the `Patient` class with the specified properties and methods (getters and setters). 166 | 3. **Develop the Patient Service:** 167 | - Implement the `PatientService` class with methods to add, update, view, delete, and list patients. 168 | - Use a `HashMap` or similar data structure to store patient records in memory. 169 | 4. **Create the Console Interface:** 170 | - Implement `CommandLineRunner` in a class, providing a menu and handling user input to interact with the `PatientService`. 171 | 5. **Testing:** 172 | - Run the application and test each menu option to ensure the application correctly manages the patient records in-memory. 173 | 174 | #### Example Code Snippets: 175 | - **Patient Class:** 176 | ```java 177 | public class Patient { 178 | private String id; 179 | private String name; 180 | private int age; 181 | private String condition; 182 | 183 | // Constructor, getters, and setters 184 | } 185 | ``` 186 | 187 | - **PatientService Class:** 188 | ```java 189 | import java.util.HashMap; 190 | import java.util.Map; 191 | 192 | public class PatientService { 193 | private final Map patients = new HashMap<>(); 194 | 195 | public void addPatient(Patient patient) { 196 | patients.put(patient.getId(), patient); 197 | } 198 | 199 | // Implement other methods 200 | } 201 | ``` 202 | 203 | - **Console Interface with CommandLineRunner:** 204 | ```java 205 | import org.springframework.boot.CommandLineRunner; 206 | import org.springframework.stereotype.Component; 207 | 208 | @Component 209 | public class ConsoleApplication implements CommandLineRunner { 210 | 211 | private final PatientService patientService = new PatientService(); 212 | 213 | @Override 214 | public void run(String... args) throws Exception { 215 | // Implement console interaction logic 216 | } 217 | } 218 | ``` 219 | 220 | -------------------------------------------------------------------------------- /JavaCore/lessons/static.MD: -------------------------------------------------------------------------------- 1 | ### Understanding Static Elements in Java 2 | 3 | In Java, the keyword `static` is used to denote elements of a class that are shared among all instances of the class. 4 | These elements belong to the class itself, rather than to any particular object instance. 5 | 6 | #### 1. Static Variables 7 | - **Definition**: Also known as static fields or class variables, they are shared among all instances of the class. 8 | - **Usage**: They are typically used for constants or variables that should be consistent across all instances. 9 | - **Example**: 10 | ```java 11 | class MyClass { 12 | static int counter = 0; // Static variable 13 | 14 | MyClass() { 15 | counter++; 16 | } 17 | } 18 | ``` 19 | - **Deeper Insight**: A static variable gets memory only once in the class area at the time of class loading. It makes it a common property for all objects (instances) of that class. This is why changing the value of a static variable by one object affects all other instances. 20 | - **Extended Example**: 21 | ```java 22 | class Student { 23 | static String schoolName = "Global High"; // Common for all students 24 | String name; // Individual for each student 25 | 26 | Student(String name) { 27 | this.name = name; 28 | } 29 | 30 | void displayInfo() { 31 | System.out.println(name + " studies in " + schoolName); 32 | } 33 | } 34 | ``` 35 | 36 | #### 2. Static Methods 37 | - **Definition**: Methods declared with the `static` keyword belong to the class, not to any specific instance. 38 | - **Usage**: Often used for utility or helper methods that don't require any object state. 39 | - **Example**: 40 | ```java 41 | class MathUtils { 42 | static int add(int a, int b) { 43 | return a + b; 44 | } 45 | } 46 | // Can be called as MathUtils.add(5, 3) 47 | ``` 48 | - **Deeper Insight**: They cannot directly access instance variables or instance methods. They are often used for operations that don't require any data from an instance of the class (from `this`). 49 | - **Static and Non-static Together**: 50 | ```java 51 | class Calculator { 52 | static int add(int a, int b) { 53 | return a + b; 54 | } 55 | 56 | int multiply(int a, int b) { 57 | return a * b; 58 | } 59 | } 60 | // Static method called without an object: Calculator.add(5, 3) 61 | // Non-static method called with an object: new Calculator().multiply(5, 3) 62 | ``` 63 | 64 | #### 3. Static Blocks 65 | - **Definition**: Static blocks are used for static initialization of a class. This block gets executed when the class is loaded into memory. 66 | - **Usage**: Useful for complex initialization that can't be handled in a single statement. 67 | - **Example**: 68 | ```java 69 | class Config { 70 | static int configValue; 71 | 72 | static { 73 | // Initialize static variables or perform static operations 74 | configValue = fetchConfigFromDatabase(); 75 | } 76 | } 77 | ``` 78 | - **Deeper Insight**: Static blocks are executed before the main method, at the time of class loading. It's mainly used for initializing static variables. It can't access non-static data (variables and methods). 79 | - **Extended Example**: 80 | ```java 81 | class DatabaseConnector { 82 | static String dbURL; 83 | 84 | static { 85 | // This block of code is executed once when the class is loaded. 86 | dbURL = System.getenv("DATABASE_URL"); 87 | } 88 | } 89 | ``` 90 | 91 | #### 4. Static Inner Classes 92 | - **Definition**: Nested classes declared as static are called static nested classes. 93 | - **Usage**: Useful when a nested class doesn't need access to an instance of the outer class. 94 | - **Example**: 95 | ```java 96 | class Outer { 97 | static class Nested { 98 | int nestedVar = 0; 99 | } 100 | } 101 | // Can be instantiated as Outer.Nested nestedInstance = new Outer.Nested(); 102 | ``` 103 | - **Deeper Insight**: A static inner class is associated with its outer class. Unlike inner classes, it doesn't need a reference to an instance of the outer class. It can access static data members of the outer class including private ones. 104 | - **Extended Example**: 105 | ```java 106 | class Outer { 107 | private static String msg = "Hello"; 108 | 109 | static class Inner { 110 | void display() { 111 | System.out.println(msg); // Can access outer class's static variable 112 | } 113 | } 114 | } 115 | Outer.Inner innerObj = new Outer.Inner(); 116 | innerObj.display(); 117 | ``` 118 | 119 | ### Key Points to Remember 120 | - Static elements are shared across all instances of the class. 121 | - They are used for elements that logically belong to the type itself, rather than to instances of the type. 122 | - Static methods can’t access instance methods and instance variables directly; they need an object reference. 123 | - Static blocks and variables are initialized in the order they appear in a class. 124 | - **When to Use Static Variables**: For shared properties (like configuration settings, constants). 125 | - **When to Use Static Methods**: For utility or helper methods; methods that don't require any object state. 126 | - **Considerations**: 127 | - Overusing static can lead to issues with object-oriented design principles, as it promotes state sharing which can complicate testing and debugging. 128 | - Static methods can't be overridden, but they can be hidden by another static method in a subclass. 129 | 130 | ### Use Cases 131 | - Constants (`static final` variables). 132 | - Utility functions that don't require object state. 133 | - Counters shared across all instances of a class. 134 | 135 | 136 | ### Recommended Resources 137 | - [Static in Java: An Overview of Static Keyword With Examples](https://www.simplilearn.com/tutorials/java-tutorial/static-keyword-in-java#:~:text=Static%20keyword%20in%20java%20in,create%20one%20instance%20of%20it.) 138 | - [Java static keyword](https://www.javatpoint.com/static-keyword-in-java) 139 | - [static Keyword](https://www.w3schools.com/java/ref_keyword_static.asp) 140 | - [static Keyword in Java](https://www.geeksforgeeks.org/static-keyword-java) 141 | - [A Guide to the Static Keyword in Java](https://www.baeldung.com/java-static) 142 | 143 | 144 | ## Tasks 145 | 146 |
147 | Task 1: Static Counter 148 |
149 | 
150 | # Static Counter
151 | ## Description:
152 | Create a class 'Counter' with a static variable 'count' and a constructor that increments this count each time a new object is created. Write a main method to demonstrate this.
153 | 
154 | ### _Inputs & Outputs:_
155 | #### _Sample Input 1:_
156 | Create 3 objects of Counter class.
157 | 
158 | #### _Sample Output 1:_
159 | Count: 3
160 | 
161 | #### _Sample Input 2:_
162 | Create 5 objects of Counter class.
163 | 
164 | #### _Sample Output 2:_
165 | Count: 5
166 | 
167 | 
168 |
169 | 170 | --- 171 | 172 |
173 | Task 2: Static Utility Method 174 |
175 | 
176 | # Static Utility Method
177 | ## Description:
178 | Implement a static method 'findMax' in a class 'ArrayOperations' that takes an array of integers and returns the maximum value.
179 | 
180 | ### _Inputs & Outputs:_
181 | #### _Sample Input 1:_
182 | [3, 5, 9, 1, 2]
183 | 
184 | #### _Sample Output 1:_
185 | 9
186 | 
187 | #### _Sample Input 2:_
188 | [10, 21, 4, 18, 6]
189 | 
190 | #### _Sample Output 2:_
191 | 21
192 | 
193 | 
194 |
195 | 196 | --- 197 | 198 |
199 | Task 3: Static Initialization Block 200 |
201 | 
202 | # Static Initialization Block
203 | ## Description:
204 | Create a class 'DatabaseConfig' with a static block to initialize a static variable 'dbURL' with a value. Display this value in a main method.
205 | 
206 | ### _Inputs & Outputs:_
207 | #### _Sample Input 1:_
208 | Run the main method.
209 | 
210 | #### _Sample Output 1:_
211 | Database URL: [The initialized URL]
212 | 
213 | 
214 |
215 | 216 | --- 217 | 218 |
219 | Task 4: Static Inner Class 220 |
221 | 
222 | # Static Inner Class
223 | ## Description:
224 | Create a class 'Outer' with a private static variable. Inside it, create a static inner class 'Inner' with a method to display the outer class's variable. Demonstrate this in a main method.
225 | 
226 | ### _Inputs & Outputs:_
227 | #### _Sample Input 1:_
228 | Create an object of the inner class and call its display method.
229 | 
230 | #### _Sample Output 1:_
231 | Value of the outer class's variable.
232 | 
233 | 
234 |
235 | 236 | -------------------------------------------------------------------------------- /spring/lessons/module_1.MD: -------------------------------------------------------------------------------- 1 | ### Module 1: Introduction to Spring Framework 2 | 3 | #### Theoretical Part 4 | 5 | **1. Introduction to Spring Framework** 6 | Spring Framework is an essential platform for developing Java-based applications, offering comprehensive infrastructure support. It facilitates building, deploying, and maintaining complex applications with ease. 7 | 8 | **2. Core Concepts of Spring** 9 | - **Inversion of Control (IoC):** Central to Spring, IoC shifts the responsibility of managing components from the application code to the framework, promoting loose coupling and flexibility. 10 | - **Dependency Injection (DI):** A form of IoC, DI allows Spring to inject dependencies into components, simplifying management and configuration. 11 | 12 | **3. Architecture of Spring Framework** 13 | Spring’s modular architecture includes: 14 | - **Core Container:** Foundation of the framework, providing IoC and DI features. 15 | - **AOP and Instrumentation:** Supports aspect-oriented programming including cross-cutting concerns. 16 | - **Data Access/Integration:** Facilitates interaction with databases and transaction management. 17 | - **Web and Web MVC:** Forms the basis for web applications in Spring, including RESTful services. 18 | 19 | **4. Advantages of Using Spring** 20 | Benefits include: 21 | - Reduced boilerplate code 22 | - Improved application scalability and maintainability 23 | - Robust abstraction layers allowing for easy integration with other frameworks. 24 | 25 | #### Practical Exercise 26 | 27 | **Setting Up IntelliJ IDEA** 28 | - Download and install IntelliJ IDEA if not already installed. 29 | - Ensure you have the Java Development Kit (JDK) installed, version 8 or above. 30 | 31 | **Creating a Spring Boot Application** 32 | - Open IntelliJ IDEA and select "New Project". 33 | - Choose "Spring Initializr" from the options on the left and set up the project SDK (Java version). 34 | - Fill in the project metadata (Group, Artifact, Name) and select "Spring Web" as the dependency. 35 | - Click "Finish" to generate the project. 36 | 37 | **Hello, Spring! Application** 38 | Navigate to `src/main/java` in your project, find the main application class (named as per your project, e.g., `HelloSpringApplication`), and enter the following code: 39 | 40 | ```java 41 | import org.springframework.boot.SpringApplication; 42 | import org.springframework.boot.autoconfigure.SpringBootApplication; 43 | 44 | @SpringBootApplication 45 | public class HelloSpringApplication { 46 | public static void main(String[] args) { 47 | SpringApplication.run(HelloSpringApplication.class, args); 48 | } 49 | } 50 | ``` 51 | 52 | **Exploring Beans and ApplicationContext** 53 | Define a `GreetingService` class in the `service` package and annotate it with `@Service`: 54 | 55 | ```java 56 | import org.springframework.stereotype.Service; 57 | 58 | @Service 59 | public class GreetingService { 60 | public String getGreeting() { 61 | return "Welcome to Spring!"; 62 | } 63 | } 64 | ``` 65 | 66 | Inject this service into a component that uses it, such as a command-line runner: 67 | 68 | ```java 69 | import org.springframework.beans.factory.annotation.Autowired; 70 | import org.springframework.boot.CommandLineRunner; 71 | import org.springframework.stereotype.Component; 72 | 73 | @Component 74 | public class AppRunner implements CommandLineRunner { 75 | @Autowired 76 | private GreetingService greetingService; 77 | 78 | @Override 79 | public void run(String... args) { 80 | System.out.println(greetingService.getGreeting()); 81 | } 82 | } 83 | ``` 84 | 85 | **Configuration and Properties** 86 | Utilize `src/main/resources/application.properties` to manage application settings. For example, to change the server port: 87 | 88 | ``` 89 | server.port=8082 90 | ``` 91 | 92 | #### Conclusion and Next Steps 93 | This module introduced you to the Spring Framework, highlighting its core concepts, architecture, and benefits. The practical exercise aimed to give a hands-on experience in setting up a basic Spring Boot application. 94 | 95 | #### Assignment 96 | Enhance the `GreetingService` to read a message from `application.properties` and display that message when the application runs. This will introduce you to property management in Spring applications. 97 | 98 | ### Recommended Resources 99 | - [Spring Modules](https://www.javatpoint.com/spring-modules) 100 | - [Spring Example](https://www.javatpoint.com/steps-to-create-spring-application) 101 | - [IoC Container](https://www.javatpoint.com/ioc-container) 102 | - [Dependency Injection](https://www.javatpoint.com/dependency-injection-in-spring) 103 | 104 | ### Practical Exercise: In-Memory Task Manager Console Application 105 | **Objective:** 106 | Develop a console-based task manager application using Spring Boot, which allows adding, retrieving, and deleting tasks stored in memory. 107 | **Requirements:** 108 | - IntelliJ IDEA with Spring Boot setup. 109 | - Understanding of basic Spring concepts like dependency injection and beans. 110 | **Task Overview:** 111 | Create an application that manages tasks in memory (using a `List` or `Map`) and allows interaction through the console (standard input/output). 112 | 113 | #### Step 1: Set Up the Project 114 | - Start a new Spring Boot project in IntelliJ IDEA, using Spring Initializr. 115 | - Choose Maven as the build tool and Java as the language. 116 | 117 | #### Step 2: Define the Task Model 118 | - In the `model` package, create a `Task` class with fields like `id`, `name`, and `completed`. 119 | ```java 120 | package com.yourdomain.project.model; 121 | 122 | public class Task { 123 | private Long id; 124 | private String name; 125 | private boolean completed; 126 | 127 | // Constructors, getters, and setters 128 | } 129 | ``` 130 | 131 | #### Step 3: Create the Task Service 132 | - In the `service` package, create a `TaskService` class to manage the in-memory list of tasks. 133 | - Implement methods to add, retrieve, and delete tasks. 134 | ```java 135 | package com.yourdomain.project.service; 136 | 137 | import com.yourdomain.project.model.Task; 138 | import org.springframework.stereotype.Service; 139 | 140 | import java.util.ArrayList; 141 | import java.util.List; 142 | import java.util.concurrent.atomic.AtomicLong; 143 | 144 | @Service 145 | public class TaskService { 146 | private final List tasks = new ArrayList<>(); 147 | private final AtomicLong counter = new AtomicLong(); 148 | 149 | public Task addTask(String name) { 150 | Task task = new Task(); 151 | task.setId(counter.incrementAndGet()); 152 | task.setName(name); 153 | task.setCompleted(false); 154 | tasks.add(task); 155 | return task; 156 | } 157 | 158 | public List getAllTasks() { 159 | return tasks; 160 | } 161 | 162 | public void deleteTask(Long taskId) { 163 | tasks.removeIf(task -> task.getId().equals(taskId)); 164 | } 165 | } 166 | ``` 167 | 168 | #### Step 4: Create a Command-Line Runner 169 | - Implement a command-line runner in your main application class to interact with the `TaskService`. 170 | ```java 171 | import com.yourdomain.project.service.TaskService; 172 | import org.springframework.beans.factory.annotation.Autowired; 173 | import org.springframework.boot.CommandLineRunner; 174 | import org.springframework.stereotype.Component; 175 | 176 | import java.util.Scanner; 177 | 178 | @Component 179 | public class TaskManagerRunner implements CommandLineRunner { 180 | @Autowired 181 | private TaskService taskService; 182 | 183 | @Override 184 | public void run(String... args) throws Exception { 185 | Scanner scanner = new Scanner(System.in); 186 | while (true) { 187 | System.out.println("Enter 1 to add a task, 2 to view tasks, 3 to delete a task, 4 to exit"); 188 | int input = scanner.nextInt(); 189 | switch (input) { 190 | case 1: 191 | System.out.println("Enter task name:"); 192 | scanner.nextLine(); // Consume newline left-over 193 | String name = scanner.nextLine(); 194 | taskService.addTask(name); 195 | break; 196 | case 2: 197 | System.out.println("Tasks:"); 198 | taskService.getAllTasks().forEach(task -> System.out.println(task.getId() + ": " + task.getName())); 199 | break; 200 | case 3: 201 | System.out.println("Enter task ID to delete:"); 202 | Long taskId = scanner.nextLong(); 203 | taskService.deleteTask(taskId); 204 | break; 205 | case 4: 206 | System.out.println("Exiting..."); 207 | return; 208 | default: 209 | System.out.println("Invalid input, try again."); 210 | break; 211 | } 212 | } 213 | } 214 | } 215 | ``` 216 | #### Step 5: Run and Test Your Application 217 | - Execute the application and interact with it through the console to manage tasks. 218 | 219 | 220 | -------------------------------------------------------------------------------- /spring/projects/project_3.MD: -------------------------------------------------------------------------------- 1 | # Advanced Financial Services Management System 2 | 3 | ## Description 4 | The objective of this project is to develop an Advanced Financial Services Management System using Java and Spring 5 | technologies. The system will facilitate account management, transaction processing, investment portfolio 6 | management, customer service, and financial advisory. 7 | 8 | ## Business Case 9 | Financial services are a critical part of the economy, and a well-designed financial services management system 10 | can greatly improve efficiency and accuracy. This project will allow developers to understand and implement 11 | essential features of such systems, emphasizing security, data integrity, and user interaction. 12 | 13 | ## Suggested Architecture & Database Description 14 | The system is divided into two microservices, each with its own database: 15 | 16 | 1. **Account Management Service**: Handles user registration, login, account management, and transaction operations (deposit, withdrawal, transfer). 17 | 2. **Investment and Advisory Service**: Handles investment management, customer service requests, and advisory sessions. 18 | 19 | The two services communicate with each other as needed, for example, to check a user's account balance before 20 | processing an investment. 21 | 22 | ### Communication example between services 23 | - **Scenario**: A user wants to invest in a new financial product. 24 | - **Steps**: 25 | 1. The user logs in to the system and navigates to the investment section. 26 | 2. The user selects the investment type and amount and submits the request. 27 | 3. The Investment and Advisory Service receives the request and checks the user's account balance by calling the Account Management Service. 28 | 4. The Account Management Service verifies the user's account balance and returns the result to the Investment and Advisory Service. 29 | 5. If the account balance is sufficient, the Investment and Advisory Service processes the investment and updates the user's investment portfolio. 30 | 6. The user receives a notification about the successful investment. 31 | - **Scenario 2**: A user wants to book an advisory session with a financial advisor. 32 | - **Steps**: 33 | 1. The user logs in to the system and navigates to the advisory section. 34 | 2. The user selects a financial advisor, date, and time for the session and submits the request. 35 | 3. The Investment and Advisory Service receives the request and checks the financial advisor's availability. 36 | 4. The Investment and Advisory Service updates the financial advisor's schedule and confirms the session. 37 | 5. The user receives a notification about the confirmed advisory session. 38 | 39 | ### Account Management Service 40 | - **Database Schema:** 41 | - **Users**: `id`, `name`, `email`, `password` 42 | - **Accounts**: `id`, `user_id`, `account_type`, `balance` 43 | - **Transactions**: `id`, `account_id`, `type`, `amount`, `date` 44 | - **API Requirements:** 45 | - **Authentication and Session Management:** 46 | - `POST /auth/register`: Register a new user. 47 | - `POST /auth/login`: Authenticate user and create a session. 48 | - `POST /auth/logout`: Terminate the session. 49 | - **Account Operations:** 50 | - `POST /accounts`: Create a new account. 51 | - `GET /accounts`: List all user's accounts. 52 | - `PUT /accounts/{id}`: Update an existing account. 53 | - `DELETE /accounts/{id}`: Delete an account. 54 | - **Transaction Operations:** 55 | - `POST /transactions/deposit`: Deposit an amount to a specific account. 56 | - `POST /transactions/withdraw`: Withdraw an amount from a specific account. 57 | - `POST /transactions/transfer`: Transfer an amount from one account to another. 58 | - `GET /transactions`: View transaction history. 59 | 60 | ### Investment and Advisory Service 61 | - **Database Schema:** 62 | - **Investments**: `id`, `user_id`, `investment_type`, `amount`, `date` 63 | - **CustomerServiceRequests**: `id`, `user_id`, `request_type`, `description`, `status` 64 | - **FinancialAdvisors**: `id`, `name`, `specialization` 65 | - **AdvisorySessions**: `id`, `user_id`, `advisor_id`, `date`, `time`, `status` 66 | - **API Requirements:** 67 | - **Investment Operations:** 68 | - `POST /investments`: Create a new investment. 69 | - `GET /investments`: List all user's investments. 70 | - `PUT /investments/{id}`: Update an existing investment. 71 | - `DELETE /investments/{id}`: Delete an investment. 72 | - **Customer Service Operations:** 73 | - `POST /service-requests`: Create a new service request. 74 | - `GET /service-requests`: List all user's service requests. 75 | - `PUT /service-requests/{id}`: Update an existing service request. 76 | - **Advisory Session Operations:** 77 | - `POST /advisory-sessions`: Book a new advisory session. 78 | - `GET /advisory-sessions`: List all user's advisory sessions. 79 | - `PUT /advisory-sessions/{id}`: Reschedule an existing advisory session. 80 | - `DELETE /advisory-sessions/{id}`: Cancel an advisory session. 81 | 82 | ## User Stories 83 | 1. **As a user, I want to:** 84 | - Register and log in to the system. 85 | - Create, view, and manage my accounts. 86 | - Perform transactions (deposit, withdrawal, transfer) on my accounts. 87 | - View my transaction history. 88 | - Create, view, and manage my investments. 89 | - View my investment portfolio. 90 | - Create customer service requests and view their status. 91 | - Book advisory sessions with financial advisors. 92 | - Receive notifications about changes in my account, transactions, investments, service requests, and advisory sessions. 93 | - Have a user-friendly interface to interact with the system. 94 | - Have access to a help or FAQ section for guidance. 95 | 2. **As a financial advisor, I want to:** 96 | - Log in to the system. 97 | - View and manage my schedule. 98 | - View the list of advisory sessions booked with me. 99 | - Have a system to manage and update my availability. 100 | - Receive notifications about new, rescheduled, or cancelled advisory sessions. 101 | 3. **As a customer service representative, I want to:** 102 | - Log in to the system. 103 | - View and manage customer service requests. 104 | - Update the status of service requests. 105 | - Communicate with users through the system. 106 | - Receive notifications about new or updated service requests. 107 | 4. **As a system, I need to:** 108 | - Validate user credentials. 109 | - Handle sessions to ensure that users' operations are secure and personal information is protected. 110 | - Process transactions accurately and securely, updating account balances in real-time. 111 | - Process investment operations accurately and securely, updating investment portfolios in real-time. 112 | - Handle customer service requests and update their status in real-time. 113 | - Manage advisory sessions and update their status in real-time. 114 | - Provide timely feedback to the user about the status of their transactions, investments, service requests, and advisory sessions. 115 | - Send notifications to users, financial advisors, and customer service representatives about relevant updates. 116 | - Maintain a high level of performance and availability. 117 | - Handle errors gracefully and provide meaningful error messages to the users. 118 | 119 | ## Acceptance Criteria 120 | 1. **Spring Boot Application Setup:** 121 | - Properly configure and initialize a Spring Boot application using Gradle as the build tool. Include dependencies for Spring Boot, Spring Data JPA, Spring Security, and Spring Web. 122 | 2. **Database and Entity Configuration:** 123 | - Define JPA entities corresponding to the database schema for Users, Accounts, Transactions, Investments, CustomerServiceRequests, FinancialAdvisors, and AdvisorySessions. 124 | - Set up a PostgreSQL database and configure Spring Data JPA to interact with it. 125 | - Create repositories for each entity with necessary custom methods to support CRUD operations beyond the basic functionalities provided by Spring Data. 126 | 3. **User Authentication:** 127 | - Implement a secure login system that authenticates users by email and password. 128 | - Ensure that all operations require user authentication. 129 | - Sessions must expire automatically after a period of inactivity or explicitly upon user logout. 130 | 4. **Transaction, Investment, Service Request, and Advisory Session Processing:** 131 | - Develop endpoints to handle account management, transaction processing, investment management, service request management, and advisory session management. These must update and fetch data accurately. 132 | - All operations must handle errors gracefully and return meaningful error messages to the user. 133 | 5. **API Documentation:** 134 | - Set up Swagger for API documentation. 135 | - Document all API endpoints with Swagger, including all request and response models, expected error messages, and status codes. 136 | 6. **Testing:** 137 | - Write integration tests for all critical functionalities such as login, account management, transaction processing, investment management, service request management, and advisory session management. -------------------------------------------------------------------------------- /JavaCore/lessons/matrix.MD: -------------------------------------------------------------------------------- 1 | ### Introduction to Two-Dimensional Arrays 2 | A two-dimensional array is an array that has other arrays as its elements. You can visualize it as a table with rows 3 | and columns. For instance, if you want to store a 3x3 matrix, you'd use a two-dimensional array. 4 | 5 | ### Declaring a Two-Dimensional Array 6 | Syntax: 7 | ```java 8 | dataType[][] arrayName = new dataType[numberOfRows][numberOfColumns]; 9 | ``` 10 | 11 | Example: 12 | ```java 13 | int[][] matrix = new int[3][3]; 14 | ``` 15 | 16 | ### Initializing a Two-Dimensional Array 17 | There are multiple ways to initialize a 2D array: 18 | 19 | 1. At the time of declaration: 20 | ```java 21 | int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; 22 | ``` 23 | 24 | 2. After declaration: 25 | ```java 26 | int[][] matrix = new int[3][3]; 27 | matrix[0][0] = 1; 28 | matrix[0][1] = 2; 29 | // ... and so on 30 | ``` 31 | 32 | ### Looping through a Two-Dimensional Array 33 | To loop through a 2D array, you would generally use nested loops: 34 | 35 | ```java 36 | for (int i = 0; i < matrix.length; i++) { 37 | for (int j = 0; j < matrix[i].length; j++) { 38 | System.out.print(matrix[i][j] + " "); 39 | } 40 | System.out.println(); // Move to the next line after printing a row 41 | } 42 | ``` 43 | 44 | ### Practical Example: Matrix Transposition 45 | 46 | Let's transpose a 3x3 matrix (swap rows with columns): 47 | 48 | ```java 49 | public class MatrixTranspose { 50 | public static void main(String[] args) { 51 | int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; 52 | int[][] transposed = new int[3][3]; 53 | 54 | for (int i = 0; i < matrix.length; i++) { 55 | for (int j = 0; j < matrix[i].length; j++) { 56 | transposed[j][i] = matrix[i][j]; 57 | } 58 | } 59 | 60 | // Print the transposed matrix 61 | for (int[] ints : transposed) { 62 | for (int anInt : ints) { 63 | System.out.print(anInt + " "); 64 | } 65 | System.out.println(); // Move to the next line after printing a row 66 | } 67 | } 68 | } 69 | ``` 70 | 71 | ### Points to Remember: 72 | 1. A two-dimensional array is essentially an array of arrays. 73 | 2. Each row in a two-dimensional array can, technically, have a different number of columns, though it's common to see matrices with uniform columns. 74 | 3. Always ensure you are not accessing an index outside the array bounds to avoid `ArrayIndexOutOfBoundsException`. 75 | 76 | 77 | ### Recommended Resources 78 | - [Matrix Programs in Java](https://www.digitalocean.com/community/tutorials/matrix-programs-in-java) 79 | - [Java Multidimensional Arrays](https://www.programiz.com/java-programming/multidimensional-array) 80 | 81 | 82 | ## Tasks 83 | 84 |
85 | Task 1: Matrix Sum 86 |
 87 | 
 88 | # **Matrix Sum**
 89 | ## **Description:**
 90 | Write a program that accepts an NxN matrix from the user and calculates the sum of its elements. The user will first input N, followed by the elements of the matrix.
 91 | 
 92 | ### _Inputs & Outputs:_
 93 | 
 94 | #### _Sample Input 1:_
 95 | Size of matrix (N): 2  
 96 | Enter element [0][0]: 1  
 97 | Enter element [0][1]: 2  
 98 | Enter element [1][0]: 3  
 99 | Enter element [1][1]: 4
100 | 
101 | #### _Sample Output 1:_
102 | The sum of the matrix elements is: 10.
103 | 
104 | #### _Sample Input 2:_
105 | Size of matrix (N): 3  
106 | Enter element [0][0]: 1  
107 | Enter element [0][1]: 2  
108 | Enter element [0][2]: 3  
109 | Enter element [1][0]: 4  
110 | Enter element [1][1]: 5  
111 | Enter element [1][2]: 6  
112 | Enter element [2][0]: 7  
113 | Enter element [2][1]: 8  
114 | Enter element [2][2]: 9
115 | 
116 | #### _Sample Output 2:_
117 | The sum of the matrix elements is: 45.
118 | 
119 | #### _Sample Input 3:_
120 | Size of matrix (N): 4  
121 | Enter element [0][0]: 1  
122 | Enter element [0][1]: 2  
123 | Enter element [0][2]: 3  
124 | Enter element [0][3]: 4  
125 | Enter element [1][0]: 5  
126 | Enter element [1][1]: 6  
127 | Enter element [1][2]: 7  
128 | Enter element [1][3]: 8  
129 | Enter element [2][0]: 9  
130 | Enter element [2][1]: 10  
131 | Enter element [2][2]: 11  
132 | Enter element [2][3]: 12  
133 | Enter element [3][0]: 13  
134 | Enter element [3][1]: 14  
135 | Enter element [3][2]: 15  
136 | Enter element [3][3]: 16
137 | 
138 | #### _Sample Output 3:_
139 | The sum of the matrix elements is: 136.
140 | 
141 | 
142 |
143 | 144 | --- 145 | 146 |
147 | Task 2: Diagonal Elements 148 |
149 | 
150 | # **Diagonal Elements**
151 | ## **Description:**
152 | Write a program that reads a 3x3 matrix and prints the elements of both the main diagonal and the secondary diagonal.
153 | 
154 | ### _Inputs & Outputs:_
155 | #### _Sample Input 1:_
156 | Enter element [0][0]: 1  
157 | Enter element [0][1]: 2  
158 | Enter element [0][2]: 3  
159 | Enter element [1][0]: 4  
160 | Enter element [1][1]: 5  
161 | Enter element [1][2]: 6  
162 | Enter element [2][0]: 7  
163 | Enter element [2][1]: 8  
164 | Enter element [2][2]: 9
165 | 
166 | #### _Sample Output 1:_
167 | Main Diagonal: 1, 5, 9  
168 | Secondary Diagonal: 3, 5, 7
169 | 
170 | 
171 |
172 | 173 | --- 174 | 175 |
176 | Task 3: Matrix Transpose 177 |
178 | 
179 | # **Matrix Transpose**
180 | ## **Description:**
181 | Given a 2x3 matrix, write a program to transpose it into a 3x2 matrix.
182 | 
183 | ### _Inputs & Outputs:_
184 | #### _Sample Input 1:_
185 | Enter element [0][0]: 1  
186 | Enter element [0][1]: 2  
187 | Enter element [0][2]: 3  
188 | Enter element [1][0]: 4  
189 | Enter element [1][1]: 5  
190 | Enter element [1][2]: 6
191 | 
192 | #### _Sample Output 1:_
193 | Transposed Matrix:  
194 | 1 4  
195 | 2 5  
196 | 3 6
197 | 
198 | 
199 |
200 | 201 | --- 202 | 203 |
204 | Task 4: Matrix Multiplication 205 |
206 | 
207 | # **Matrix Multiplication**
208 | ## **Description:**
209 | Write a program to multiply two 2x2 matrices entered by the user.
210 | 
211 | ### _Inputs & Outputs:_
212 | #### _Sample Input 1:_
213 | Enter matrix A elements:  
214 | Enter element [0][0]: 1  
215 | Enter element [0][1]: 2  
216 | Enter element [1][0]: 3  
217 | Enter element [1][1]: 4
218 | 
219 | Enter matrix B elements:  
220 | Enter element [0][0]: 2  
221 | Enter element [0][1]: 0  
222 | Enter element [1][0]: 1  
223 | Enter element [1][1]: 3
224 | 
225 | #### _Sample Output 1:_
226 | Resultant Matrix:  
227 | 4 6  
228 | 10 12
229 | 
230 | 
231 |
232 | 233 | --- 234 | 235 |
236 | Task 5: Find the Highest Average 237 |
238 | 
239 | # **Matrix Explorer**
240 | ## **Description:**
241 | Write a program that takes scores of students in multiple subjects and finds the student with the highest average score.
242 | 
243 | ### _Inputs & Outputs:_
244 | #### _Sample Input 1:_
245 | Number of students: 3  
246 | Number of subjects: 2  
247 | Enter scores for student 1:  
248 | Math: 85  
249 | Science: 90
250 | 
251 | Enter scores for student 2:  
252 | Math: 78  
253 | Science: 82
254 | 
255 | Enter scores for student 3:  
256 | Math: 92  
257 | Science: 88
258 | 
259 | #### _Sample Output 1:_
260 | Student 3 has the highest average score of 90.0
261 | 
262 | 
263 |
264 | 265 | --- 266 | 267 |
268 | Task 6: Pattern Recognition 269 |
270 | 
271 | # **Pattern Hunter**
272 | ## **Description:**
273 | Write a program that recognizes if the given 3x3 matrix is symmetric around its main diagonal.
274 | 
275 | ### _Inputs & Outputs:_
276 | #### _Sample Input 1:_
277 | Enter element [0][0]: 1  
278 | Enter element [0][1]: 2  
279 | Enter element [0][2]: 3  
280 | Enter element [1][0]: 2  
281 | Enter element [1][1]: 4  
282 | Enter element [1][2]: 5  
283 | Enter element [2][0]: 3  
284 | Enter element [2][1]: 5  
285 | Enter element [2][2]: 6
286 | 
287 | #### _Sample Output 1:_
288 | The matrix is symmetric around its main diagonal.
289 | 
290 | 
291 |
292 | 293 | --- 294 | 295 |
296 | Task 7: Boundary Elements 297 |
298 | 
299 | # **Border Keeper**
300 | ## **Description:**
301 | Write a program that accepts a 4x4 matrix and prints the boundary elements.
302 | 
303 | ### _Inputs & Outputs:_
304 | #### _Sample Input 1:_
305 | Enter element [0][0]: 1  
306 | ...  
307 | Enter element [3][3]: 16
308 | 
309 | #### _Sample Output 1:_
310 | Boundary Elements: 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5
311 | 
312 | 
313 |
314 | 315 | --- 316 | 317 |
318 | Task 8: Anti-Diagonal Elements 319 |
320 | 
321 | # **Reverse Diagonal Inspector**
322 | ## **Description:**
323 | Given a 4x4 matrix, write a program to print the elements of the anti-diagonal (from bottom-left to top-right).
324 | 
325 | ### _Inputs & Outputs:_
326 | #### _Sample Input 1:_
327 | Enter element [0][0]: 1  
328 | ...  
329 | Enter element [3][3]: 16
330 | 
331 | #### _Sample Output 1:_
332 | Anti-Diagonal Elements: 13, 10, 7, 4
333 | 
334 | 
335 |
336 | 337 | 338 | -------------------------------------------------------------------------------- /spring/lessons/module_5.MD: -------------------------------------------------------------------------------- 1 | ### Module: Data Access with Spring Data 2 | 3 | #### Overview 4 | This module will introduce you to Spring Data, a powerful framework that simplifies data handling with Spring 5 | applications, offering consistent, declarative, and convenient ways to access data from various data stores. 6 | We'll cover key concepts, repository interfaces, and how to integrate Spring Data with JPA, JDBC, and REST 7 | APIs using Spring Boot. This module is designed for students who already have a foundation in Java, Spring Boot, 8 | and RESTful services. 9 | 10 | #### Learning Objectives 11 | By the end of this module, you should be able to: 12 | 1. Understand the core principles and benefits of using Spring Data in Spring applications. 13 | 2. Define and use repository interfaces to abstract data access. 14 | 3. Configure Spring Data with JPA to perform database operations without boilerplate code. 15 | 4. Integrate Spring Data repositories with Spring Boot applications. 16 | 5. Develop a REST API that leverages Spring Data for CRUD operations. 17 | 18 | #### Pre-requisites 19 | 20 | - Basic knowledge of Java and Java Core. 21 | - Understanding of JDBC and its limitations. 22 | - Familiarity with Spring Boot and building REST APIs. 23 | 24 | ### Part 1: Introduction to Spring Data 25 | #### Content 26 | - **What is Spring Data?** 27 | - Simplifies data access operations 28 | - Reduces boilerplate code 29 | - Supports NoSQL and relational databases 30 | - **Key Features of Spring Data** 31 | - Repository abstraction 32 | - Query derivation from method names 33 | - Implementation domain base classes 34 | 35 | #### Example 36 | ```java 37 | public interface UserRepository extends CrudRepository { 38 | } 39 | ``` 40 | 41 | This simple example shows a repository interface extending `CrudRepository`, providing CRUD operations for `User` entities. 42 | 43 | 44 | ### Part 2: Configuring Spring Data with JPA 45 | #### Content 46 | - **Integration with JPA** 47 | - Setting up JPA in Spring Boot 48 | - Configuring data source and EntityManager 49 | - **Defining Entity Models** 50 | - Annotating classes with `@Entity` 51 | - Mapping relationships with `@OneToMany`, `@ManyToOne` 52 | - **Repository Interfaces** 53 | - Extending `JpaRepository` 54 | - Benefits of using JpaRepository interface 55 | 56 | #### Example 57 | ```java 58 | @Entity 59 | public class Book { 60 | @Id 61 | @GeneratedValue(strategy = GenerationType.AUTO) 62 | private Long id; 63 | 64 | private String title; 65 | private String author; 66 | 67 | // getters and setters 68 | } 69 | 70 | public interface BookRepository extends JpaRepository { 71 | } 72 | ``` 73 | This example defines a `Book` entity and a repository interface for accessing `Book` records. 74 | 75 | ### Part 3: Creating Repository Methods 76 | #### Content 77 | - **Custom Query Methods** 78 | - Defining query methods in repositories 79 | - Query creation from method names 80 | 81 | - **Using `@Query` Annotation** 82 | - Writing JPQL and SQL queries with `@Query` 83 | - Parameters binding in queries 84 | 85 | #### Example 86 | ```java 87 | public interface UserRepository extends JpaRepository { 88 | List findByLastName(String lastName); 89 | 90 | @Query("SELECT u FROM User u WHERE u.email = ?1") 91 | User findByEmail(String email); 92 | } 93 | ``` 94 | 95 | ### Part 4: Integrating Spring Data with REST 96 | #### Content 97 | - **Building a REST Controller** 98 | - Autowiring repository interfaces 99 | - Implementing CRUD operations 100 | 101 | - **Exception Handling** 102 | - Handling common data access exceptions 103 | - Custom exception responses 104 | 105 | #### Example 106 | ```java 107 | @RestController 108 | @RequestMapping("/api/books") 109 | public class BookController { 110 | @Autowired 111 | private BookRepository bookRepository; 112 | 113 | @GetMapping("/{id}") 114 | public ResponseEntity getBookById(@PathVariable Long id) { 115 | Book book = bookRepository.findById(id) 116 | .orElseThrow(() -> new ResourceNotFoundException("Book not found")); 117 | return ResponseEntity.ok().body(book); 118 | } 119 | 120 | // Additional CRUD endpoints 121 | } 122 | ``` 123 | 124 | --- 125 | 126 | ### Conclusion 127 | This module on Data Access with Spring Data offers a streamlined approach to integrating database operations into your 128 | Spring Boot applications. By the end of this module, you should be comfortable setting up repositories, configuring 129 | entities, and extending Spring Data to meet your specific data access needs. Continue practicing with different entity 130 | models and explore advanced querying capabilities to deepen your understanding of Spring Data. 131 | 132 | ### Practical Exercise: Book Management System with SQLite Database 133 | 134 | #### Objective 135 | Develop a simple book management system using Spring Boot, Spring Data JPA, and SQLite. This system will allow users to perform CRUD (Create, Read, Update, Delete) operations on books stored in an SQLite database. 136 | 137 | #### Tools and Technologies 138 | - **Java**: Programming language. 139 | - **Spring Boot**: Framework for easy bootstrapping and development of new Spring Applications. 140 | - **Spring Data JPA**: Simplifies data access operations. 141 | - **SQLite**: Lightweight, file-based database management system. 142 | - **Gradle**: Dependency management. 143 | 144 | ### Setup Instructions 145 | 1. **Project Setup**: 146 | - Create a new Spring Boot project using [Spring Initializr](https://start.spring.io/). 147 | - Choose Gradle as the build tool and Java as the language. 148 | - Add dependencies for 'Spring Web' and 'Spring Data JPA'. 149 | 150 | 2. **Dependencies**: 151 | - Modify your `build.gradle` file to include the necessary dependencies for SQLite. Here's how your `dependencies` section might look: 152 | ```gradle 153 | dependencies { 154 | implementation 'org.springframework.boot:spring-boot-starter-web' 155 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 156 | runtimeOnly 'org.xerial:sqlite-jdbc:3.36.0.3' 157 | 158 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 159 | } 160 | ``` 161 | 162 | 3. **Configure the SQLite Database**: 163 | - In the `src/main/resources` directory, create an `application.properties` file. 164 | - Add the following properties to configure the connection to the SQLite database: 165 | 166 | ```properties 167 | spring.datasource.url=jdbc:sqlite:books.db 168 | spring.datasource.driver-class-name=org.sqlite.JDBC 169 | spring.jpa.database-platform=org.hibernate.dialect.SQLiteDialect 170 | spring.jpa.hibernate.ddl-auto=update 171 | ``` 172 | 173 | 4. **Entity Creation**: 174 | - Define a Book entity. 175 | 176 | ```java 177 | @Entity 178 | public class Book { 179 | @Id 180 | @GeneratedValue(strategy = GenerationType.AUTO) 181 | private Long id; 182 | private String title; 183 | private String author; 184 | private String isbn; 185 | 186 | // Standard getters and setters 187 | } 188 | ``` 189 | 190 | 5. **Repository Interface**: 191 | - Create a repository interface for the `Book` entity. 192 | 193 | ```java 194 | public interface BookRepository extends JpaRepository { 195 | List findByAuthor(String author); 196 | } 197 | ``` 198 | 199 | 6. **REST Controller**: 200 | - Implement a REST controller to manage books. 201 | 202 | ```java 203 | @RestController 204 | @RequestMapping("/api/books") 205 | public class BookController { 206 | @Autowired 207 | private BookRepository bookRepository; 208 | 209 | @PostMapping 210 | public Book addBook(@RequestBody Book book) { 211 | return bookRepository.save(book); 212 | } 213 | 214 | @GetMapping 215 | public List getAllBooks() { 216 | return bookRepository.findAll(); 217 | } 218 | 219 | @GetMapping("/{id}") 220 | public Book getBookById(@PathVariable Long id) { 221 | return bookRepository.findById(id).orElseThrow(() -> new RuntimeException("Book not found")); 222 | } 223 | 224 | @PutMapping("/{id}") 225 | public Book updateBook(@PathVariable Long id, @RequestBody Book updatedBook) { 226 | return bookRepository.findById(id) 227 | .map(book -> { 228 | book.setTitle(updatedBook.getTitle()); 229 | book.setAuthor(updatedBook.getAuthor()); 230 | book.setIsbn(updatedBook.getIsbn()); 231 | return bookRepository.save(book); 232 | }) 233 | .orElseGet(() -> { 234 | updatedBook.setId(id); 235 | return bookRepository.save(updatedBook); 236 | }); 237 | } 238 | 239 | @DeleteMapping("/{id}") 240 | public void deleteBook(@PathVariable Long id) { 241 | bookRepository.deleteById(id); 242 | } 243 | } 244 | ``` 245 | 246 | #### Exercise Tasks 247 | - **Implement the Entity and Repository**: Define the `Book` entity and create the corresponding repository interface. 248 | - **Create the REST Controller**: Develop the controller with endpoints to handle CRUD operations. 249 | - **Test the Application**: 250 | - Run your application and use tools like Postman or Curl to test the REST API. 251 | - Add, retrieve, update, and delete book entries from the SQLite database. 252 | 253 | 254 | ### Recommended Resources 255 | - [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa) 256 | - [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) 257 | - [Spring Data JPA Tutorial](https://www.javatpoint.com/spring-and-jpa-integration) 258 | -------------------------------------------------------------------------------- /JavaCore/lessons/polymorphism.MD: -------------------------------------------------------------------------------- 1 | ### Understanding Polymorphism 2 | 3 | Polymorphism in Java refers to the ability of a single method to operate on objects of different classes. 4 | It's a concept where one interface can be used for a general class of actions. The specific action is determined by 5 | the exact nature of the situation. 6 | 7 | There are two types of polymorphism in Java: 8 | 1. **Compile-time Polymorphism (Static Binding)**: This is achieved by method overloading and operator overloading. However, Java doesn't support operator overloading. 9 | 2. **Run-time Polymorphism (Dynamic Binding)**: This is achieved by method overriding, which occurs in the context of inheritance. 10 | 11 | ### Compile-time Polymorphism 12 | Compile-time polymorphism is achieved when multiple methods have the same name but different parameters (number, types, or order of parameters). 13 | 14 | **Example:** 15 | ```java 16 | class Adder { 17 | static int add(int a, int b) { 18 | return a + b; 19 | } 20 | static double add(double a, double b) { 21 | return a + b; 22 | } 23 | } 24 | 25 | public class TestPolymorphism { 26 | public static void main(String[] args) { 27 | System.out.println(Adder.add(5, 6)); // Calls the first add method 28 | System.out.println(Adder.add(5.0, 6.0)); // Calls the second add method 29 | } 30 | } 31 | ``` 32 | 33 | ### Run-time Polymorphism 34 | Run-time polymorphism is achieved by method overriding, where a subclass provides a specific implementation of a method that is already provided by one of its superclasses. 35 | 36 | **Example:** 37 | ```java 38 | class Animal { 39 | void sound() { 40 | System.out.println("The animal makes a sound"); 41 | } 42 | } 43 | 44 | class Dog extends Animal { 45 | void sound() { 46 | System.out.println("The dog barks"); 47 | } 48 | } 49 | 50 | public class TestPolymorphism { 51 | public static void main(String[] args) { 52 | Animal myAnimal = new Animal(); 53 | Animal myDog = new Dog(); 54 | 55 | myAnimal.sound(); // Outputs: The animal makes a sound 56 | myDog.sound(); // Outputs: The dog barks 57 | } 58 | } 59 | ``` 60 | 61 | In the above example, even though `myDog` is of type `Animal`, it uses the `sound` method of the `Dog` class because 62 | it was overridden. 63 | 64 | ### Key Points 65 | - Polymorphism allows for flexibility and loose coupling in code. 66 | - The `instanceof` keyword can be used to test whether an object is an instance of a specific class or subclass. 67 | - Polymorphism can be achieved with abstract classes and interfaces. 68 | 69 | 70 | ### Recommended Resources 71 | - [Polymorphism in Java with Examples](https://www.mygreatlearning.com/blog/polymorphism-in-java/#:~:text=Polymorphism%20in%20Java%20is%20the,instance%2C%20is%20one%20such%20language.) 72 | - [Java Polymorphism](https://www.w3schools.com/java/java_polymorphism.asp) 73 | - [Polymorphism in Java](https://www.geeksforgeeks.org/polymorphism-in-java) 74 | - [Polymorphism](https://www.javatpoint.com/runtime-polymorphism-in-java) 75 | - [What Is Polymorphism in Java?](https://blog.hubspot.com/website/polymorphism-java) 76 | - [Polymorphism documentation](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) 77 | - [Object-Oriented Programming in Java – A Beginner's Guide](https://www.freecodecamp.org/news/object-oriented-programming-concepts-java) 78 | 79 | 80 | ## Tasks 81 | 82 |
83 | Task 1: Method Overloading 84 |
 85 | 
 86 | # Method Overloading
 87 | ## Description:
 88 | Create a class 'Multiplier' that has several 'multiply' methods with different parameter lists (overloaded methods) to multiply two integers, two doubles, and one double and one integer.
 89 | 
 90 | ### _Inputs & Outputs:_
 91 | #### _Sample Input 1:_
 92 | Multiplier.multiply(3, 4)
 93 | 
 94 | #### _Sample Output 1:_
 95 | 12
 96 | 
 97 | #### _Sample Input 2:_
 98 | Multiplier.multiply(2.5, 3.0)
 99 | 
100 | #### _Sample Output 2:_
101 | 7.5
102 | 
103 | 
104 |
105 | 106 | --- 107 | 108 |
109 | Task 2: Method Overriding 110 |
111 | 
112 | # Method Overriding
113 | ## Description:
114 | Create a superclass 'Shape' with a method 'draw()' and subclasses 'Circle' and 'Rectangle' that override the 'draw()' method to print the shape being drawn.
115 | 
116 | ### _Inputs & Outputs:_
117 | #### _Sample Input 1:_
118 | Shape shape = new Circle();
119 | shape.draw();
120 | 
121 | #### _Sample Output 1:_
122 | Drawing Circle
123 | 
124 | #### _Sample Input 2:_
125 | Shape shape = new Rectangle();
126 | shape.draw();
127 | 
128 | #### _Sample Output 2:_
129 | Drawing Rectangle
130 | 
131 | 
132 |
133 | 134 | --- 135 | 136 |
137 | Task 3: Runtime Polymorphism with Inheritance 138 |
139 | 
140 | # Runtime Polymorphism with Inheritance
141 | ## Description:
142 | Create a base class 'Bank' with a method 'getInterestRate()' and derived classes 'BankA', 'BankB', and 'BankC' that override the method to provide specific interest rates.
143 | 
144 | ### _Inputs & Outputs:_
145 | #### _Sample Input 1:_
146 | Bank bank = new BankA();
147 | bank.getInterestRate();
148 | 
149 | #### _Sample Output 1:_
150 | 2.5% (Assuming BankA offers a 2.5% interest rate)
151 | 
152 | #### _Sample Input 2:_
153 | Bank bank = new BankB();
154 | bank.getInterestRate();
155 | 
156 | #### _Sample Output 2:_
157 | 3.0% (Assuming BankB offers a 3.0% interest rate)
158 | 
159 | 
160 |
161 | 162 | --- 163 | 164 |
165 | Task 4: Abstract Class and Polymorphism 166 |
167 | 
168 | # Abstract Class and Polymorphism
169 | ## Description:
170 | Create an abstract class 'Device' with an abstract method 'start()'. Create concrete classes 'Computer' and 'Smartphone' that extend 'Device' and implement the 'start()' method.
171 | 
172 | ### _Inputs & Outputs:_
173 | #### _Sample Input 1:_
174 | Device device = new Computer();
175 | device.start();
176 | 
177 | #### _Sample Output 1:_
178 | Computer is starting
179 | 
180 | #### _Sample Input 2:_
181 | Device device = new Smartphone();
182 | device.start();
183 | 
184 | #### _Sample Output 2:_
185 | Smartphone is starting
186 | 
187 | 
188 |
189 | 190 | --- 191 | 192 |
193 | Task 5: Interface Polymorphism 194 |
195 | 
196 | # Interface Polymorphism
197 | ## Description:
198 | Create an interface 'Animal' with a method 'makeSound()'. Create classes 'Dog' and 'Cat' that implement the 'Animal' interface and provide their versions of 'makeSound()'.
199 | 
200 | ### _Inputs & Outputs:_
201 | #### _Sample Input 1:_
202 | Animal animal = new Dog();
203 | animal.makeSound();
204 | 
205 | #### _Sample Output 1:_
206 | Bark
207 | 
208 | #### _Sample Input 2:_
209 | Animal animal = new Cat();
210 | animal.makeSound();
211 | 
212 | #### _Sample Output 2:_
213 | Meow
214 | 
215 | 
216 |
217 | 218 | --- 219 | 220 |
221 | Task 6: Polymorphic Arrays 222 |
223 | 
224 | # Polymorphic Arrays
225 | ## Description:
226 | Create an array of 'Animal' objects where each array element can hold different types of animals like 'Dog', 'Cat', etc. Iterate over the array and invoke the 'makeSound()' method for each animal.
227 | 
228 | ### _Inputs & Outputs:_
229 | #### _No Sample Input (This task is about creating and executing a polymorphic array)_
230 | 
231 | #### _Sample Output:_
232 | Bark
233 | Meow
234 | [...outputs depend on the animals added to the array...]
235 | 
236 | 
237 |
238 | 239 | --- 240 | 241 |
242 | Task 7: Payment Processing System 243 |
244 | 
245 | # Payment Processing System
246 | ## Description:
247 | Design a simple payment processing system where you have a base class `Payment` with a method `processPayment()`. Subclasses `CreditCardPayment`, `PaypalPayment`, and `BankTransferPayment` should override this method to provide specific processing mechanisms.
248 | 
249 | ### _Inputs & Outputs:_
250 | #### _Sample Input 1:_
251 | Payment payment = new CreditCardPayment(100.00);
252 | payment.processPayment();
253 | 
254 | #### _Sample Output 1:_
255 | Processing credit card payment for $100.00
256 | 
257 | #### _Sample Input 2:_
258 | Payment payment = new PaypalPayment(75.50);
259 | payment.processPayment();
260 | 
261 | #### _Sample Output 2:_
262 | Processing PayPal payment for $75.50
263 | 
264 | 
265 |
266 | 267 | --- 268 | 269 |
270 | Task 8: Event Notification System 271 |
272 | 
273 | # Event Notification System
274 | ## Description:
275 | Create an event notification system where you have an interface `Notifier` with a method `sendNotification()`. Classes `EmailNotifier`, `SMSNotifier`, and `PushNotifier` implement the `Notifier` interface to send notifications through their respective channels.
276 | 
277 | ### _Inputs & Outputs:_
278 | #### _Sample Input 1:_
279 | Notifier notifier = new EmailNotifier("user@example.com", "Server Down");
280 | notifier.sendNotification();
281 | 
282 | #### _Sample Output 1:_
283 | Sending email to user@example.com with message: Server Down
284 | 
285 | #### _Sample Input 2:_
286 | Notifier notifier = new SMSNotifier("+123456789", "Balance Low");
287 | notifier.sendNotification();
288 | 
289 | #### _Sample Output 2:_
290 | Sending SMS to +123456789 with message: Balance Low
291 | 
292 | 
293 |
294 | 295 | --------------------------------------------------------------------------------