├── .gitattributes ├── README.md ├── java_advanced_guide.md ├── lesson1 ├── Arrays │ ├── ArrayLists.java │ ├── ArrayManipulation.java │ ├── Arrays.class │ ├── Arrays.java │ ├── ArraysExample.java │ └── HashMaps.java ├── Basic syntax │ ├── BasicSyntax.java │ ├── Encapsulation.java │ ├── FinallyBlock.java │ ├── MethodsAndFunctions.java │ ├── Operators.java │ ├── ThrowingExceptions.java │ ├── TryCatchBlocks.java │ └── VariablesAndDataTypes.java ├── Classes │ ├── AccessModifiers.java │ ├── ClassManipulation.java │ ├── ClassesAndObjects.java │ └── Constructors.java └── Loops │ ├── ControlFlow.java │ └── Loops.java ├── lesson2 ├── DatabaseConnectivity │ ├── CRUDOperations.java │ └── DatabaseConnection.java ├── FileHandling │ ├── ReadingWritingFiles.java │ └── WorkingWithStreams.java ├── MultithreadingConcurrency │ ├── Synchronization.java │ └── Threads.java └── OOPAdvanced │ ├── Abstraction.java │ ├── Inheritance.java │ └── Polymorphism.java ├── lesson3 ├── DesignPatterns │ ├── DependencyInjection.java │ ├── FactoryPattern.java │ ├── ObserverPattern.java │ └── SingletonPattern.java ├── FunctionalProgramming │ ├── LambdaExpressions.java │ ├── OptionalClass.java │ └── StreamsAPI.java ├── JavaCollectionsFramework │ ├── Lists.java │ ├── Maps.java │ ├── Queues.java │ └── Sets.java └── MemoryManagement │ ├── GarbageCollection.java │ ├── JVMInternals.java │ └── MemoryLeaks.java ├── lesson4 ├── BuildingGUI │ ├── BuildingGUIWithSwing.java │ └── EventHandlingInGUI.java ├── SpringBoot │ ├── BuildingRestAPIs.java │ ├── DependencyInjection.java │ ├── HandlingApiRequests.java │ └── WorkingWithSpringDataJPA.java └── UnitTesting │ ├── MockingWithMockito.java │ └── UnitTestingWithJUnit.java └── lesson5 ├── DevOpsDeployment ├── CICDWithJenkins.java ├── DockerizingJavaApplications.java └── KubernetesForJavaMicroservices.java ├── Microservices ├── BuildingMicroservices.java ├── RestfulApisAndGraphQL.java └── ServiceCommunication.java └── WorkingWithAPIs ├── CallingExternalAPIs.java └── JsonParsingWithJackson.java /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Tutorials for Beginners 2 | 3 | Welcome to the Java Tutorials for Beginners! This repository contains a collection of tutorials designed to help beginners learn Java programming from scratch. 4 | 5 | ## Java Beginner to Advanced Guide 6 | 7 | In addition to the beginner tutorials, we now have a Java Advanced Guide for those looking to deepen their knowledge. The advanced guide covers more complex topics and is designed for those who have completed the beginner tutorials or have equivalent experience. 8 | 9 | To access the Java Advanced Guide, navigate to the [`java-beginner-to-advanced-guide`](https://github.com/Sandlie101G12B/Java-tutorials-for-beginners/blob/main/java_advanced_guide.md) directory in this repository. 10 | 11 | ## Prerequisites 12 | 13 | Before you begin, ensure you have met the following requirements: 14 | - You have installed [Java Development Kit (JDK)](https://www.oracle.com/java/technologies/javase-downloads.html). 15 | - You have installed [Apache Maven](https://maven.apache.org/install.html). 16 | - You have a basic understanding of programming concepts. 17 | 18 | ## Installation 19 | 20 | To get started with the tutorials, clone this repository to your local machine using the following command: 21 | 22 | ```bash 23 | git clone https://github.com/Sandlie101G12B/Java-tutorials-for-beginners.git 24 | ``` 25 | 26 | ## Usage 27 | 28 | Follow the tutorials in the order they are presented to build your understanding of Java step-by-step. Each tutorial is located in its own directory and contains a README file with instructions. 29 | 30 | ## Contributing 31 | 32 | Contributions are welcome! To contribute, follow these steps: 33 | 1. Fork this repository. 34 | 2. Create a new branch (`git checkout -b feature-branch`). 35 | 3. Make your changes and commit them (`git commit -m 'Add some feature'`). 36 | 4. Push to the branch (`git push origin feature-branch`). 37 | 5. Create a new Pull Request. -------------------------------------------------------------------------------- /java_advanced_guide.md: -------------------------------------------------------------------------------- 1 | # Advanced Java Guide 2 | 3 | ## Introduction 4 | This guide covers advanced Java topics, building on the basics to help you become proficient in Java programming. 5 | 6 | ## Syntax 7 | Java syntax is largely influenced by C and C++ but has fewer low-level facilities. 8 | 9 | ### Example 10 | ```java 11 | // This is a comment 12 | public class Main { 13 | public static void main(String[] args) { 14 | System.out.println("Hello, World!"); 15 | } 16 | } 17 | ``` 18 | 19 | ## Variables 20 | Variables are containers for storing data values. 21 | 22 | ### Example 23 | ```java 24 | int myNum = 5; // Integer (whole number) 25 | float myFloatNum = 5.99f; // Floating point number 26 | char myLetter = 'D'; // Character 27 | boolean myBool = true; // Boolean 28 | String myText = "Hello"; // String 29 | ``` 30 | 31 | ## Data Types 32 | Java has a rich set of data types. 33 | 34 | ### Primitive Data Types 35 | - **byte**: 8-bit integer 36 | - **short**: 16-bit integer 37 | - **int**: 32-bit integer 38 | - **long**: 64-bit integer 39 | - **float**: Single-precision floating-point 40 | - **double**: Double-precision floating-point 41 | - **char**: Single 16-bit Unicode character 42 | - **boolean**: true or false 43 | 44 | ### Non-Primitive Data Types 45 | - **String** 46 | - **Arrays** 47 | - **Classes** 48 | - **Interfaces** 49 | 50 | ## Operators 51 | Operators are used to perform operations on variables and values. 52 | 53 | ### Arithmetic Operators 54 | - **+**: Addition 55 | - **-**: Subtraction 56 | - **\***: Multiplication 57 | - **/**: Division 58 | - **%**: Modulus 59 | 60 | ### Example 61 | ```java 62 | int x = 5; 63 | int y = 3; 64 | System.out.println(x + y); // Output: 8 65 | ``` 66 | 67 | ### Comparison Operators 68 | - **==**: Equal to 69 | - **!=**: Not equal to 70 | - **>**: Greater than 71 | - **<**: Less than 72 | - **>=**: Greater than or equal to 73 | - **<=**: Less than or equal to 74 | 75 | ### Example 76 | ```java 77 | int x = 5; 78 | int y = 3; 79 | System.out.println(x > y); // Output: true 80 | ``` 81 | 82 | ### Logical Operators 83 | - **&&**: Logical and 84 | - **||**: Logical or 85 | - **!**: Logical not 86 | 87 | ### Example 88 | ```java 89 | int x = 5; 90 | int y = 3; 91 | System.out.println(x > 3 && y < 5); // Output: true 92 | ``` 93 | 94 | ## Control Flow 95 | Control flow statements are used to control the flow of execution in a program. 96 | 97 | ### If-Else 98 | ```java 99 | int x = 20; 100 | if (x > 18) { 101 | System.out.println("x is greater than 18"); 102 | } else { 103 | System.out.println("x is not greater than 18"); 104 | } 105 | ``` 106 | 107 | ### Switch 108 | ```java 109 | int day = 4; 110 | switch (day) { 111 | case 1: 112 | System.out.println("Monday"); 113 | break; 114 | case 2: 115 | System.out.println("Tuesday"); 116 | break; 117 | case 3: 118 | System.out.println("Wednesday"); 119 | break; 120 | case 4: 121 | System.out.println("Thursday"); 122 | break; 123 | case 5: 124 | System.out.println("Friday"); 125 | break; 126 | case 6: 127 | System.out.println("Saturday"); 128 | break; 129 | case 7: 130 | System.out.println("Sunday"); 131 | break; 132 | default: 133 | System.out.println("Invalid day"); 134 | } 135 | ``` 136 | 137 | ### Loops 138 | Loops are used to execute a block of code repeatedly. 139 | 140 | #### For Loop 141 | ```java 142 | for (int i = 0; i < 5; i++) { 143 | System.out.println(i); 144 | } 145 | ``` 146 | 147 | #### While Loop 148 | ```java 149 | int i = 0; 150 | while (i < 5) { 151 | System.out.println(i); 152 | i++; 153 | } 154 | ``` 155 | 156 | #### Do-While Loop 157 | ```java 158 | int i = 0; 159 | do { 160 | System.out.println(i); 161 | i++; 162 | } while (i < 5); 163 | ``` 164 | 165 | ## Arrays 166 | Arrays are used to store multiple values in a single variable. 167 | 168 | ### Example 169 | ```java 170 | String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; 171 | System.out.println(cars[0]); // Output: Volvo 172 | ``` 173 | 174 | ## Methods 175 | Methods are used to perform certain actions, and they are also known as functions. 176 | 177 | ### Example 178 | ```java 179 | public class Main { 180 | static void myMethod() { 181 | System.out.println("Hello, World!"); 182 | } 183 | 184 | public static void main(String[] args) { 185 | myMethod(); 186 | } 187 | } 188 | ``` 189 | 190 | ## Classes and Objects 191 | Java is an object-oriented programming language. Everything in Java is associated with classes and objects. 192 | 193 | ### Example 194 | ```java 195 | public class Main { 196 | int x = 5; 197 | 198 | public static void main(String[] args) { 199 | Main myObj = new Main(); 200 | System.out.println(myObj.x); 201 | } 202 | } 203 | ``` 204 | 205 | ## Object-Oriented Programming (OOP) 206 | Java is an object-oriented programming language. Understanding OOP principles is crucial for advanced Java programming. 207 | 208 | ### Encapsulation 209 | Encapsulation is the mechanism of wrapping the data (variables) and code (methods) together as a single unit. 210 | 211 | ### Example 212 | ```java 213 | public class Person { 214 | private String name; // private = restricted access 215 | 216 | // Getter 217 | public String getName() { 218 | return name; 219 | } 220 | 221 | // Setter 222 | public void setName(String newName) { 223 | this.name = newName; 224 | } 225 | } 226 | ``` 227 | 228 | ### Inheritance 229 | Inheritance is a mechanism wherein a new class is derived from an existing class. 230 | 231 | ### Example 232 | ```java 233 | class Animal { 234 | protected String name; 235 | 236 | public void eat() { 237 | System.out.println("This animal eats food."); 238 | } 239 | } 240 | 241 | class Dog extends Animal { 242 | public void bark() { 243 | System.out.println("The dog barks."); 244 | } 245 | } 246 | 247 | public class Main { 248 | public static void main(String[] args) { 249 | Dog myDog = new Dog(); 250 | myDog.name = "Buddy"; 251 | myDog.eat(); 252 | myDog.bark(); 253 | } 254 | } 255 | ``` 256 | 257 | ### Polymorphism 258 | Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance. 259 | 260 | ### Example 261 | ```java 262 | class Animal { 263 | public void sound() { 264 | System.out.println("Animal makes a sound"); 265 | } 266 | } 267 | 268 | class Dog extends Animal { 269 | public void sound() { 270 | System.out.println("Dog barks"); 271 | } 272 | } 273 | 274 | class Cat extends Animal { 275 | public void sound() { 276 | System.out.println("Cat meows"); 277 | } 278 | } 279 | 280 | public class Main { 281 | public static void main(String[] args) { 282 | Animal myAnimal = new Animal(); 283 | Animal myDog = new Dog(); 284 | Animal myCat = new Cat(); 285 | 286 | myAnimal.sound(); 287 | myDog.sound(); 288 | myCat.sound(); 289 | } 290 | } 291 | ``` 292 | 293 | ### Abstraction 294 | Abstraction is the process of hiding the implementation details and showing only functionality to the user. 295 | 296 | ### Example 297 | ```java 298 | abstract class Animal { 299 | public abstract void animalSound(); 300 | public void sleep() { 301 | System.out.println("Zzz"); 302 | } 303 | } 304 | 305 | class Dog extends Animal { 306 | public void animalSound() { 307 | System.out.println("The dog barks"); 308 | } 309 | } 310 | 311 | public class Main { 312 | public static void main(String[] args) { 313 | Dog myDog = new Dog(); 314 | myDog.animalSound(); 315 | myDog.sleep(); 316 | } 317 | } 318 | ``` 319 | 320 | ## Interfaces 321 | An interface is a completely "abstract class" that is used to group related methods with empty bodies. 322 | 323 | ### Example 324 | ```java 325 | interface Animal { 326 | public void animalSound(); 327 | public void sleep(); 328 | } 329 | 330 | class Dog implements Animal { 331 | public void animalSound() { 332 | System.out.println("The dog barks"); 333 | } 334 | public void sleep() { 335 | System.out.println("The dog sleeps"); 336 | } 337 | } 338 | 339 | public class Main { 340 | public static void main(String[] args) { 341 | Dog myDog = new Dog(); 342 | myDog.animalSound(); 343 | myDog.sleep(); 344 | } 345 | } 346 | ``` 347 | 348 | ## Exception Handling 349 | Exception handling is a powerful mechanism to handle runtime errors. 350 | 351 | ### Example 352 | ```java 353 | public class Main { 354 | public static void main(String[] args) { 355 | try { 356 | int[] myNumbers = {1, 2, 3}; 357 | System.out.println(myNumbers[10]); 358 | } catch (Exception e) { 359 | System.out.println("Something went wrong."); 360 | } finally { 361 | System.out.println("The 'try catch' is finished."); 362 | } 363 | } 364 | } 365 | ``` 366 | 367 | ## Collections Framework 368 | The Java Collections Framework provides a set of interfaces and classes to handle collections of objects. 369 | 370 | ### List 371 | A List is an ordered collection (also known as a sequence). 372 | 373 | ### Example 374 | ```java 375 | import java.util.ArrayList; 376 | import java.util.List; 377 | 378 | public class Main { 379 | public static void main(String[] args) { 380 | List list = new ArrayList<>(); 381 | list.add("Apple"); 382 | list.add("Banana"); 383 | list.add("Cherry"); 384 | 385 | for (String fruit : list) { 386 | System.out.println(fruit); 387 | } 388 | } 389 | } 390 | ``` 391 | 392 | ### Set 393 | A Set is a collection that cannot contain duplicate elements. 394 | 395 | ### Example 396 | ```java 397 | import java.util.HashSet; 398 | import java.util.Set; 399 | 400 | public class Main { 401 | public static void main(String[] args) { 402 | Set set = new HashSet<>(); 403 | set.add("Apple"); 404 | set.add("Banana"); 405 | set.add("Cherry"); 406 | set.add("Apple"); // Duplicate element 407 | 408 | for (String fruit : set) { 409 | System.out.println(fruit); 410 | } 411 | } 412 | } 413 | ``` 414 | 415 | ### Map 416 | A Map is an object that maps keys to values. 417 | 418 | ### Example 419 | ```java 420 | import java.util.HashMap; 421 | import java.util.Map; 422 | 423 | public class Main { 424 | public static void main(String[] args) { 425 | Map map = new HashMap<>(); 426 | map.put("Apple", 1); 427 | map.put("Banana", 2); 428 | map.put("Cherry", 3); 429 | 430 | for (Map.Entry entry : map.entrySet()) { 431 | System.out.println(entry.getKey() + ": " + entry.getValue()); 432 | } 433 | } 434 | } 435 | ``` 436 | 437 | ## Generics 438 | Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. 439 | 440 | ### Example 441 | ```java 442 | public class Main { 443 | public static void printArray(T[] array) { 444 | for (T element : array) { 445 | System.out.println(element); 446 | } 447 | } 448 | 449 | public static void main(String[] args) { 450 | Integer[] intArray = {1, 2, 3, 4, 5}; 451 | String[] stringArray = {"Hello", "World"}; 452 | 453 | printArray(intArray); 454 | printArray(stringArray); 455 | } 456 | } 457 | ``` 458 | 459 | ### Bounded Type Parameters 460 | You can set bounds for type parameters to restrict the types that can be used. 461 | 462 | ### Example 463 | ```java 464 | public class Main { 465 | public static void printArray(T[] array) { 466 | for (T element : array) { 467 | System.out.println(element); 468 | } 469 | } 470 | 471 | public static void main(String[] args) { 472 | Integer[] intArray = {1, 2, 3, 4, 5}; 473 | Double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5}; 474 | 475 | printArray(intArray); 476 | printArray(doubleArray); 477 | } 478 | } 479 | ``` 480 | 481 | ### Generic Methods 482 | You can define methods with generic type parameters. 483 | 484 | ### Example 485 | ```java 486 | public class Main { 487 | public static void printArray(T[] array) { 488 | for (T element : array) { 489 | System.out.println(element); 490 | } 491 | } 492 | 493 | public static void main(String[] args) { 494 | Integer[] intArray = {1, 2, 3, 4, 5}; 495 | String[] stringArray = {"Hello", "World"}; 496 | 497 | printArray(intArray); 498 | printArray(stringArray); 499 | } 500 | } 501 | ``` 502 | 503 | ## Lambda Expressions 504 | Lambda expressions are used to provide the implementation of a functional interface. 505 | 506 | ### Example 507 | ```java 508 | import java.util.ArrayList; 509 | import java.util.List; 510 | 511 | public class Main { 512 | public static void main(String[] args) { 513 | List list = new ArrayList<>(); 514 | list.add("Apple"); 515 | list.add("Banana"); 516 | list.add("Cherry"); 517 | 518 | list.forEach(fruit -> System.out.println(fruit)); 519 | } 520 | } 521 | ``` 522 | 523 | ### Example with Functional Interface 524 | ```java 525 | import java.util.function.Predicate; 526 | 527 | public class Main { 528 | public static void main(String[] args) { 529 | Predicate isEven = (n) -> n % 2 == 0; 530 | System.out.println(isEven.test(4)); // Output: true 531 | } 532 | } 533 | ``` 534 | 535 | ## Streams 536 | Streams are used to process collections of objects. 537 | 538 | ### Example 539 | ```java 540 | import java.util.Arrays; 541 | import java.util.List; 542 | 543 | public class Main { 544 | public static void main(String[] args) { 545 | List list = Arrays.asList("Apple", "Banana", "Cherry"); 546 | 547 | list.stream() 548 | .filter(fruit -> fruit.startsWith("A")) 549 | .forEach(System.out::println); 550 | } 551 | } 552 | ``` 553 | 554 | ### Example with Stream Operations 555 | ```java 556 | import java.util.Arrays; 557 | import java.util.List; 558 | import java.util.stream.Collectors; 559 | 560 | public class Main { 561 | public static void main(String[] args) { 562 | List list = Arrays.asList("Apple", "Banana", "Cherry", "Date"); 563 | 564 | List result = list.stream() 565 | .filter(fruit -> fruit.startsWith("A")) 566 | .map(String::toUpperCase) 567 | .collect(Collectors.toList()); 568 | 569 | result.forEach(System.out::println); // Output: APPLE 570 | } 571 | } 572 | ``` 573 | 574 | ## Multithreading 575 | Multithreading is a Java feature that allows concurrent execution of two or more parts of a program. 576 | 577 | ### Example 578 | ```java 579 | class MyThread extends Thread { 580 | public void run() { 581 | System.out.println("Thread is running"); 582 | } 583 | } 584 | 585 | public class Main { 586 | public static void main(String[] args) { 587 | MyThread thread = new MyThread(); 588 | thread.start(); 589 | } 590 | } 591 | ``` 592 | 593 | ### Example with Runnable Interface 594 | ```java 595 | class MyRunnable implements Runnable { 596 | public void run() { 597 | System.out.println("Thread is running"); 598 | } 599 | } 600 | 601 | public class Main { 602 | public static void main(String[] args) { 603 | Thread thread = new Thread(new MyRunnable()); 604 | thread.start(); 605 | } 606 | } 607 | ``` 608 | 609 | ## File I/O 610 | Java provides several classes for file input and output. 611 | 612 | ### Example 613 | ```java 614 | import java.io.File; 615 | import java.io.FileWriter; 616 | import java.io.IOException; 617 | import java.util.Scanner; 618 | 619 | public class Main { 620 | public static void main(String[] args) { 621 | try { 622 | File myFile = new File("filename.txt"); 623 | if (myFile.createNewFile()) { 624 | System.out.println("File created: " + myFile.getName()); 625 | } else { 626 | System.out.println("File already exists."); 627 | } 628 | 629 | FileWriter myWriter = new FileWriter("filename.txt"); 630 | myWriter.write("Hello, World!"); 631 | myWriter.close(); 632 | System.out.println("Successfully wrote to the file."); 633 | 634 | Scanner myReader = new Scanner(myFile); 635 | while (myReader.hasNextLine()) { 636 | String data = myReader.nextLine(); 637 | System.out.println(data); 638 | } 639 | myReader.close(); 640 | } catch (IOException e) { 641 | System.out.println("An error occurred."); 642 | e.printStackTrace(); 643 | } 644 | } 645 | } 646 | ``` 647 | 648 | ### Example with BufferedReader and BufferedWriter 649 | ```java 650 | import java.io.*; 651 | 652 | public class Main { 653 | public static void main(String[] args) { 654 | try { 655 | BufferedWriter writer = new BufferedWriter(new FileWriter("filename.txt")); 656 | writer.write("Hello, World!"); 657 | writer.close(); 658 | 659 | BufferedReader reader = new BufferedReader(new FileReader("filename.txt")); 660 | String line; 661 | while ((line = reader.readLine()) != null) { 662 | System.out.println(line); 663 | } 664 | reader.close(); 665 | } catch (IOException e) { 666 | e.printStackTrace(); 667 | } 668 | } 669 | } 670 | ``` 671 | 672 | ## Networking 673 | Java provides the `java.net` package for networking applications. 674 | 675 | ### Example 676 | ```java 677 | import java.io.BufferedReader; 678 | import java.io.InputStreamReader; 679 | import java.net.HttpURLConnection; 680 | import java.net.URL; 681 | 682 | public class Main { 683 | public static void main(String[] args) { 684 | try { 685 | URL url = new URL("http://example.com"); 686 | HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 687 | conn.setRequestMethod("GET"); 688 | 689 | BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 690 | String inputLine; 691 | StringBuffer content = new StringBuffer(); 692 | while ((inputLine = in.readLine()) != null) { 693 | content.append(inputLine); 694 | } 695 | in.close(); 696 | conn.disconnect(); 697 | 698 | System.out.println(content.toString()); 699 | } catch (Exception e) { 700 | e.printStackTrace(); 701 | } 702 | } 703 | } 704 | ``` 705 | 706 | ### Example with ServerSocket and Socket 707 | ```java 708 | import java.io.*; 709 | import java.net.*; 710 | 711 | public class Main { 712 | public static void main(String[] args) { 713 | try { 714 | ServerSocket serverSocket = new ServerSocket(6666); 715 | Socket socket = serverSocket.accept(); 716 | DataInputStream dis = new DataInputStream(socket.getInputStream()); 717 | String str = dis.readUTF(); 718 | System.out.println("Message: " + str); 719 | serverSocket.close(); 720 | } catch (Exception e) { 721 | e.printStackTrace(); 722 | } 723 | } 724 | } 725 | ``` 726 | 727 | ## Reflection 728 | Reflection is a feature in Java that allows an executing Java program to examine or "reflect" upon itself, and manipulate the internal properties of the program. 729 | 730 | ### Example 731 | ```java 732 | import java.lang.reflect.Method; 733 | 734 | public class Main { 735 | public static void main(String[] args) { 736 | try { 737 | Class cls = Class.forName("java.util.ArrayList"); 738 | Method[] methods = cls.getDeclaredMethods(); 739 | for (Method method : methods) { 740 | System.out.println(method.getName()); 741 | } 742 | } catch (ClassNotFoundException e) { 743 | e.printStackTrace(); 744 | } 745 | } 746 | } 747 | ``` 748 | 749 | ### Example with Field Manipulation 750 | ```java 751 | import java.lang.reflect.Field; 752 | 753 | public class Main { 754 | public static void main(String[] args) { 755 | try { 756 | Class cls = Class.forName("java.util.ArrayList"); 757 | Field field = cls.getDeclaredField("size"); 758 | field.setAccessible(true); 759 | ArrayList list = new ArrayList<>(); 760 | list.add(1); 761 | System.out.println("Size before: " + field.get(list)); 762 | field.set(list, 10); 763 | System.out.println("Size after: " + field.get(list)); 764 | } catch (Exception e) { 765 | e.printStackTrace(); 766 | } 767 | } 768 | } 769 | ``` 770 | 771 | ## Annotations 772 | Annotations provide metadata about the program and are used to provide information to the compiler, to be processed at runtime, or to be used by tools. 773 | 774 | ### Example 775 | ```java 776 | import java.lang.annotation.*; 777 | 778 | @Retention(RetentionPolicy.RUNTIME) 779 | @Target(ElementType.METHOD) 780 | @interface MyAnnotation { 781 | String value(); 782 | } 783 | 784 | public class Main { 785 | @MyAnnotation(value = "Hello") 786 | public void myMethod() { 787 | System.out.println("My Method"); 788 | } 789 | 790 | public static void main(String[] args) { 791 | try { 792 | Method method = Main.class.getMethod("myMethod"); 793 | MyAnnotation annotation = method.getAnnotation(MyAnnotation.class); 794 | System.out.println(annotation.value()); 795 | } catch (NoSuchMethodException e) { 796 | e.printStackTrace(); 797 | } 798 | } 799 | } 800 | ``` 801 | 802 | ### Example with Custom Annotation 803 | ```java 804 | import java.lang.annotation.*; 805 | 806 | @Retention(RetentionPolicy.RUNTIME) 807 | @Target(ElementType.TYPE) 808 | @interface MyAnnotation { 809 | String value(); 810 | } 811 | 812 | @MyAnnotation(value = "Hello") 813 | public class Main { 814 | public static void main(String[] args) { 815 | MyAnnotation annotation = Main.class.getAnnotation(MyAnnotation.class); 816 | System.out.println(annotation.value()); 817 | } 818 | } 819 | ``` 820 | 821 | ## Serialization 822 | Serialization is the process of converting an object into a byte stream, and deserialization is the process of converting a byte stream back into an object. 823 | 824 | ### Example 825 | ```java 826 | import java.io.*; 827 | 828 | class Person implements Serializable { 829 | private static final long serialVersionUID = 1L; 830 | String name; 831 | int age; 832 | 833 | Person(String name, int age) { 834 | this.name = name; 835 | this.age = age; 836 | } 837 | } 838 | 839 | public class Main { 840 | public static void main(String[] args) { 841 | Person person = new Person("John", 30); 842 | 843 | // Serialization 844 | try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"))) { 845 | out.writeObject(person); 846 | } catch (IOException e) { 847 | e.printStackTrace(); 848 | } 849 | 850 | // Deserialization 851 | try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"))) { 852 | Person deserializedPerson = (Person) in.readObject(); 853 | System.out.println("Name: " + deserializedPerson.name + ", Age: " + deserializedPerson.age); 854 | } catch (IOException | ClassNotFoundException e) { 855 | e.printStackTrace(); 856 | } 857 | } 858 | } 859 | ``` 860 | 861 | ### Example with Externalizable Interface 862 | ```java 863 | import java.io.*; 864 | 865 | class Person implements Externalizable { 866 | String name; 867 | int age; 868 | 869 | public Person() {} 870 | 871 | Person(String name, int age) { 872 | this.name = name; 873 | this.age = age; 874 | } 875 | 876 | public void writeExternal(ObjectOutput out) throws IOException { 877 | out.writeObject(name); 878 | out.writeInt(age); 879 | } 880 | 881 | public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { 882 | name = (String) in.readObject(); 883 | age = in.readInt(); 884 | } 885 | } 886 | 887 | public class Main { 888 | public static void main(String[] args) { 889 | Person person = new Person("John", 30); 890 | 891 | // Serialization 892 | try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"))) { 893 | out.writeObject(person); 894 | } catch (IOException e) { 895 | e.printStackTrace(); 896 | } 897 | 898 | // Deserialization 899 | try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"))) { 900 | Person deserializedPerson = (Person) in.readObject(); 901 | System.out.println("Name: " + deserializedPerson.name + ", Age: " + deserializedPerson.age); 902 | } catch (IOException | ClassNotFoundException e) { 903 | e.printStackTrace(); 904 | } 905 | } 906 | } 907 | ``` 908 | 909 | ## JavaFX 910 | JavaFX is a software platform for creating and delivering desktop applications, as well as rich internet applications. 911 | 912 | ### Example 913 | ```java 914 | import javafx.application.Application; 915 | import javafx.scene.Scene; 916 | import javafx.scene.control.Button; 917 | import javafx.stage.Stage; 918 | 919 | public class Main extends Application { 920 | @Override 921 | public void start(Stage primaryStage) { 922 | Button btn = new Button("Click Me"); 923 | btn.setOnAction(e -> System.out.println("Hello, JavaFX!")); 924 | 925 | Scene scene = new Scene(btn, 200, 100); 926 | primaryStage.setScene(scene); 927 | primaryStage.setTitle("JavaFX Example"); 928 | primaryStage.show(); 929 | } 930 | 931 | public static void main(String[] args) { 932 | launch(args); 933 | } 934 | } 935 | ``` 936 | 937 | ### Example with Scene and Stage 938 | ```java 939 | import javafx.application.Application; 940 | import javafx.scene.Scene; 941 | import javafx.scene.control.Label; 942 | import javafx.stage.Stage; 943 | 944 | public class Main extends Application { 945 | @Override 946 | public void start(Stage primaryStage) { 947 | Label label = new Label("Hello, JavaFX!"); 948 | Scene scene = new Scene(label, 200, 100); 949 | primaryStage.setScene(scene); 950 | primaryStage.setTitle("JavaFX Example"); 951 | primaryStage.show(); 952 | } 953 | 954 | public static void main(String[] args) { 955 | launch(args); 956 | } 957 | } 958 | ``` 959 | 960 | ## Theory of Java 961 | 962 | Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It was developed by Sun Microsystems (now owned by Oracle Corporation) and released in 1995. Java applications are typically compiled to bytecode that can run on any Java Virtual Machine (JVM) regardless of the underlying computer architecture. 963 | 964 | One of the core principles of Java is its platform independence, which is achieved through the use of the JVM. The JVM allows Java programs to be written once and run anywhere, making Java a popular choice for cross-platform development. This is often referred to as the "write once, run anywhere" (WORA) capability of Java. 965 | 966 | Java's object-oriented nature allows developers to create modular programs and reusable code. Key concepts of object-oriented programming (OOP) such as inheritance, encapsulation, polymorphism, and abstraction are integral to Java. These principles help in organizing complex programs, making them easier to manage and extend. 967 | 968 | Java also emphasizes security and robustness. The language includes features such as automatic memory management (garbage collection), exception handling, and a strong type-checking mechanism. These features help in writing reliable and error-free code, reducing the likelihood of runtime errors and security vulnerabilities. 969 | 970 | In addition to its core language features, Java has a rich standard library that provides a wide range of functionalities, from data structures and algorithms to networking and graphical user interface (GUI) development. The extensive ecosystem of third-party libraries and frameworks further enhances Java's capabilities, making it suitable for a wide variety of applications, including web development, enterprise software, mobile applications, and more. 971 | 972 | # Using Common Java Libraries 973 | 974 | ## Introduction 975 | Java libraries are collections of pre-written code that developers can use to optimize tasks. This guide covers how to use some commonly used Java libraries. 976 | 977 | ## Apache Commons 978 | 979 | ### Apache Commons Lang 980 | Apache Commons Lang provides helper utilities for the java.lang API. 981 | 982 | ### Example 983 | Add the dependency to your `pom.xml` file: 984 | ```xml 985 | 986 | org.apache.commons 987 | commons-lang3 988 | 3.12.0 989 | 990 | ``` 991 | 992 | ### Usage 993 | ```java 994 | import org.apache.commons.lang3.StringUtils; 995 | 996 | public class Main { 997 | public static void main(String[] args) { 998 | String str = "Hello, World!"; 999 | System.out.println(StringUtils.reverse(str)); 1000 | } 1001 | } 1002 | ``` 1003 | 1004 | ### Apache Commons IO 1005 | Apache Commons IO provides utility classes for working with IO. 1006 | 1007 | ### Example 1008 | Add the dependency to your `pom.xml` file: 1009 | ```xml 1010 | 1011 | commons-io 1012 | commons-io 1013 | 2.11.0 1014 | 1015 | ``` 1016 | 1017 | ### Usage 1018 | ```java 1019 | import org.apache.commons.io.FileUtils; 1020 | 1021 | import java.io.File; 1022 | import java.io.IOException; 1023 | 1024 | public class Main { 1025 | public static void main(String[] args) { 1026 | File file = new File("example.txt"); 1027 | try { 1028 | FileUtils.writeStringToFile(file, "Hello, World!", "UTF-8"); 1029 | String content = FileUtils.readFileToString(file, "UTF-8"); 1030 | System.out.println(content); 1031 | } catch (IOException e) { 1032 | e.printStackTrace(); 1033 | } 1034 | } 1035 | } 1036 | ``` 1037 | 1038 | ## Google Guava 1039 | 1040 | ### Google Guava 1041 | Google Guava provides a set of core libraries that include new collection types, immutable collections, and more. 1042 | 1043 | ### Example 1044 | Add the dependency to your `pom.xml` file: 1045 | ```xml 1046 | 1047 | com.google.guava 1048 | guava 1049 | 31.0.1-jre 1050 | 1051 | ``` 1052 | 1053 | ### Usage 1054 | ```java 1055 | import com.google.common.collect.ImmutableList; 1056 | 1057 | public class Main { 1058 | public static void main(String[] args) { 1059 | ImmutableList list = ImmutableList.of("Apple", "Banana", "Cherry"); 1060 | System.out.println(list); 1061 | } 1062 | } 1063 | ``` 1064 | 1065 | ### Example with Optional 1066 | ```java 1067 | import com.google.common.base.Optional; 1068 | 1069 | public class Main { 1070 | public static void main(String[] args) { 1071 | Optional optional = Optional.of("Hello, World!"); 1072 | if (optional.isPresent()) { 1073 | System.out.println(optional.get()); 1074 | } 1075 | } 1076 | } 1077 | ``` 1078 | 1079 | ## Jackson 1080 | 1081 | ### Jackson 1082 | Jackson is a suite of data-processing tools for Java, including the flagship JSON parsing and generation library. 1083 | 1084 | ### Example 1085 | Add the dependency to your `pom.xml` file: 1086 | ```xml 1087 | 1088 | com.fasterxml.jackson.core 1089 | jackson-databind 1090 | 2.13.0 1091 | 1092 | ``` 1093 | 1094 | ### Usage 1095 | ```java 1096 | import com.fasterxml.jackson.databind.ObjectMapper; 1097 | 1098 | public class Main { 1099 | public static void main(String[] args) { 1100 | ObjectMapper mapper = new ObjectMapper(); 1101 | String json = "{\"name\":\"John\", \"age\":30}"; 1102 | try { 1103 | Person person = mapper.readValue(json, Person.class); 1104 | System.out.println(person.getName()); 1105 | } catch (Exception e) { 1106 | e.printStackTrace(); 1107 | } 1108 | } 1109 | } 1110 | 1111 | class Person { 1112 | private String name; 1113 | private int age; 1114 | 1115 | // Getters and setters 1116 | public String getName() { 1117 | return name; 1118 | } 1119 | 1120 | public void setName(String name) { 1121 | this.name = name; 1122 | } 1123 | 1124 | public int getAge() { 1125 | return age; 1126 | } 1127 | 1128 | public void setAge(int age) { 1129 | this.age = age; 1130 | } 1131 | } 1132 | ``` 1133 | 1134 | ## Log4j 1135 | 1136 | ### Log4j 1137 | Log4j is a reliable, fast, and flexible logging framework (APIs) written in Java. 1138 | 1139 | ### Example 1140 | Add the dependency to your `pom.xml` file: 1141 | ```xml 1142 | 1143 | org.apache.logging.log4j 1144 | log4j-core 1145 | 2.14.1 1146 | 1147 | 1148 | org.apache.logging.log4j 1149 | log4j-api 1150 | 2.14.1 1151 | 1152 | ``` 1153 | 1154 | ### Usage 1155 | ```java 1156 | import org.apache.logging.log4j.LogManager; 1157 | import org.apache.logging.log4j.Logger; 1158 | 1159 | public class Main { 1160 | private static final Logger logger = LogManager.getLogger(Main.class); 1161 | 1162 | public static void main(String[] args) { 1163 | logger.info("Hello, Log4j!"); 1164 | } 1165 | } 1166 | ``` 1167 | 1168 | ## Hibernate 1169 | 1170 | ### Hibernate 1171 | Hibernate is an object-relational mapping (ORM) tool for the Java programming language. 1172 | 1173 | ### Example 1174 | Add the dependency to your `pom.xml` file: 1175 | ```xml 1176 | 1177 | org.hibernate 1178 | hibernate-core 1179 | 5.5.7.Final 1180 | 1181 | ``` 1182 | 1183 | ### Usage 1184 | ```java 1185 | import org.hibernate.Session; 1186 | import org.hibernate.SessionFactory; 1187 | import org.hibernate.cfg.Configuration; 1188 | 1189 | public class Main { 1190 | public static void main(String[] args) { 1191 | SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); 1192 | Session session = factory.openSession(); 1193 | session.beginTransaction(); 1194 | 1195 | Person person = new Person(); 1196 | person.setName("John"); 1197 | person.setAge(30); 1198 | 1199 | session.save(person); 1200 | session.getTransaction().commit(); 1201 | session.close(); 1202 | } 1203 | } 1204 | 1205 | @Entity 1206 | @Table(name = "person") 1207 | class Person { 1208 | @Id 1209 | @GeneratedValue(strategy = GenerationType.IDENTITY) 1210 | private int id; 1211 | 1212 | private String name; 1213 | private int age; 1214 | 1215 | // Getters and setters 1216 | public int getId() { 1217 | return id; 1218 | } 1219 | 1220 | public void setId(int id) { 1221 | this.id = id; 1222 | } 1223 | 1224 | public String getName() { 1225 | return name; 1226 | } 1227 | 1228 | public void setName(String name) { 1229 | this.name = name; 1230 | } 1231 | 1232 | public int getAge() { 1233 | return age; 1234 | } 1235 | 1236 | public void setAge(int age) { 1237 | this.age = age; 1238 | } 1239 | } 1240 | ``` 1241 | 1242 | ## Apache HttpClient 1243 | 1244 | ### Apache HttpClient 1245 | Apache HttpClient provides a robust and flexible solution for HTTP communication. 1246 | 1247 | ### Example 1248 | Add the dependency to your `pom.xml` file: 1249 | ```xml 1250 | 1251 | org.apache.httpcomponents 1252 | httpclient 1253 | 4.5.13 1254 | 1255 | ``` 1256 | 1257 | ### Usage 1258 | ```java 1259 | import org.apache.http.HttpEntity; 1260 | import org.apache.http.client.methods.CloseableHttpResponse; 1261 | import org.apache.http.client.methods.HttpGet; 1262 | import org.apache.http.impl.client.CloseableHttpClient; 1263 | import org.apache.http.impl.client.HttpClients; 1264 | import org.apache.http.util.EntityUtils; 1265 | 1266 | import java.io.IOException; 1267 | 1268 | public class Main { 1269 | public static void main(String[] args) { 1270 | CloseableHttpClient httpClient = HttpClients.createDefault(); 1271 | HttpGet request = new HttpGet("https://api.github.com"); 1272 | 1273 | try (CloseableHttpResponse response = httpClient.execute(request)) { 1274 | HttpEntity entity = response.getEntity(); 1275 | if (entity != null) { 1276 | String result = EntityUtils.toString(entity); 1277 | System.out.println(result); 1278 | } 1279 | } catch (IOException e) { 1280 | e.printStackTrace(); 1281 | } 1282 | } 1283 | } 1284 | ``` 1285 | 1286 | ## Conclusion 1287 | This guide provides an overview of advanced Java topics. For more detailed information, refer to the [Oracle Java Documentation](https://docs.oracle.com/en/java/). 1288 | -------------------------------------------------------------------------------- /lesson1/Arrays/ArrayLists.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class ArrayLists { 4 | 5 | public static void main(String[] args) { 6 | // Create a new ArrayList to hold String elements 7 | ArrayList list = new ArrayList<>(); 8 | 9 | // Add elements to the ArrayList 10 | list.add("Apple"); 11 | list.add("Banana"); 12 | list.add("Cherry"); 13 | 14 | // Iterate through the ArrayList and print each element 15 | for (String fruit : list) { 16 | System.out.println("Fruit: " + fruit); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /lesson1/Arrays/ArrayManipulation.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class ArrayManipulation { 4 | 5 | public static void main(String[] args) { 6 | // Declare and initialize an array of integers 7 | int[] numbers = {5, 3, 8, 1, 2}; 8 | 9 | // Sort the array 10 | Arrays.sort(numbers); 11 | System.out.println("Sorted array: " + Arrays.toString(numbers)); 12 | 13 | // Fill the array with a specific value 14 | Arrays.fill(numbers, 10); 15 | System.out.println("Array filled with 10: " + Arrays.toString(numbers)); 16 | 17 | // Copy the array 18 | int[] copiedArray = Arrays.copyOf(numbers, numbers.length); 19 | System.out.println("Copied array: " + Arrays.toString(copiedArray)); 20 | 21 | // Compare two arrays 22 | boolean areEqual = Arrays.equals(numbers, copiedArray); 23 | System.out.println("Are the original and copied arrays equal? " + areEqual); 24 | 25 | // Search for an element in the array 26 | int index = Arrays.binarySearch(numbers, 10); 27 | System.out.println("Index of element 10: " + index); 28 | 29 | // Declare and initialize a 2D array 30 | int[][] matrix = { 31 | {1, 2, 3}, 32 | {4, 5, 6}, 33 | {7, 8, 9} 34 | }; 35 | 36 | // Print the 2D array 37 | System.out.println("2D array: " + Arrays.deepToString(matrix)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /lesson1/Arrays/Arrays.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Sandlie101G12B/Java-tutorials-for-beginners/9d97924aef2d47e45d6d3b607b5d371cc61549bb/lesson1/Arrays/Arrays.class -------------------------------------------------------------------------------- /lesson1/Arrays/Arrays.java: -------------------------------------------------------------------------------- 1 | 2 | public class Arrays { 3 | 4 | public static void main(String[] args) { 5 | int[] arr = new int[5]; // Declare an array of integers with size 5 6 | arr[0] = 10; // Initialize the first element 7 | arr[1] = 20; // Initialize the second element 8 | arr[2] = 30; // Initialize the third element 9 | arr[3] = 40; // Initialize the fourth element 10 | arr[4] = 50; // Initialize the fifth element 11 | 12 | // Loop through the array and print each element 13 | for (int i = 0; i < arr.length; i++) { 14 | System.out.println("Element at index " + i + ": " + arr[i]); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /lesson1/Arrays/ArraysExample.java: -------------------------------------------------------------------------------- 1 | 2 | public class ArraysExample { 3 | 4 | public static void main(String[] args) { 5 | // Declare and initialize an array of integers 6 | int[] numbers = {1, 2, 3, 4, 5}; 7 | 8 | // Access and print elements of the array 9 | System.out.println("First element: " + numbers[0]); 10 | System.out.println("Second element: " + numbers[1]); 11 | 12 | // Modify an element of the array 13 | numbers[2] = 10; 14 | System.out.println("Modified third element: " + numbers[2]); 15 | 16 | // Iterate through the array using a for loop 17 | System.out.print("Array elements: "); 18 | for (int i = 0; i < numbers.length; i++) { 19 | System.out.print(numbers[i] + " "); 20 | } 21 | System.out.println(); 22 | 23 | // Iterate through the array using a for-each loop 24 | System.out.print("Array elements (for-each): "); 25 | for (int number : numbers) { 26 | System.out.print(number + " "); 27 | } 28 | System.out.println(); 29 | 30 | // Declare and initialize a 2D array 31 | int[][] matrix = { 32 | {1, 2, 3}, 33 | {4, 5, 6}, 34 | {7, 8, 9} 35 | }; 36 | 37 | // Access and print elements of the 2D array 38 | System.out.println("Element at (0,0): " + matrix[0][0]); 39 | System.out.println("Element at (1,1): " + matrix[1][1]); 40 | 41 | // Iterate through the 2D array using nested for loops 42 | System.out.println("2D array elements:"); 43 | for (int i = 0; i < matrix.length; i++) { 44 | for (int j = 0; j < matrix[i].length; j++) { 45 | System.out.print(matrix[i][j] + " "); 46 | } 47 | System.out.println(); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /lesson1/Arrays/HashMaps.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashMap; 3 | 4 | public class HashMaps { 5 | 6 | public static void main(String[] args) { 7 | HashMap map = new HashMap<>(); 8 | map.put(1, "One"); 9 | map.put(2, "Two"); 10 | map.put(3, "Three"); 11 | 12 | for (Integer key : map.keySet()) { 13 | System.out.println("Key: " + key + ", Value: " + map.get(key)); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lesson1/Basic syntax/BasicSyntax.java: -------------------------------------------------------------------------------- 1 | 2 | public class BasicSyntax { 3 | 4 | // The main method is the entry point of any Java application 5 | public static void main(String[] args) { 6 | // Print a message to the console 7 | System.out.println("Hello, World!"); 8 | 9 | // Variable declaration and initialization 10 | int number = 10; // Integer variable to store whole numbers 11 | double decimal = 5.5; // Double variable to store decimal numbers 12 | String text = "Java"; // String variable to store text 13 | boolean flag = true; // Boolean variable to store true/false values 14 | 15 | // Printing variables to the console 16 | System.out.println("Number: " + number); // Prints the value of the integer variable 17 | System.out.println("Decimal: " + decimal); // Prints the value of the double variable 18 | System.out.println("Text: " + text); // Prints the value of the string variable 19 | System.out.println("Flag: " + flag); // Prints the value of the boolean variable 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /lesson1/Basic syntax/Encapsulation.java: -------------------------------------------------------------------------------- 1 | 2 | public class Encapsulation { 3 | 4 | public static void main(String[] args) { 5 | Student student = new Student(); // Create a new Student object 6 | student.setName("Alice"); // Set the name of the student 7 | student.setAge(20); // Set the age of the student 8 | 9 | System.out.println("Name: " + student.getName()); // Print the name of the student 10 | System.out.println("Age: " + student.getAge()); // Print the age of the student 11 | } 12 | } 13 | 14 | class Student { 15 | 16 | private String name; // Private field to store the name of the student 17 | private int age; // Private field to store the age of the student 18 | 19 | // Getter method to get the name of the student 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | // Setter method to set the name of the student 25 | public void setName(String name) { 26 | this.name = name; 27 | } 28 | 29 | // Getter method to get the age of the student 30 | public int getAge() { 31 | return age; 32 | } 33 | 34 | // Setter method to set the age of the student 35 | public void setAge(int age) { 36 | this.age = age; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /lesson1/Basic syntax/FinallyBlock.java: -------------------------------------------------------------------------------- 1 | public class FinallyBlock { 2 | 3 | public static void main(String[] args) { 4 | try { 5 | int result = 10 / 0; 6 | System.out.println("Result: " + result); 7 | } catch (ArithmeticException e) { 8 | System.out.println("Error: Division by zero"); 9 | } finally { 10 | System.out.println("This block is always executed"); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /lesson1/Basic syntax/MethodsAndFunctions.java: -------------------------------------------------------------------------------- 1 | 2 | public class MethodsAndFunctions { 3 | 4 | public static void main(String[] args) { 5 | int result = add(5, 3); // Call the add method with arguments 5 and 3 6 | System.out.println("Sum: " + result); // Print the result 7 | } 8 | 9 | // Method to add two numbers 10 | public static int add(int a, int b) { 11 | return a + b; // Return the sum of a and b 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /lesson1/Basic syntax/Operators.java: -------------------------------------------------------------------------------- 1 | 2 | public class Operators { 3 | 4 | public static void main(String[] args) { 5 | int a = 10; // Declare and initialize an integer variable a 6 | int b = 5; // Declare and initialize an integer variable b 7 | 8 | // Arithmetic Operators 9 | System.out.println("Addition: " + (a + b)); // Adds a and b 10 | System.out.println("Subtraction: " + (a - b)); // Subtracts b from a 11 | System.out.println("Multiplication: " + (a * b)); // Multiplies a and b 12 | System.out.println("Division: " + (a / b)); // Divides a by b 13 | System.out.println("Modulus: " + (a % b)); // Remainder of a divided by b 14 | 15 | // Relational Operators 16 | System.out.println("Equal to: " + (a == b)); // Checks if a is equal to b 17 | System.out.println("Not equal to: " + (a != b)); // Checks if a is not equal to b 18 | System.out.println("Greater than: " + (a > b)); // Checks if a is greater than b 19 | System.out.println("Less than: " + (a < b)); // Checks if a is less than b 20 | 21 | // Logical Operators 22 | boolean x = true; // Declare and initialize a boolean variable x 23 | boolean y = false; // Declare and initialize a boolean variable y 24 | System.out.println("Logical AND: " + (x && y)); // Logical AND operation 25 | System.out.println("Logical OR: " + (x || y)); // Logical OR operation 26 | System.out.println("Logical NOT: " + (!x)); // Logical NOT operation 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /lesson1/Basic syntax/ThrowingExceptions.java: -------------------------------------------------------------------------------- 1 | 2 | public class ThrowingExceptions { 3 | 4 | public static void main(String[] args) { 5 | try { 6 | checkAge(15); 7 | } catch (Exception e) { 8 | System.out.println("Exception caught: " + e.getMessage()); 9 | } 10 | } 11 | 12 | public static void checkAge(int age) throws Exception { 13 | if (age < 18) { 14 | throw new Exception("Age must be 18 or older"); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /lesson1/Basic syntax/TryCatchBlocks.java: -------------------------------------------------------------------------------- 1 | 2 | public class TryCatchBlocks { 3 | 4 | public static void main(String[] args) { 5 | try { 6 | int result = 10 / 0; 7 | System.out.println("Result: " + result); 8 | } catch (ArithmeticException e) { 9 | System.out.println("Error: Division by zero"); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /lesson1/Basic syntax/VariablesAndDataTypes.java: -------------------------------------------------------------------------------- 1 | 2 | public class VariablesAndDataTypes { 3 | 4 | public static void main(String[] args) { 5 | int myInt = 5; 6 | double myDouble = 5.99; 7 | String myString = "Hello"; 8 | boolean myBoolean = true; 9 | 10 | System.out.println("Integer: " + myInt); 11 | System.out.println("Double: " + myDouble); 12 | System.out.println("String: " + myString); 13 | System.out.println("Boolean: " + myBoolean); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /lesson1/Classes/AccessModifiers.java: -------------------------------------------------------------------------------- 1 | 2 | public class AccessModifiers { 3 | 4 | public static void main(String[] args) { 5 | Animal animal = new Animal(); // Create a new Animal object 6 | animal.setName("Lion"); // Set the name of the animal 7 | System.out.println("Animal name: " + animal.getName()); // Print the name of the animal 8 | } 9 | } 10 | 11 | class Animal { 12 | 13 | private String name; // Private field to store the name of the animal 14 | 15 | // Setter method to set the name of the animal 16 | public void setName(String name) { 17 | this.name = name; 18 | } 19 | 20 | // Getter method to get the name of the animal 21 | public String getName() { 22 | return name; 23 | } 24 | 25 | // Public method 26 | public void publicMethod() { 27 | System.out.println("Public method"); 28 | } 29 | 30 | // Private method 31 | private void privateMethod() { 32 | System.out.println("Private method"); 33 | } 34 | 35 | // Protected method 36 | protected void protectedMethod() { 37 | System.out.println("Protected method"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /lesson1/Classes/ClassManipulation.java: -------------------------------------------------------------------------------- 1 | 2 | public class ClassManipulation { 3 | 4 | public static void main(String[] args) { 5 | // Create an instance of the Person class 6 | Person person = new Person("John", 25); 7 | 8 | // Access and modify fields using getter and setter methods 9 | System.out.println("Name: " + person.getName()); 10 | System.out.println("Age: " + person.getAge()); 11 | 12 | person.setName("Jane"); 13 | person.setAge(30); 14 | 15 | System.out.println("Updated Name: " + person.getName()); 16 | System.out.println("Updated Age: " + person.getAge()); 17 | 18 | // Call a method of the Person class 19 | person.displayInfo(); 20 | } 21 | } 22 | 23 | // Define the Person class 24 | class Person { 25 | 26 | // Private fields 27 | private String name; 28 | private int age; 29 | 30 | // Constructor to initialize fields 31 | public Person(String name, int age) { 32 | this.name = name; 33 | this.age = age; 34 | } 35 | 36 | // Getter method for name 37 | public String getName() { 38 | return name; 39 | } 40 | 41 | // Setter method for name 42 | public void setName(String name) { 43 | this.name = name; 44 | } 45 | 46 | // Getter method for age 47 | public int getAge() { 48 | return age; 49 | } 50 | 51 | // Setter method for age 52 | public void setAge(int age) { 53 | this.age = age; 54 | } 55 | 56 | // Method to display information 57 | public void displayInfo() { 58 | System.out.println("Person Info: Name = " + name + ", Age = " + age); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /lesson1/Classes/ClassesAndObjects.java: -------------------------------------------------------------------------------- 1 | 2 | public class ClassesAndObjects { 3 | 4 | public static void main(String[] args) { 5 | Car myCar = new Car(); // Create a new Car object 6 | myCar.setModel("Toyota"); // Set the model of the car 7 | System.out.println("Car model: " + myCar.getModel()); // Print the model of the car 8 | } 9 | } 10 | 11 | class Car { 12 | 13 | private String model; // Private field to store the model of the car 14 | 15 | // Setter method to set the model of the car 16 | public void setModel(String model) { 17 | this.model = model; 18 | } 19 | 20 | // Getter method to get the model of the car 21 | public String getModel() { 22 | return model; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /lesson1/Classes/Constructors.java: -------------------------------------------------------------------------------- 1 | 2 | public class Constructors { 3 | 4 | public static void main(String[] args) { 5 | Person person = new Person("John", 25); // Create a new Person object with name "John" and age 25 6 | System.out.println("Name: " + person.getName()); // Print the name of the person 7 | System.out.println("Age: " + person.getAge()); // Print the age of the person 8 | } 9 | } 10 | 11 | class Person { 12 | 13 | private String name; // Private field to store the name of the person 14 | private int age; // Private field to store the age of the person 15 | 16 | // Constructor to initialize the name and age of the person 17 | public Person(String name, int age) { 18 | this.name = name; 19 | this.age = age; 20 | } 21 | 22 | // Getter method to get the name of the person 23 | public String getName() { 24 | return name; 25 | } 26 | 27 | // Getter method to get the age of the person 28 | public int getAge() { 29 | return age; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /lesson1/Loops/ControlFlow.java: -------------------------------------------------------------------------------- 1 | 2 | public class ControlFlow { 3 | 4 | public static void main(String[] args) { 5 | int number = 10; // Declare and initialize an integer variable 6 | 7 | // if-else statement 8 | if (number > 0) { 9 | System.out.println("Positive number"); // Executes if number is greater than 0 10 | } else { 11 | System.out.println("Non-positive number"); // Executes if number is not greater than 0 12 | } 13 | 14 | // switch statement 15 | int day = 3; // Declare and initialize an integer variable representing a day 16 | switch (day) { 17 | case 1: 18 | System.out.println("Monday"); // Executes if day is 1 19 | break; 20 | case 2: 21 | System.out.println("Tuesday"); // Executes if day is 2 22 | break; 23 | case 3: 24 | System.out.println("Wednesday"); // Executes if day is 3 25 | break; 26 | default: 27 | System.out.println("Other day"); // Executes if day is not 1, 2, or 3 28 | break; 29 | } 30 | 31 | // while loop 32 | int count = 0; 33 | while (count < 5) { 34 | System.out.println("Count: " + count); // Executes while count is less than 5 35 | count++; 36 | } 37 | 38 | // do-while loop 39 | count = 0; 40 | do { 41 | System.out.println("Count in do-while: " + count); // Executes at least once 42 | count++; 43 | } while (count < 5); 44 | 45 | // for loop 46 | for (int i = 0; i < 5; i++) { 47 | System.out.println("For loop iteration: " + i); // Executes 5 times 48 | } 49 | 50 | // for-each loop 51 | int[] numbers = {1, 2, 3, 4, 5}; 52 | for (int num : numbers) { 53 | System.out.println("For-each loop value: " + num); // Iterates through each element in the array 54 | } 55 | 56 | // break statement 57 | for (int i = 0; i < 10; i++) { 58 | if (i == 5) { 59 | break; // Exits the loop when i is 5 60 | } 61 | System.out.println("Break example: " + i); 62 | } 63 | 64 | // continue statement 65 | for (int i = 0; i < 10; i++) { 66 | if (i % 2 == 0) { 67 | continue; // Skips the current iteration if i is even 68 | } 69 | System.out.println("Continue example: " + i); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /lesson1/Loops/Loops.java: -------------------------------------------------------------------------------- 1 | 2 | public class Loops { 3 | 4 | public static void main(String[] args) { 5 | // for loop 6 | for (int i = 0; i < 5; i++) { 7 | System.out.println("For loop iteration: " + i); // Executes 5 times, i ranges from 0 to 4 8 | } 9 | 10 | // while loop 11 | int j = 0; // Initialize loop control variable 12 | while (j < 5) { 13 | System.out.println("While loop iteration: " + j); // Executes while j is less than 5 14 | j++; // Increment loop control variable 15 | } 16 | 17 | // do-while loop 18 | int k = 0; // Initialize loop control variable 19 | do { 20 | System.out.println("Do-while loop iteration: " + k); // Executes at least once 21 | k++; // Increment loop control variable 22 | } while (k < 5); // Condition is checked after the loop body 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /lesson2/DatabaseConnectivity/CRUDOperations.java: -------------------------------------------------------------------------------- 1 | 2 | import java.sql.*; 3 | 4 | public class CRUDOperations { 5 | 6 | public static void main(String[] args) { 7 | // Database URL, username, and password 8 | String url = "jdbc:mysql://localhost:3306/mydatabase"; 9 | String user = "root"; 10 | String password = "password"; 11 | 12 | // Establishing a connection to the database 13 | try (Connection connection = DriverManager.getConnection(url, user, password)) { 14 | // Create operation 15 | String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)"; 16 | try (PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) { 17 | preparedStatement.setString(1, "John Doe"); 18 | preparedStatement.setString(2, "john.doe@example.com"); 19 | preparedStatement.executeUpdate(); // Executing the insert statement 20 | } 21 | 22 | // Read operation 23 | String selectSQL = "SELECT * FROM users"; 24 | try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(selectSQL)) { 25 | while (resultSet.next()) { 26 | System.out.println("User: " + resultSet.getString("name") + ", Email: " + resultSet.getString("email")); 27 | } 28 | } 29 | 30 | // Update operation 31 | String updateSQL = "UPDATE users SET email = ? WHERE name = ?"; 32 | try (PreparedStatement preparedStatement = connection.prepareStatement(updateSQL)) { 33 | preparedStatement.setString(1, "new.email@example.com"); 34 | preparedStatement.setString(2, "John Doe"); 35 | preparedStatement.executeUpdate(); // Executing the update statement 36 | } 37 | 38 | // Delete operation 39 | String deleteSQL = "DELETE FROM users WHERE name = ?"; 40 | try (PreparedStatement preparedStatement = connection.prepareStatement(deleteSQL)) { 41 | preparedStatement.setString(1, "John Doe"); 42 | preparedStatement.executeUpdate(); // Executing the delete statement 43 | } 44 | 45 | } catch (SQLException e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /lesson2/DatabaseConnectivity/DatabaseConnection.java: -------------------------------------------------------------------------------- 1 | 2 | import java.sql.Connection; 3 | import java.sql.DriverManager; 4 | import java.sql.SQLException; 5 | 6 | public class DatabaseConnection { 7 | 8 | public static void main(String[] args) { 9 | // Database URL, username, and password 10 | String url = "jdbc:mysql://localhost:3306/mydatabase"; 11 | String user = "root"; 12 | String password = "password"; 13 | 14 | // Establishing a connection to the database 15 | try { 16 | Connection connection = DriverManager.getConnection(url, user, password); 17 | System.out.println("Connected to the database."); 18 | connection.close(); // Closing the connection 19 | } catch (SQLException e) { 20 | e.printStackTrace(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /lesson2/FileHandling/ReadingWritingFiles.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.*; 3 | 4 | public class ReadingWritingFiles { 5 | 6 | public static void main(String[] args) { 7 | String filePath = "example.txt"; 8 | 9 | // Writing to a file using FileWriter 10 | try (FileWriter writer = new FileWriter(filePath)) { 11 | writer.write("Hello, world!"); // Writing data to the file 12 | } catch (IOException e) { 13 | e.printStackTrace(); 14 | } 15 | 16 | // Reading from a file using BufferedReader 17 | try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { 18 | String line; 19 | while ((line = reader.readLine()) != null) { 20 | System.out.println(line); // Reading data from the file 21 | } 22 | } catch (IOException e) { 23 | e.printStackTrace(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /lesson2/FileHandling/WorkingWithStreams.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.*; 3 | 4 | public class WorkingWithStreams { 5 | 6 | public static void main(String[] args) { 7 | String filePath = "example.txt"; 8 | 9 | // Writing to a file using OutputStream 10 | try (OutputStream outputStream = new FileOutputStream(filePath)) { 11 | String data = "Hello, world!"; 12 | outputStream.write(data.getBytes()); // Writing data to the file 13 | } catch (IOException e) { 14 | e.printStackTrace(); 15 | } 16 | 17 | // Reading from a file using InputStream 18 | try (InputStream inputStream = new FileInputStream(filePath)) { 19 | int content; 20 | while ((content = inputStream.read()) != -1) { 21 | System.out.print((char) content); // Reading data from the file 22 | } 23 | } catch (IOException e) { 24 | e.printStackTrace(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /lesson2/MultithreadingConcurrency/Synchronization.java: -------------------------------------------------------------------------------- 1 | 2 | class Counter { 3 | 4 | private int count = 0; 5 | 6 | // Synchronization ensures that only one thread can access the increment method at a time. 7 | public synchronized void increment() { 8 | count++; 9 | } 10 | 11 | public int getCount() { 12 | return count; 13 | } 14 | } 15 | 16 | public class Synchronization { 17 | 18 | public static void main(String[] args) { 19 | Counter counter = new Counter(); 20 | 21 | // Creating two threads that will increment the counter 22 | Thread t1 = new Thread(() -> { 23 | for (int i = 0; i < 1000; i++) { 24 | counter.increment(); 25 | } 26 | }); 27 | 28 | Thread t2 = new Thread(() -> { 29 | for (int i = 0; i < 1000; i++) { 30 | counter.increment(); 31 | } 32 | }); 33 | 34 | // Starting the threads 35 | t1.start(); 36 | t2.start(); 37 | 38 | // Waiting for both threads to finish 39 | try { 40 | t1.join(); 41 | t2.join(); 42 | } catch (InterruptedException e) { 43 | e.printStackTrace(); 44 | } 45 | 46 | // Printing the final count 47 | System.out.println("Count: " + counter.getCount()); // Outputs: Count: 2000 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /lesson2/MultithreadingConcurrency/Threads.java: -------------------------------------------------------------------------------- 1 | 2 | class MyThread extends Thread { 3 | 4 | // The run method contains the code that constitutes the new thread. 5 | public void run() { 6 | System.out.println("Thread is running."); 7 | } 8 | } 9 | 10 | class MyRunnable implements Runnable { 11 | 12 | // The run method contains the code that constitutes the new thread. 13 | public void run() { 14 | System.out.println("Runnable is running."); 15 | } 16 | } 17 | 18 | public class Threads { 19 | 20 | public static void main(String[] args) { 21 | // Creating a new thread by extending the Thread class 22 | MyThread thread = new MyThread(); 23 | thread.start(); // Starts the thread and calls the run method 24 | 25 | // Creating a new thread by implementing the Runnable interface 26 | Thread runnableThread = new Thread(new MyRunnable()); 27 | runnableThread.start(); // Starts the thread and calls the run method 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /lesson2/OOPAdvanced/Abstraction.java: -------------------------------------------------------------------------------- 1 | 2 | abstract class Animal { 3 | 4 | // Abstraction allows us to define methods that must be implemented by subclasses. 5 | // This is an abstract method. 6 | public abstract void sound(); 7 | } 8 | 9 | class Dog extends Animal { 10 | 11 | // Implementing the abstract method for Dog 12 | @Override 13 | public void sound() { 14 | System.out.println("The dog barks."); 15 | } 16 | } 17 | 18 | interface AnimalInterface { 19 | 20 | // Interfaces can also be used to achieve abstraction. 21 | void sound(); 22 | } 23 | 24 | class Cat implements AnimalInterface { 25 | 26 | // Implementing the interface method for Cat 27 | @Override 28 | public void sound() { 29 | System.out.println("The cat meows."); 30 | } 31 | } 32 | 33 | public class Abstraction { 34 | 35 | public static void main(String[] args) { 36 | // Creating an instance of Dog 37 | Animal myDog = new Dog(); 38 | myDog.sound(); // Outputs: The dog barks. 39 | 40 | // Creating an instance of Cat 41 | AnimalInterface myCat = new Cat(); 42 | myCat.sound(); // Outputs: The cat meows. 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /lesson2/OOPAdvanced/Inheritance.java: -------------------------------------------------------------------------------- 1 | 2 | class Animal { 3 | 4 | // Inheritance allows a class to inherit fields and methods from another class. 5 | // This method will be inherited by subclasses. 6 | public void eat() { 7 | System.out.println("This animal eats food."); 8 | } 9 | } 10 | 11 | class Dog extends Animal { 12 | 13 | // This method is specific to the Dog class. 14 | public void bark() { 15 | System.out.println("The dog barks."); 16 | } 17 | } 18 | 19 | public class Inheritance { 20 | 21 | public static void main(String[] args) { 22 | // Creating an instance of Dog 23 | Dog myDog = new Dog(); 24 | 25 | // The Dog class inherits the eat method from the Animal class. 26 | myDog.eat(); // Outputs: This animal eats food. 27 | myDog.bark(); // Outputs: The dog barks. 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /lesson2/OOPAdvanced/Polymorphism.java: -------------------------------------------------------------------------------- 1 | 2 | class Animal { 3 | 4 | // Polymorphism allows methods to do different things based on the object it is acting upon. 5 | // This method will be overridden in subclasses. 6 | public void sound() { 7 | System.out.println("This animal makes a sound."); 8 | } 9 | } 10 | 11 | class Dog extends Animal { 12 | 13 | // Overriding the sound method for Dog 14 | @Override 15 | public void sound() { 16 | System.out.println("The dog barks."); 17 | } 18 | } 19 | 20 | class Cat extends Animal { 21 | 22 | // Overriding the sound method for Cat 23 | @Override 24 | public void sound() { 25 | System.out.println("The cat meows."); 26 | } 27 | } 28 | 29 | public class Polymorphism { 30 | 31 | public static void main(String[] args) { 32 | // Polymorphism allows us to use a superclass reference to refer to a subclass object. 33 | Animal myDog = new Dog(); 34 | Animal myCat = new Cat(); 35 | 36 | // The actual method that gets called is determined at runtime. 37 | myDog.sound(); // Outputs: The dog barks. 38 | myCat.sound(); // Outputs: The cat meows. 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /lesson3/DesignPatterns/DependencyInjection.java: -------------------------------------------------------------------------------- 1 | // Service class with a method to serve 2 | class Service { 3 | public void serve() { 4 | System.out.println("Service is serving."); 5 | } 6 | } 7 | 8 | // Client class that depends on Service 9 | class Client { 10 | private Service service; 11 | 12 | // Constructor to inject the Service dependency 13 | public Client(Service service) { 14 | this.service = service; 15 | } 16 | 17 | // Method to use the Service 18 | public void doSomething() { 19 | service.serve(); 20 | } 21 | } 22 | 23 | // Main class to demonstrate Dependency Injection 24 | public class DependencyInjection { 25 | public static void main(String[] args) { 26 | // Create a Service object 27 | Service service = new Service(); 28 | // Inject the Service object into the Client 29 | Client client = new Client(service); 30 | // Call the doSomething method of the Client 31 | client.doSomething(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /lesson3/DesignPatterns/FactoryPattern.java: -------------------------------------------------------------------------------- 1 | // Interface for Shape 2 | 3 | interface Shape { 4 | 5 | void draw(); 6 | } 7 | 8 | // Implementation of Circle 9 | class Circle implements Shape { 10 | 11 | @Override 12 | public void draw() { 13 | System.out.println("Drawing a Circle."); 14 | } 15 | } 16 | 17 | // Implementation of Square 18 | class Square implements Shape { 19 | 20 | @Override 21 | public void draw() { 22 | System.out.println("Drawing a Square."); 23 | } 24 | } 25 | 26 | // Factory class to generate objects of concrete classes based on given information 27 | class ShapeFactory { 28 | 29 | // Method to get an object of a specific shape type 30 | public Shape getShape(String shapeType) { 31 | if (shapeType == null) { 32 | return null; 33 | } 34 | if (shapeType.equalsIgnoreCase("CIRCLE")) { 35 | return new Circle(); 36 | } else if (shapeType.equalsIgnoreCase("SQUARE")) { 37 | return new Square(); 38 | } 39 | return null; 40 | } 41 | } 42 | 43 | // Main class to demonstrate the Factory pattern 44 | public class FactoryPattern { 45 | 46 | public static void main(String[] args) { 47 | // Create a ShapeFactory object 48 | ShapeFactory shapeFactory = new ShapeFactory(); 49 | 50 | // Get an object of Circle and call its draw method 51 | Shape shape1 = shapeFactory.getShape("CIRCLE"); 52 | if (shape1 != null) { 53 | shape1.draw(); 54 | } else { 55 | System.out.println("Shape not found."); 56 | } 57 | 58 | // Get an object of Square and call its draw method 59 | Shape shape2 = shapeFactory.getShape("SQUARE"); 60 | if (shape2 != null) { 61 | shape2.draw(); 62 | } else { 63 | System.out.println("Shape not found."); 64 | } 65 | 66 | // Attempt to get an object of an unknown shape type 67 | Shape shape3 = shapeFactory.getShape("TRIANGLE"); 68 | if (shape3 != null) { 69 | shape3.draw(); 70 | } else { 71 | System.out.println("Shape not found."); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /lesson3/DesignPatterns/ObserverPattern.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | // Observer interface with an update method 5 | interface Observer { 6 | void update(String message); 7 | } 8 | 9 | // Subject class that maintains a list of observers 10 | class Subject { 11 | private List observers = new ArrayList<>(); 12 | private String message; 13 | 14 | // Method to add an observer 15 | public void addObserver(Observer observer) { 16 | observers.add(observer); 17 | } 18 | 19 | // Method to remove an observer 20 | public void removeObserver(Observer observer) { 21 | observers.remove(observer); 22 | } 23 | 24 | // Method to notify all observers of a change 25 | public void notifyObservers() { 26 | for (Observer observer : observers) { 27 | observer.update(message); 28 | } 29 | } 30 | 31 | // Method to set a new message and notify observers 32 | public void setMessage(String message) { 33 | this.message = message; 34 | notifyObservers(); 35 | } 36 | } 37 | 38 | // Concrete implementation of Observer 39 | class ConcreteObserver implements Observer { 40 | private String name; 41 | 42 | public ConcreteObserver(String name) { 43 | this.name = name; 44 | } 45 | 46 | @Override 47 | public void update(String message) { 48 | System.out.println(name + " received message: " + message); 49 | } 50 | } 51 | 52 | // Main class to demonstrate the Observer pattern 53 | public class ObserverPattern { 54 | public static void main(String[] args) { 55 | // Create a Subject object 56 | Subject subject = new Subject(); 57 | 58 | // Create Observer objects 59 | Observer observer1 = new ConcreteObserver("Observer 1"); 60 | Observer observer2 = new ConcreteObserver("Observer 2"); 61 | 62 | // Add observers to the subject 63 | subject.addObserver(observer1); 64 | subject.addObserver(observer2); 65 | 66 | // Set a new message and notify observers 67 | subject.setMessage("Hello, Observers!"); 68 | 69 | // Remove an observer and set a new message 70 | subject.removeObserver(observer1); 71 | subject.setMessage("Observer 1 has been removed."); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /lesson3/DesignPatterns/SingletonPattern.java: -------------------------------------------------------------------------------- 1 | 2 | public class SingletonPattern { 3 | 4 | // Static variable to hold the single instance of the class 5 | private static SingletonPattern instance; 6 | 7 | // Private constructor to prevent instantiation from other classes 8 | private SingletonPattern() { 9 | } 10 | 11 | // Public method to provide access to the single instance 12 | public static SingletonPattern getInstance() { 13 | if (instance == null) { 14 | // Create the instance if it does not exist 15 | instance = new SingletonPattern(); 16 | } 17 | // Return the single instance 18 | return instance; 19 | } 20 | 21 | // Method to display a message 22 | public void showMessage() { 23 | System.out.println("Hello from Singleton!"); 24 | } 25 | 26 | public static void main(String[] args) { 27 | // Get the single instance of SingletonPattern 28 | SingletonPattern singleton = SingletonPattern.getInstance(); 29 | // Call the showMessage method 30 | singleton.showMessage(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /lesson3/FunctionalProgramming/LambdaExpressions.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.function.BiFunction; 3 | import java.util.function.Consumer; 4 | import java.util.function.Predicate; 5 | 6 | public class LambdaExpressions { 7 | 8 | public static void main(String[] args) { 9 | // Lambda expressions in Java provide a clear and concise way to represent 10 | // one method interface using an expression. They are used primarily to define 11 | // the inline implementation of a functional interface. 12 | 13 | // Create a lambda expression to add two integers 14 | BiFunction add = (a, b) -> a + b; 15 | 16 | // Use the lambda expression to add 5 and 3, and print the result 17 | System.out.println("Sum: " + add.apply(5, 3)); 18 | 19 | // Create a lambda expression to check if a number is even 20 | Predicate isEven = x -> x % 2 == 0; 21 | 22 | // Use the lambda expression to check if 4 is even, and print the result 23 | System.out.println("Is 4 even? " + isEven.test(4)); 24 | 25 | // Create a lambda expression to print a message 26 | Consumer printMessage = message -> System.out.println("Message: " + message); 27 | 28 | // Use the lambda expression to print a message 29 | printMessage.accept("Hello, world!"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /lesson3/FunctionalProgramming/OptionalClass.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Optional; 3 | 4 | public class OptionalClass { 5 | 6 | public static void main(String[] args) { 7 | // The Optional class in Java is used to represent a value that may or may not be present. 8 | // It helps to avoid null pointer exceptions. 9 | 10 | // Create an Optional object that may or may not contain a value 11 | Optional optional = Optional.ofNullable(null); 12 | 13 | // Check if a value is present 14 | if (optional.isPresent()) { 15 | // Get and print the value if present 16 | System.out.println("Value: " + optional.get()); 17 | } else { 18 | // Print a message if the value is not present 19 | System.out.println("Value is not present"); 20 | } 21 | 22 | // Use ifPresent to execute a lambda expression if a value is present 23 | optional.ifPresent(value -> System.out.println("Value: " + value)); 24 | 25 | // Create an Optional object with a non-null value 26 | Optional nonEmptyOptional = Optional.of("Hello"); 27 | 28 | // Get the value using orElse 29 | String value = nonEmptyOptional.orElse("Default Value"); 30 | System.out.println("Value: " + value); 31 | 32 | // Get the value using orElseGet 33 | value = nonEmptyOptional.orElseGet(() -> "Default Value"); 34 | System.out.println("Value: " + value); 35 | 36 | // Throw an exception if the value is not present 37 | try { 38 | value = optional.orElseThrow(() -> new IllegalStateException("Value is not present")); 39 | } catch (IllegalStateException e) { 40 | System.out.println(e.getMessage()); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /lesson3/FunctionalProgramming/StreamsAPI.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | public class StreamsAPI { 7 | 8 | public static void main(String[] args) { 9 | // The Streams API in Java provides a functional approach to processing collections of objects. 10 | // It allows operations such as filtering, mapping, and reducing. 11 | 12 | // Create a list of integers 13 | List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 14 | 15 | // Use the stream API to filter numbers greater than 5 16 | List filteredNumbers = numbers.stream() 17 | .filter(x -> x > 5) // Filter numbers greater than 5 18 | .collect(Collectors.toList()); // Collect the result into a list 19 | 20 | // Print the filtered numbers 21 | System.out.println("Filtered Numbers: " + filteredNumbers); 22 | 23 | // Use the stream API to map numbers to their squares 24 | List squaredNumbers = numbers.stream() 25 | .map(x -> x * x) // Map each number to its square 26 | .collect(Collectors.toList()); // Collect the result into a list 27 | 28 | // Print the squared numbers 29 | System.out.println("Squared Numbers: " + squaredNumbers); 30 | 31 | // Use the stream API to find the sum of all numbers 32 | int sum = numbers.stream() 33 | .reduce(0, (a, b) -> a + b); // Reduce the stream to the sum of its elements 34 | 35 | // Print the sum 36 | System.out.println("Sum of Numbers: " + sum); 37 | 38 | // Use the stream API to find the maximum number 39 | int max = numbers.stream() 40 | .max(Integer::compare).orElseThrow(); // Find the maximum number 41 | 42 | // Print the maximum number 43 | System.out.println("Maximum Number: " + max); 44 | 45 | // Use the stream API to find the minimum number 46 | int min = numbers.stream() 47 | .min(Integer::compare).orElseThrow(); // Find the minimum number 48 | 49 | // Print the minimum number 50 | System.out.println("Minimum Number: " + min); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /lesson3/JavaCollectionsFramework/Lists.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.LinkedList; 4 | import java.util.HashMap; 5 | import java.util.TreeMap; 6 | 7 | public class Lists { 8 | 9 | public static void main(String[] args) { 10 | // Lists are collections that allow duplicate elements and maintain the order of insertion. 11 | 12 | // ArrayList is an implementation of the List interface that uses a dynamic array for storage. 13 | // It allows random access to elements. 14 | ArrayList arrayList = new ArrayList<>(); 15 | arrayList.add("Apple"); 16 | arrayList.add("Banana"); 17 | arrayList.add("Cherry"); 18 | 19 | // Print the ArrayList 20 | System.out.println("ArrayList: " + arrayList); 21 | 22 | // LinkedList is an implementation of the List interface that uses a doubly linked list for storage. 23 | // It allows efficient insertion and removal of elements. 24 | LinkedList linkedList = new LinkedList<>(); 25 | linkedList.add("Dog"); 26 | linkedList.add("Cat"); 27 | linkedList.add("Cow"); 28 | 29 | // Print the LinkedList 30 | System.out.println("LinkedList: " + linkedList); 31 | 32 | // Create a HashMap 33 | HashMap hashMap = new HashMap<>(); 34 | hashMap.put(1, "One"); 35 | hashMap.put(2, "Two"); 36 | hashMap.put(3, "Three"); 37 | 38 | // Print the HashMap 39 | System.out.println("HashMap: " + hashMap); 40 | 41 | // Create a TreeMap 42 | TreeMap treeMap = new TreeMap<>(); 43 | treeMap.put(1, "Uno"); 44 | treeMap.put(2, "Dos"); 45 | treeMap.put(3, "Tres"); 46 | 47 | // Print the TreeMap 48 | System.out.println("TreeMap: " + treeMap); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /lesson3/JavaCollectionsFramework/Maps.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashMap; 3 | import java.util.TreeMap; 4 | import java.util.PriorityQueue; 5 | import java.util.ArrayDeque; 6 | 7 | public class Maps { 8 | 9 | public static void main(String[] args) { 10 | // Maps are collections that store key-value pairs. 11 | 12 | // HashMap is an implementation of the Map interface that uses a hash table for storage. 13 | // It does not guarantee any specific order of elements. 14 | HashMap hashMap = new HashMap<>(); 15 | hashMap.put(1, "One"); 16 | hashMap.put(2, "Two"); 17 | hashMap.put(3, "Three"); 18 | 19 | // Print the HashMap 20 | System.out.println("HashMap: " + hashMap); 21 | 22 | // Tree Map is an implementation of the Map interface that uses a tree for storage. 23 | // It stores elements in a sorted order based on the keys. 24 | TreeMap treeMap = new TreeMap<>(); 25 | treeMap.put(1, "Uno"); 26 | treeMap.put(2, "Dos"); 27 | treeMap.put(3, "Tres"); 28 | 29 | // Print the TreeMap 30 | System.out.println("TreeMap: " + treeMap); 31 | 32 | // Create a PriorityQueue 33 | PriorityQueue priorityQueue = new PriorityQueue<>(); 34 | priorityQueue.add(10); 35 | 36 | // Print the PriorityQueue 37 | System.out.println("PriorityQueue: " + priorityQueue); 38 | 39 | // Create an ArrayDeque 40 | ArrayDeque deque = new ArrayDeque<>(); 41 | deque.add("First"); 42 | 43 | // Print the ArrayDeque 44 | System.out.println("Deque: " + deque); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /lesson3/JavaCollectionsFramework/Queues.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayDeque; 3 | import java.util.PriorityQueue; 4 | import java.util.HashSet; 5 | import java.util.TreeSet; 6 | 7 | public class Queues { 8 | 9 | public static void main(String[] args) { 10 | // Queues are collections that hold elements prior to processing. 11 | // They typically order elements in a FIFO (first-in-first-out) manner. 12 | 13 | // PriorityQueue is an implementation of the Queue interface that orders elements 14 | // based on their natural ordering or a specified comparator. 15 | PriorityQueue priorityQueue = new PriorityQueue<>(); 16 | priorityQueue.add(10); 17 | priorityQueue.add(20); 18 | priorityQueue.add(15); 19 | 20 | // Print the PriorityQueue 21 | System.out.println("PriorityQueue: " + priorityQueue); 22 | 23 | // ArrayDeque is an implementation of the Deque interface that allows elements 24 | // to be added or removed from both ends. 25 | ArrayDeque deque = new ArrayDeque<>(); 26 | deque.add("First"); 27 | deque.add("Second"); 28 | deque.add("Third"); 29 | 30 | // Print the ArrayDeque 31 | System.out.println("Deque: " + deque); 32 | 33 | // Create a HashSet 34 | HashSet hashSet = new HashSet<>(); 35 | hashSet.add("Apple"); 36 | hashSet.add("Banana"); 37 | hashSet.add("Cherry"); 38 | 39 | // Print the HashSet 40 | System.out.println("HashSet: " + hashSet); 41 | 42 | // Create a TreeSet 43 | TreeSet treeSet = new TreeSet<>(); 44 | treeSet.add("Dog"); 45 | treeSet.add("Cat"); 46 | treeSet.add("Elephant"); 47 | 48 | // Print the TreeSet 49 | System.out.println("TreeSet: " + treeSet); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /lesson3/JavaCollectionsFramework/Sets.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashSet; 3 | import java.util.TreeSet; 4 | 5 | public class Sets { 6 | 7 | public static void main(String[] args) { 8 | // Sets are collections that do not allow duplicate elements. 9 | 10 | // HashSet is an implementation of the Set interface that uses a hash table for storage. 11 | // It does not guarantee any specific order of elements. 12 | HashSet hashSet = new HashSet<>(); 13 | hashSet.add("Apple"); 14 | hashSet.add("Banana"); 15 | hashSet.add("Cherry"); 16 | 17 | // Print the HashSet 18 | System.out.println("HashSet: " + hashSet); 19 | 20 | // TreeSet is an implementation of the Set interface that uses a tree for storage. 21 | // It stores elements in a sorted order. 22 | TreeSet treeSet = new TreeSet<>(); 23 | treeSet.add("Dog"); 24 | treeSet.add("Cat"); 25 | treeSet.add("Cow"); 26 | 27 | // Print the TreeSet 28 | System.out.println("TreeSet: " + treeSet); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /lesson3/MemoryManagement/GarbageCollection.java: -------------------------------------------------------------------------------- 1 | 2 | public class GarbageCollection { 3 | 4 | public static void main(String[] args) { 5 | // Garbage collection is the process of automatically reclaiming memory 6 | // by destroying objects that are no longer reachable. 7 | 8 | // Create an object of GarbageCollection 9 | GarbageCollection obj = new GarbageCollection(); 10 | 11 | // Set the object reference to null, making it eligible for garbage collection 12 | obj = null; 13 | 14 | // Request garbage collection 15 | System.gc(); 16 | System.out.println("Garbage collection requested."); 17 | } 18 | 19 | @Override 20 | protected void finalize() throws Throwable { 21 | // The finalize method is called by the garbage collector before an object is destroyed. 22 | // It can be overridden to perform cleanup operations. 23 | System.out.println("Garbage collector called."); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /lesson3/MemoryManagement/JVMInternals.java: -------------------------------------------------------------------------------- 1 | 2 | public class JVMInternals { 3 | 4 | public static void main(String[] args) { 5 | // The JVM (Java Virtual Machine) manages memory through several areas: 6 | // - Heap: where all objects are allocated. 7 | // - Stack: where method calls and local variables are stored. 8 | // - Method Area: where class structures and static variables are stored. 9 | // - Native Method Stack: where native method calls are stored. 10 | 11 | // Print the maximum amount of memory that the JVM will attempt to use 12 | System.out.println("Heap Size: " + Runtime.getRuntime().maxMemory()); 13 | 14 | // Print the number of available processors to the JVM 15 | System.out.println("Available Processors: " + Runtime.getRuntime().availableProcessors()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /lesson3/MemoryManagement/MemoryLeaks.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | public class MemoryLeaks { 6 | 7 | public static void main(String[] args) { 8 | // Memory leaks occur when objects are no longer needed but are not released, 9 | // causing the application to consume more memory over time. 10 | 11 | // Example of a memory leak: 12 | // Create a list to hold strings 13 | List list = new ArrayList<>(); 14 | 15 | // Infinite loop to continuously add strings to the list 16 | while (true) { 17 | list.add("Memory Leak"); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /lesson4/BuildingGUI/BuildingGUIWithSwing.java: -------------------------------------------------------------------------------- 1 | 2 | import javax.swing.*; 3 | 4 | public class BuildingGUIWithSwing { 5 | 6 | public static void main(String[] args) { 7 | // Creating a JFrame window 8 | JFrame frame = new JFrame("My GUI Application"); 9 | JButton button = new JButton("Click Me"); 10 | 11 | // Adding an ActionListener to the button using a lambda expression 12 | button.addActionListener(e -> JOptionPane.showMessageDialog(frame, "Button Clicked!")); 13 | 14 | // Setting up the JFrame window 15 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 | frame.setSize(300, 200); 17 | frame.setLayout(new java.awt.FlowLayout()); 18 | frame.add(button); 19 | frame.setVisible(true); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /lesson4/BuildingGUI/EventHandlingInGUI.java: -------------------------------------------------------------------------------- 1 | 2 | import javax.swing.*; 3 | import java.awt.event.ActionEvent; 4 | import java.awt.event.ActionListener; 5 | 6 | public class EventHandlingInGUI { 7 | 8 | public static void main(String[] args) { 9 | // Creating a JFrame window 10 | JFrame frame = new JFrame("Event Handling Example"); 11 | JButton button = new JButton("Click Me"); 12 | 13 | // Adding an ActionListener to the button 14 | button.addActionListener(new ActionListener() { 15 | @Override 16 | public void actionPerformed(ActionEvent e) { 17 | // Displaying a message dialog when the button is clicked 18 | JOptionPane.showMessageDialog(frame, "Button Clicked!"); 19 | } 20 | }); 21 | 22 | // Setting up the JFrame window 23 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 24 | frame.setSize(300, 200); 25 | frame.setLayout(new java.awt.FlowLayout()); 26 | frame.add(button); 27 | frame.setVisible(true); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /lesson4/SpringBoot/BuildingRestAPIs.java: -------------------------------------------------------------------------------- 1 | 2 | import org.springframework.boot.SpringApplication; 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @SpringBootApplication 9 | public class BuildingRestAPIs { 10 | 11 | public static void main(String[] args) { 12 | // SpringApplication.run starts the Spring Boot application. 13 | SpringApplication.run(BuildingRestAPIs.class, args); 14 | } 15 | } 16 | 17 | @RestController 18 | @RequestMapping("/api") 19 | class ApiController { 20 | 21 | // Endpoint to handle GET requests. 22 | @GetMapping("/hello") 23 | public String sayHello() { 24 | return "Hello, World!"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /lesson4/SpringBoot/DependencyInjection.java: -------------------------------------------------------------------------------- 1 | 2 | import org.springframework.beans.factory.annotation.Autowired; 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.stereotype.Component; 6 | import org.springframework.stereotype.Service; 7 | 8 | @Component 9 | class ServiceComponent { 10 | 11 | // This method simulates a service that performs some action. 12 | public void serve() { 13 | System.out.println("Service is serving."); 14 | } 15 | } 16 | 17 | @Service 18 | class ClientService { 19 | 20 | private final ServiceComponent serviceComponent; 21 | 22 | // Constructor injection of the ServiceComponent. 23 | @Autowired 24 | public ClientService(ServiceComponent serviceComponent) { 25 | this.serviceComponent = serviceComponent; 26 | } 27 | 28 | // This method calls the serve method of the ServiceComponent. 29 | public void doSomething() { 30 | serviceComponent.serve(); 31 | } 32 | } 33 | 34 | @SpringBootApplication 35 | public class DependencyInjection { 36 | 37 | public static void main(String[] args) { 38 | // SpringApplication.run starts the Spring Boot application. 39 | SpringApplication.run(DependencyInjection.class, args); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /lesson4/SpringBoot/HandlingApiRequests.java: -------------------------------------------------------------------------------- 1 | 2 | import org.springframework.boot.SpringApplication; 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.web.bind.annotation.*; 5 | 6 | @SpringBootApplication 7 | public class HandlingApiRequests { 8 | 9 | public static void main(String[] args) { 10 | // SpringApplication.run starts the Spring Boot application. 11 | SpringApplication.run(HandlingApiRequests.class, args); 12 | } 13 | } 14 | 15 | @RestController 16 | @RequestMapping("/api") 17 | class ApiController { 18 | 19 | // Endpoint to handle GET requests. 20 | @GetMapping("/greet") 21 | public String greet() { 22 | return "Greetings!"; 23 | } 24 | 25 | // Endpoint to handle POST requests. 26 | @PostMapping("/echo") 27 | public String echo(@RequestBody String message) { 28 | return "Echo: " + message; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /lesson4/SpringBoot/WorkingWithSpringDataJPA.java: -------------------------------------------------------------------------------- 1 | 2 | import org.springframework.boot.SpringApplication; 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | import org.springframework.web.bind.annotation.*; 7 | 8 | import javax.persistence.Entity; 9 | import javax.persistence.GeneratedValue; 10 | import javax.persistence.GenerationType; 11 | import javax.persistence.Id; 12 | import java.util.List; 13 | 14 | @SpringBootApplication 15 | public class WorkingWithSpringDataJPA { 16 | 17 | public static void main(String[] args) { 18 | // SpringApplication.run starts the Spring Boot application. 19 | SpringApplication.run(WorkingWithSpringDataJPA.class, args); 20 | } 21 | } 22 | 23 | @Entity 24 | class User { 25 | 26 | @Id 27 | @GeneratedValue(strategy = GenerationType.IDENTITY) 28 | private Long id; 29 | private String name; 30 | 31 | // Getters and setters for the fields. 32 | public Long getId() { 33 | return id; 34 | } 35 | 36 | public void setId(Long id) { 37 | this.id = id; 38 | } 39 | 40 | public String getName() { 41 | return name; 42 | } 43 | 44 | public void setName(String name) { 45 | this.name = name; 46 | } 47 | } 48 | 49 | @Repository 50 | interface UserRepository extends JpaRepository { 51 | // JpaRepository provides CRUD operations for the User entity. 52 | } 53 | 54 | @RestController 55 | @RequestMapping("/users") 56 | class UserController { 57 | 58 | private final UserRepository userRepository; 59 | 60 | // Constructor injection of the UserRepository. 61 | public UserController(UserRepository userRepository) { 62 | this.userRepository = userRepository; 63 | } 64 | 65 | // Endpoint to get all users. 66 | @GetMapping 67 | public List getAllUsers() { 68 | return userRepository.findAll(); 69 | } 70 | 71 | // Endpoint to create a new user. 72 | @PostMapping 73 | public User createUser(@RequestBody User user) { 74 | return userRepository.save(user); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /lesson4/UnitTesting/MockingWithMockito.java: -------------------------------------------------------------------------------- 1 | 2 | import org.junit.jupiter.api.Test; 3 | import org.mockito.Mockito; 4 | import static org.junit.jupiter.api.Assertions.assertEquals; 5 | import static org.mockito.Mockito.when; 6 | 7 | class Service { 8 | 9 | // This method simulates a service that performs some action. 10 | public String serve() { 11 | return "Service is serving."; 12 | } 13 | } 14 | 15 | class Client { 16 | 17 | private final Service service; 18 | 19 | // The Client class depends on the Service class. 20 | public Client(Service service) { 21 | this.service = service; 22 | } 23 | 24 | // This method calls the serve method of the Service class. 25 | public String doSomething() { 26 | return service.serve(); 27 | } 28 | } 29 | 30 | public class MockingWithMockito { 31 | 32 | @Test 33 | public void testDoSomething() { 34 | // Mockito is a framework for creating mock objects. 35 | // Mocking is used to simulate the behavior of real objects in controlled ways. 36 | Service mockService = Mockito.mock(Service.class); 37 | 38 | // Define the behavior of the mock object. 39 | when(mockService.serve()).thenReturn("Mocked Service is serving."); 40 | 41 | // Use the mock object in the Client class. 42 | Client client = new Client(mockService); 43 | 44 | // Verify that the Client class behaves as expected when using the mock object. 45 | assertEquals("Mocked Service is serving.", client.doSomething()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /lesson4/UnitTesting/UnitTestingWithJUnit.java: -------------------------------------------------------------------------------- 1 | 2 | import org.junit.jupiter.api.Test; 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | public class UnitTestingWithJUnit { 6 | 7 | // Unit testing is a type of software testing where individual units or components of a software are tested. 8 | // JUnit is a popular framework for unit testing in Java. 9 | @Test 10 | public void testAddition() { 11 | // The assertEquals method checks if the expected value matches the actual value. 12 | assertEquals(5, add(2, 3)); 13 | } 14 | 15 | // This method adds two integers and returns the result. 16 | public int add(int a, int b) { 17 | return a + b; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /lesson5/DevOpsDeployment/CICDWithJenkins.java: -------------------------------------------------------------------------------- 1 | 2 | public class CICDWithJenkins { 3 | 4 | public static void main(String[] args) { 5 | // Jenkins is an open-source automation server that helps automate the parts of software development related to building, testing, and deploying. 6 | // It supports continuous integration (CI) and continuous delivery (CD). 7 | 8 | // Example of a Jenkins pipeline script (Jenkinsfile): 9 | /* 10 | pipeline { 11 | agent any 12 | 13 | stages { 14 | stage('Build') { 15 | steps { 16 | echo 'Building...' 17 | sh 'mvn clean package' 18 | } 19 | } 20 | stage('Test') { 21 | steps { 22 | echo 'Testing...' 23 | sh 'mvn test' 24 | } 25 | } 26 | stage('Deploy') { 27 | steps { 28 | echo 'Deploying...' 29 | sh 'scp target/my-java-application.jar user@server:/path/to/deploy' 30 | } 31 | } 32 | } 33 | } 34 | */ 35 | System.out.println("CI/CD with Jenkins"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /lesson5/DevOpsDeployment/DockerizingJavaApplications.java: -------------------------------------------------------------------------------- 1 | 2 | public class DockerizingJavaApplications { 3 | 4 | public static void main(String[] args) { 5 | // Docker is a platform for developing, shipping, and running applications inside containers. 6 | // Containers are lightweight, portable, and self-sufficient units that can run anywhere. 7 | 8 | // Example of a Dockerfile for a Java application: 9 | /* 10 | # Use an official OpenJDK runtime as a parent image 11 | FROM openjdk:11-jre-slim 12 | 13 | # Set the working directory in the container 14 | WORKDIR /app 15 | 16 | # Copy the current directory contents into the container at /app 17 | COPY . /app 18 | 19 | # Make port 8080 available to the world outside this container 20 | EXPOSE 8080 21 | 22 | # Run the application 23 | CMD ["java", "-jar", "my-java-application.jar"] 24 | */ 25 | System.out.println("Dockerizing Java Applications"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /lesson5/DevOpsDeployment/KubernetesForJavaMicroservices.java: -------------------------------------------------------------------------------- 1 | 2 | public class KubernetesForJavaMicroservices { 3 | 4 | public static void main(String[] args) { 5 | // Kubernetes is an open-source platform for automating deployment, scaling, and operations of application containers across clusters of hosts. 6 | // It provides container-centric infrastructure to manage applications. 7 | 8 | // Example of a Kubernetes deployment YAML file for a Java microservice: 9 | /* 10 | apiVersion: apps/v1 11 | kind: Deployment 12 | metadata: 13 | name: java-microservice 14 | spec: 15 | replicas: 3 16 | selector: 17 | matchLabels: 18 | app: java-microservice 19 | template: 20 | metadata: 21 | labels: 22 | app: java-microservice 23 | spec: 24 | containers: 25 | - name: java-microservice 26 | image: my-java-microservice:latest 27 | ports: 28 | - containerPort: 8080 29 | */ 30 | System.out.println("Kubernetes for Java Microservices"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /lesson5/Microservices/BuildingMicroservices.java: -------------------------------------------------------------------------------- 1 | 2 | import org.springframework.boot.SpringApplication; 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @SpringBootApplication 9 | public class BuildingMicroservices { 10 | 11 | public static void main(String[] args) { 12 | // SpringApplication.run starts the Spring Boot application. 13 | SpringApplication.run(BuildingMicroservices.class, args); 14 | } 15 | } 16 | 17 | @RestController 18 | @RequestMapping("/api") 19 | class MicroserviceController { 20 | 21 | // Endpoint to handle GET requests 22 | @GetMapping("/hello") 23 | public String sayHello() { 24 | return "Hello from Microservice!"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /lesson5/Microservices/RestfulApisAndGraphQL.java: -------------------------------------------------------------------------------- 1 | import org.springframework.boot.SpringApplication; 2 | import org.springframework.boot.autoconfigure.SpringBootApplication; 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | import graphql.schema.GraphQLSchema; 7 | import graphql.schema.StaticDataFetcher; 8 | import graphql.GraphQL; 9 | import graphql.schema.idl.RuntimeWiring; 10 | import graphql.schema.idl.SchemaGenerator; 11 | import graphql.schema.idl.SchemaParser; 12 | import graphql.schema.idl.TypeDefinitionRegistry; 13 | import org.springframework.web.bind.annotation.PostMapping; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | 16 | @SpringBootApplication 17 | public class RestfulApisAndGraphQL { 18 | 19 | public static void main(String[] args) { 20 | // SpringApplication.run starts the Spring Boot application. 21 | SpringApplication.run(RestfulApisAndGraphQL.class, args); 22 | } 23 | } 24 | 25 | @RestController 26 | @RequestMapping("/api") 27 | class ApiController { 28 | 29 | // Endpoint to handle GET requests in REST API 30 | @GetMapping("/greet") 31 | public String greet() { 32 | return "Greetings from REST API!"; 33 | } 34 | } 35 | 36 | @RestController 37 | @RequestMapping("/graphql") 38 | class GraphQLController { 39 | 40 | private final GraphQL graphQL; 41 | 42 | // Constructor to initialize GraphQL schema 43 | public GraphQLController() { 44 | String schema = "type Query{hello: String}"; 45 | TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(schema); 46 | RuntimeWiring wiring = RuntimeWiring.newRuntimeWiring() 47 | .type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("Hello from GraphQL!"))) 48 | .build(); 49 | GraphQLSchema graphQLSchema = new SchemaGenerator().makeExecutableSchema(typeRegistry, wiring); 50 | this.graphQL = GraphQL.newGraphQL(graphQLSchema).build(); 51 | } 52 | 53 | // Endpoint to handle GraphQL queries 54 | @PostMapping 55 | public Map execute(@RequestBody String query) { 56 | return graphQL.execute(query).getData(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /lesson5/Microservices/ServiceCommunication.java: -------------------------------------------------------------------------------- 1 | import org.springframework.cloud.openfeign.FeignClient; 2 | import org.springframework.web.bind.annotation.GetMapping; 3 | import org.springframework.web.bind.annotation.RequestMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.cloud.netflix.eureka.EnableEurekaClient; 8 | import org.springframework.cloud.openfeign.EnableFeignClients; 9 | 10 | @SpringBootApplication 11 | @EnableEurekaClient 12 | @EnableFeignClients // Enable Feign Clients 13 | public class ServiceCommunication { 14 | 15 | public static void main(String[] args) { 16 | // SpringApplication.run starts the Spring Boot application. 17 | SpringApplication.run(ServiceCommunication.class, args); 18 | } 19 | } 20 | 21 | // FeignClient for communication with another service 22 | @FeignClient(name = "other-service", url = "http://localhost:8081") 23 | interface OtherServiceClient { 24 | 25 | // Endpoint in the other service 26 | @GetMapping("/api/hello") 27 | String getHello(); 28 | } 29 | 30 | @RestController 31 | @RequestMapping("/api") 32 | class CommunicationController { 33 | 34 | private final OtherServiceClient otherServiceClient; 35 | 36 | // Constructor injection of OtherServiceClient 37 | public CommunicationController(OtherServiceClient otherServiceClient) { 38 | this.otherServiceClient = otherServiceClient; 39 | } 40 | 41 | // Endpoint to communicate with the other service 42 | @GetMapping("/communicate") 43 | public String communicate() { 44 | return otherServiceClient.getHello(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /lesson5/WorkingWithAPIs/CallingExternalAPIs.java: -------------------------------------------------------------------------------- 1 | import org.springframework.boot.SpringApplication; 2 | import org.springframework.boot.autoconfigure.SpringBootApplication; 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | import org.springframework.web.client.RestTemplate; 8 | import org.springframework.web.reactive.function.client.WebClient; 9 | 10 | @SpringBootApplication 11 | public class CallingExternalAPIs { 12 | 13 | public static void main(String[] args) { 14 | // SpringApplication.run starts the Spring Boot application. 15 | SpringApplication.run(CallingExternalAPIs.class, args); 16 | } 17 | 18 | // Bean for RestTemplate 19 | @Bean 20 | public RestTemplate restTemplate() { 21 | return new RestTemplate(); 22 | } 23 | 24 | // Bean for WebClient.Builder 25 | @Bean 26 | public WebClient.Builder webClientBuilder() { 27 | return WebClient.builder(); 28 | } 29 | } 30 | 31 | @RestController 32 | @RequestMapping("/api") 33 | class ApiController { 34 | 35 | private final RestTemplate restTemplate; 36 | private final WebClient webClient; 37 | 38 | // Constructor injection of RestTemplate and WebClient.Builder 39 | public ApiController(RestTemplate restTemplate, WebClient.Builder webClientBuilder) { 40 | this.restTemplate = restTemplate; 41 | this.webClient = webClientBuilder.baseUrl("https://jsonplaceholder.typicode.com").build(); 42 | } 43 | 44 | // Endpoint to call external API using RestTemplate 45 | @GetMapping("/resttemplate") 46 | public String callApiWithRestTemplate() { 47 | return restTemplate.getForObject("https://jsonplaceholder.typicode.com/posts/1", String.class); 48 | } 49 | 50 | // Endpoint to call external API using WebClient 51 | @GetMapping("/webclient") 52 | public String callApiWithWebClient() { 53 | return webClient.get().uri("/posts/1").retrieve().bodyToMono(String.class).block(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /lesson5/WorkingWithAPIs/JsonParsingWithJackson.java: -------------------------------------------------------------------------------- 1 | 2 | import com.fasterxml.jackson.databind.ObjectMapper; 3 | 4 | public class JsonParsingWithJackson { 5 | 6 | public static void main(String[] args) { 7 | // JSON string to be parsed 8 | String jsonString = "{\"name\":\"John\", \"age\":30}"; 9 | 10 | // ObjectMapper is the main class for parsing JSON in Jackson 11 | ObjectMapper objectMapper = new ObjectMapper(); 12 | try { 13 | // Parsing JSON string to Person object 14 | Person person = objectMapper.readValue(jsonString, Person.class); 15 | // Printing parsed data 16 | System.out.println("Name: " + person.getName()); 17 | System.out.println("Age: " + person.getAge()); 18 | } catch (Exception e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | } 23 | 24 | class Person { 25 | 26 | private String name; 27 | private int age; 28 | 29 | // Getters and setters for the fields 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public void setName(String name) { 35 | this.name = name; 36 | } 37 | 38 | public int getAge() { 39 | return age; 40 | } 41 | 42 | public void setAge(int age) { 43 | this.age = age; 44 | } 45 | } 46 | --------------------------------------------------------------------------------