├── Java_Concepts ├── Array │ ├── Array.java │ ├── Array_2D.java │ └── Array_ArrayOfObjects.java ├── Basic │ ├── AccessModifier.java │ ├── AnonymousObject.java │ ├── ConditionalStatements.java │ ├── Constructor.java │ ├── ControlFlow.java │ ├── DataTypes.java │ ├── EnumConcept.java │ ├── ExceptionHandlingConcept.java │ ├── GenericClass.java │ ├── MethodOverloading.java │ ├── NestedClass.java │ ├── ObjectClassConcept.java │ ├── ReadingUserInput.java │ ├── RegexConcept.java │ ├── Stack_vs_Heap.java │ ├── StaticConcepts.java │ ├── SwitchCase.java │ ├── TernaryOperator.java │ ├── Up_down_Casting.java │ ├── _HelloWorld.java │ └── _Intro.java ├── Collection │ ├── CollectionConcept.java │ ├── Collection_List_Interface.java │ ├── Collection_Map_Interface.java │ ├── Collection_Queue_Interface.java │ ├── Collection_Set_Interface.java │ └── Comparable_vs_Comparator.java ├── DSA │ └── Algorithm_BinarySearch.java ├── Interface │ ├── InterfaceConcept.java │ └── InterfaceTypes.java ├── OOPS │ ├── DateClass.java │ ├── FinalKeyword.java │ ├── OopsConcepts.java │ ├── Oops_Abstraction.java │ ├── Oops_Encapsulation.java │ ├── Oops_Inheritance.java │ ├── Oops_Inheritance_Hierarchical.java │ ├── Oops_Inheritance_Hybrid.java │ ├── Oops_Inheritance_MultiLevel.java │ ├── Oops_Inheritance_Single.java │ ├── Oops_Polymorphism.java │ ├── Overloading_vs_OverRiding.java │ ├── StreamConcept.java │ ├── ThisKeyword.java │ └── This_vs_Super.java ├── PackageConcept │ ├── AccessModifier_PackageConcept │ │ ├── AccessModifierMain.java │ │ ├── AccessModifier_Package │ │ │ ├── ClassA.java │ │ │ └── ClassB.java │ │ └── AnotherAccessModifier_Package │ │ │ └── ClassC.java │ └── Basic_PackageConcepts │ │ ├── AdvOperation │ │ ├── AdvLevel1_Operation.java │ │ └── AdvLevel2_Operation.java │ │ ├── BasicOperation │ │ ├── Level1_Operation.java │ │ └── Level2_Operation.java │ │ └── PackageConcept_SimpleCalculator.java ├── String │ └── StringConcepts.java └── Thread │ └── ThreadConcept.java ├── Java_Tasks ├── Calculator_System │ ├── AdvancedCalculator.java │ ├── BasicCalculator.java │ ├── Calculator.java │ └── CalculatorMain.java └── Student_Management │ ├── Add_Student.java │ ├── Remove_Student.java │ ├── Search_Student.java │ ├── Sort_Student.java │ ├── StudentMain.java │ └── View_Student.java ├── LICENSE └── README.md /Java_Concepts/Array/Array.java: -------------------------------------------------------------------------------- 1 | // Array: 2 | /* 3 | Definition: 4 | An array is a fixed-size collection of elements of the same data type arranged in a sequential order. 5 | Each element in an array is accessed by its index. 6 | 7 | Characteristics: 8 | Arrays have a fixed size that is determined at the time of array creation and cannot be changed dynamically. 9 | Array elements are stored in contiguous memory locations, allowing for efficient access using index-based retrieval. 10 | Array indices start from 0 and go up to length - 1, where length is the size of the array. 11 | 12 | Declaration Syntax: 13 | dataType[] arrayName; // Preferred syntax 14 | // OR 15 | dataType arrayName[]; // Alternate syntax (less common) 16 | 17 | Ways to Declare and Use Arrays: 18 | 19 | 1) Declaration and Initialization in One Step: 20 | int[] numbers = {1, 2, 3, 4, 5}; // Initialize array with values 21 | 22 | 2) Declaration and Initialization in Two Steps: 23 | int[] numbers; 24 | numbers = new int[]{1, 2, 3, 4, 5}; // Initialize array after declaration 25 | 26 | 3) Empty Array Declaration: 27 | int[] numbers = new int[5]; // Create an array of size 5 with default values (0 for int) 28 | 29 | 4) Accessing Array Elements: 30 | int[] numbers = {1, 2, 3, 4, 5}; 31 | int firstElement = numbers[0]; // Accessing the first element 32 | int lastElement = numbers[numbers.length - 1]; // Accessing the last element 33 | 34 | 5) Looping Through Array Elements: 35 | int[] numbers = {1, 2, 3, 4, 5}; 36 | for (int i = 0; i < numbers.length; i++) { 37 | System.out.println(numbers[i]); // Print each element 38 | } 39 | 40 | 6) Enhanced For Loop (For-each Loop): 41 | int[] numbers = {1, 2, 3, 4, 5}; 42 | for (int num : numbers) { 43 | System.out.println(num); // Print each element 44 | } 45 | 46 | */ 47 | import java.util.Arrays; 48 | 49 | public class Array { 50 | public static void main(String[] a){ 51 | 52 | // Declaration and Initialization in One Step 53 | int[] numArray1 = {1,2,3,4,5}; // Initialize array with values 54 | for (int i = 0; i < numArray1.length; i++) { 55 | System.out.println(i + " : " + numArray1[i]); // Print each element 56 | } 57 | 58 | System.out.println("----------------"); 59 | 60 | // Declaration and Initialization in Two Steps: 61 | int[] numArray2; 62 | numArray2 = new int[] {8,6,10,7,9}; // Initialize array after declaration 63 | 64 | Arrays.sort(numArray2); //Sort the array with inBuild Arrays sort method 65 | 66 | int index = 0; 67 | for(int i : numArray2){ 68 | System.out.println(index + " : " + i); 69 | index++; 70 | } 71 | 72 | System.out.println("----------------"); 73 | 74 | // Array Copy(InBuild Method()) 75 | 76 | int[] copyFrom = new int[] {11, 12, 13, 14, 15}; 77 | int[] copyInto = new int[copyFrom.length]; 78 | System.arraycopy (copyFrom, 0, copyInto, 0, copyFrom. length); 79 | for (int i = 0; i < copyInto.length; i++) { 80 | System.out.println (copyInto[i]); 81 | } 82 | 83 | System.out.println("----------------"); 84 | 85 | // Min Max Array 86 | MinMaxArray run = new MinMaxArray(); 87 | int[] result = run.findMinMax(numArray1); 88 | // Print the array without using loops 89 | System.out.println(Arrays.toString(result)); 90 | 91 | } 92 | } 93 | 94 | class MinMaxArray { 95 | public int[] findMinMax(int[] arr) //return type of array int[] 96 | { 97 | // Initialize min and max to the first element in the array 98 | int min = arr[0]; 99 | int max = arr[0]; 100 | 101 | for (int i = 1; i < arr.length; i++) { 102 | // If the current element is smaller than min then assign min to it 103 | if (arr[i] < min) { 104 | min = arr[i]; 105 | } 106 | // If the current element is larger than max then assign max to it 107 | if (arr[i] > max) { 108 | max = arr[i]; 109 | } 110 | } 111 | // return a new integer array that contains min and max 112 | return new int[] {min, max}; 113 | } 114 | } 115 | 116 | /* 117 | numArray1: 118 | In numArray1, the array is declared and initialized in a single step. This is called an "array initializer" syntax. 119 | Here, the compiler automatically determines the size of the array based on the number of elements provided within the curly braces {}. 120 | It's a concise way to create and initialize arrays. 121 | 122 | numArray2: 123 | In numArray2, the array is declared first using int[] numbers;, but it is not initialized yet. 124 | Then, in the next line, the array is initialized using the new keyword. Here, the new keyword is used to explicitly allocate memory for the array on the heap. 125 | It's necessary when the size of the array is not known at compile-time or when you want to separate the declaration and initialization steps. 126 | The array size is explicitly specified with new int[]{...}, allowing more flexibility in determining the size dynamically or based on other factors at runtime. 127 | 128 | //Drawbacks of array: 129 | -Fixed Size: Arrays have a fixed size, which cannot be changed dynamically after initialization. 130 | -Homogeneous Data: Arrays can only store elements of the same data type. 131 | -Inefficient Insertion/Deletion: Insertion or deletion of elements in the middle of an array can be inefficient, requiring shifting of elements. 132 | -No Built-in Methods: Arrays lack built-in methods for common operations like sorting, searching, or resizing. 133 | 134 | // System.arrayCopy() 135 | The System.arrayCopy() method in Java is used to copy elements from one array to another. 136 | It provides a fast and efficient way to copy array contents, whether it's a complete array or a portion of it. 137 | 138 | public static void arrayCopy(Object src, int srcPos, Object dest, int destPos, int length) 139 | 140 | Parameters: 141 | src: The source array from which elements are to be copied. 142 | srcPos: The starting position in the source array from where elements will be copied. 143 | dest: The destination array to which elements will be copied. 144 | destPos: The starting position in the destination array where elements will be copied. 145 | length: The number of elements to be copied. 146 | 147 | Notes: 148 | Both src and dest must be arrays of the same type. 149 | The starting positions srcPos and destPos are zero-based indices. 150 | The length parameter determines the number of elements to copy. 151 | The src array is not modified by this operation. 152 | 153 | //Findings: 154 | -- 155 | int[] numArray2 = new int[5]; // Allocate memory for an array of size 5 156 | numArray2 = {6, 7, 8, 9, 10}; // Initialize the array with values {6, 7, 8, 9, 10} 157 | this approach is not valid when you have already declared and instantiated the array using new int[5]. 158 | In Java, you can't use the array initializer syntax directly after assigning a new array reference to the same variable. 159 | Only Use Direct Initialization or Indirect Initialization. 160 | -- 161 | */ 162 | -------------------------------------------------------------------------------- /Java_Concepts/Array/Array_2D.java: -------------------------------------------------------------------------------- 1 | // multi-dimensional array 2 | /* 3 | A multi-dimensional array in Java is an array of arrays, or, more generally, an array of arrays of arrays, and so on. 4 | It allows you to represent data in multiple dimensions, such as rows and columns in a table or a matrix. 5 | 6 | Declaration Syntax: 7 | dataType[][] arrayName; // Two-dimensional array 8 | dataType[][][] arrayName; // Three-dimensional array 9 | // and so on... 10 | 11 | Initialization Syntax: 12 | dataType[][] arrayName = { 13 | {value1, value2, ...}, // First row 14 | {value3, value4, ...}, // Second row 15 | // Additional rows... 16 | }; 17 | 18 | To access elements of a multi-dimensional array using multiple indices. 19 | For a two-dimensional array, you specify the row index followed by the column index. 20 | */ 21 | 22 | public class Array_2D { 23 | public static void main(String[] a){ 24 | int[][] TwoDimArray = { 25 | {1,2,3}, 26 | {4,5,6}, 27 | {7,8,9} 28 | }; 29 | 30 | for (int i = 0; i < TwoDimArray.length; i++) { // Iterate over each row index 31 | for (int j = 0; j < TwoDimArray[i].length; j++) { // Iterate over each column index in the current row 32 | System.out.print(TwoDimArray[i][j] + " "); // Print the element at row i and column j 33 | } 34 | System.out.println(); // Move to the next line after printing all elements of the current row 35 | } 36 | 37 | System.out.println("----------"); 38 | 39 | int[][] TwoDimArray2 = new int[3][3]; 40 | 41 | // Assigning Random values 42 | for (int i = 0; i < TwoDimArray2.length; i++) { // Iterate over each row index 43 | for (int j = 0; j < TwoDimArray2[i].length; j++) { // Iterate over each column index in the current row 44 | TwoDimArray2[i][j] = (int)(Math.random() * 10); // It returns a random double value greater than or equal to 0.0 and less than 1.0. multiply the result of Math.random() by 10 to range (0-10), type casted to convert to an integer. 45 | } 46 | } 47 | 48 | // Enhanced for loop 49 | for (int arr[] : TwoDimArray2) { // Iterate over each row in the two-dimensional array 50 | for (int ele : arr) { // Iterate over each element in the current row 51 | System.out.print(ele + " "); // Print the element followed by a space 52 | } 53 | System.out.println(); // Move to the next line after printing all elements of the current row 54 | } 55 | 56 | System.out.println("----------"); 57 | 58 | int[][] jaggedArray = new int[3][]; // Create a jagged array with 3 rows 59 | jaggedArray[0] = new int[4]; // First row has 4 elements 60 | jaggedArray[1] = new int[2]; // Second row has 2 elements 61 | jaggedArray[2] = new int[5]; // Third row has 5 element 62 | 63 | // Assigning Random values in jagged array 64 | for (int i = 0; i < jaggedArray.length; i++) { 65 | for (int j = 0; j < jaggedArray[i].length; j++) { 66 | jaggedArray[i][j] = (int)(Math.random() * 10); 67 | } 68 | } 69 | 70 | for (int arr[] : jaggedArray) { 71 | for (int ele : arr) { 72 | System.out.print(ele + " "); 73 | } 74 | System.out.println(); 75 | } 76 | 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Java_Concepts/Array/Array_ArrayOfObjects.java: -------------------------------------------------------------------------------- 1 | // Array Of Objects 2 | /* 3 | array of objects in Java is an array where each element is an object of a specific class. 4 | It allows you to store multiple objects of the same class in a contiguous memory block. 5 | */ 6 | 7 | // Define a Array_Person class 8 | class Array_Person { 9 | private String name; 10 | private int age; 11 | 12 | // Constructor 13 | public Array_Person(String name, int age) { 14 | this.name = name; 15 | this.age = age; 16 | } 17 | 18 | // Getter methods 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public int getAge() { 24 | return age; 25 | } 26 | } 27 | 28 | // Main class 29 | public class Array_ArrayOfObjects { 30 | public static void main(String[] args) { 31 | // Create an array of Array_Person objects 32 | Array_Person[] people = new Array_Person[3]; // Array of size 3 33 | 34 | // Initialize array elements with Array_Person objects 35 | people[0] = new Array_Person("Alice", 25); 36 | people[1] = new Array_Person("Bob", 30); 37 | people[2] = new Array_Person("Charlie", 35); 38 | 39 | // Access and print information of each Array_Person 40 | for (Array_Person Array_Person : people) { 41 | System.out.println("Name: " + Array_Person.getName() + ", Age: " + Array_Person.getAge()); 42 | } 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/AccessModifier.java: -------------------------------------------------------------------------------- 1 | // Access modifiers 2 | /* 3 | Access modifiers in Java control the visibility and accessibility of classes, methods, and variables within a program. 4 | They enforce encapsulation and help in implementing data hiding, abstraction, and access control mechanisms. 5 | There are four main types of access modifiers in Java: 6 | 7 | Private: 8 | -The private access modifier restricts access to the class, method, or variable to within the same class only. 9 | -It is the most restrictive access modifier and ensures the highest level of encapsulation. 10 | 11 | Default (Package-private): 12 | -If no access modifier is specified, it is considered to have default access. 13 | -The default access modifier allows access only within the same package. 14 | -Classes, methods, and variables with default access can only be accessed within the same package and are not accessible outside the package. 15 | 16 | Protected: 17 | -The protected access modifier allows access to the class, method, or variable within the same package or subclasses (even if they belong to different packages). 18 | -It is more restrictive than public but less restrictive than default and private. 19 | 20 | Public: 21 | -The public access modifier allows unrestricted access to the class, method, or variable from any other class or package. 22 | -Classes with public access can be accessed from anywhere in the program.It has the widest scope of accessibility. 23 | -Methods and variables with public access can be accessed from any class. 24 | 25 | */ 26 | 27 | // AccessModifier.java 28 | 29 | // Class with default access modifier 30 | class AccessClass { 31 | // Private variable accessible only within the class 32 | @SuppressWarnings("unused") 33 | private int privateVar = 10; 34 | 35 | // Default variable accessible within the package 36 | int defaultVar = 20; 37 | 38 | // Protected variable accessible within the package and by subclasses 39 | protected int protectedVar = 30; 40 | 41 | // Public variable accessible from anywhere 42 | public int publicVar = 40; 43 | 44 | // Private method accessible only within the class 45 | @SuppressWarnings("unused") 46 | private void privateMethod() { 47 | System.out.println("Private method called"); 48 | } 49 | 50 | // Default method accessible within the package 51 | void defaultMethod() { 52 | System.out.println("Default method called"); 53 | } 54 | 55 | // Protected method accessible within the package and by subclasses 56 | protected void protectedMethod() { 57 | System.out.println("Protected method called"); 58 | } 59 | 60 | // Public method accessible from anywhere 61 | public void publicMethod() { 62 | System.out.println("Public method called"); 63 | } 64 | } 65 | 66 | // Main class to demonstrate access modifiers 67 | public class AccessModifier { 68 | public static void main(String[] args) { 69 | AccessClass obj = new AccessClass(); 70 | 71 | // Accessing variables 72 | //obj.privateVar; // Error: privateVar has private access in AccessClass 73 | System.out.println("Default variable: " + obj.defaultVar); // Output: Default variable: 20 74 | System.out.println("Protected variable: " + obj.protectedVar); // Output: Protected variable: 30 75 | System.out.println("Public variable: " + obj.publicVar); // Output: Public variable: 40 76 | 77 | // Accessing methods 78 | //obj.privateMethod(); // Error: privateMethod() has private access in AccessClass 79 | obj.defaultMethod(); // Output: Default method called 80 | obj.protectedMethod(); // Output: Protected method called 81 | obj.publicMethod(); // Output: Public method called 82 | } 83 | } 84 | 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/AnonymousObject.java: -------------------------------------------------------------------------------- 1 | // Anonymous Object 2 | /* 3 | In Java, an anonymous object is an object that is created without assigning it to any variable. 4 | Instead, it is instantiated and used directly at the point of creation. 5 | Anonymous objects are typically used for one-time use or for performing a single operation without the need to store the reference for later use. 6 | 7 | Anonymous objects are useful when: 8 | -You need to perform a single operation or method call without storing the object's reference. 9 | -There's no need to reuse the object or access its state later in the program. 10 | -You want to keep the code concise and avoid cluttering it with unnecessary variable declarations. 11 | */ 12 | 13 | public class AnonymousObject { 14 | public void displayMessage() { 15 | System.out.println("Hello, this is an anonymous object!"); 16 | } 17 | 18 | public static void main(String[] args) { 19 | /* 20 | // Normal Object creation using references 21 | AnonymousObject obj = new AnonymousObject(); 22 | obj.displayMessage(); 23 | */ 24 | 25 | // Creating and using an anonymous object 26 | new AnonymousObject().displayMessage(); // Creating an anonymous object of AnonymousObject and calling displayMessage method directly 27 | 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/ConditionalStatements.java: -------------------------------------------------------------------------------- 1 | public class ConditionalStatements { 2 | public static void main(){ 3 | int a = 7; 4 | int b = 8; 5 | byte c = 10; 6 | 7 | // conditional statement 8 | if(a>b && a>c) 9 | System.out.println("a is greater " + a); 10 | else if(b>c) 11 | System.out.println("b is greater " + b); 12 | else 13 | System.out.println("c is greater " + c); 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/Constructor.java: -------------------------------------------------------------------------------- 1 | // Constructor 2 | /* 3 | 1)Constructor in Java: 4 | A constructor in Java is a special type of method that is automatically invoked when an object of a class is created. 5 | It is used to initialize the state of an object by assigning initial values to its instance variables or performing any necessary setup tasks. 6 | constructors are automatically invoked each time when an object of a class is created. 7 | 8 | 2)Key Points: 9 | - Purpose: 10 | - Initialization: Constructors initialize the newly created object with initial values. 11 | - Setup Tasks: They can perform any setup tasks required before the object is ready to use. 12 | - Characteristics: 13 | - Same name as class: Constructors have the same name as the class they belong to. 14 | - No return type: Constructors do not have a return type, not even void. 15 | - Invoked implicitly: They are invoked implicitly by the new keyword when an object is created. 16 | - Cannot be called directly: Constructors cannot be called directly using methods like other member functions. 17 | 18 | // Example of a constructor 19 | public class MyClass { 20 | public MyClass() { 21 | // Constructor body 22 | } 23 | } 24 | 25 | 3)Types of Constructors: 26 | a. Default Constructor: 27 | - A constructor with no parameters is called a default constructor. 28 | - It is automatically provided by the compiler if no other constructors are defined. 29 | - Initializes instance variables to their default values (0 for numeric types, null for reference types, etc.). 30 | 31 | // Example of a default constructor 32 | public class MyClass { 33 | public MyClass() { 34 | // Default constructor body 35 | } 36 | } 37 | 38 | b. Parameterized Constructor: 39 | - A constructor with parameters is called a parameterized constructor. 40 | - Allows initialization of instance variables with specified values passed as arguments during object creation. 41 | 42 | // Example of a parameterized constructor 43 | public class MyClass { 44 | public MyClass(int value) { 45 | // Parameterized constructor body 46 | } 47 | } 48 | 49 | c. Copy Constructor: 50 | - A constructor that creates an object by copying the state of another object of the same class. 51 | - Typically used to create a new object with the same state as an existing object. 52 | 53 | // Example of a copy constructor 54 | public class MyClass { 55 | public MyClass(MyClass obj) { 56 | // Copy constructor body 57 | } 58 | } 59 | 60 | 4)Constructor Overloading: 61 | - Like other methods, constructors can be overloaded by defining multiple constructors with different parameter lists. 62 | - Allows creating objects with different initialization options based on the parameters passed. 63 | 64 | // Example of constructor overloading 65 | public class MyClass { 66 | public MyClass() { 67 | // Default constructor body 68 | } 69 | 70 | public MyClass(int value) { 71 | // Parameterized constructor body 72 | } 73 | } 74 | 75 | 5)Constructor Access Modifiers: 76 | - Constructors can have access modifiers like public, protected, private, or default (no modifier). 77 | - The choice of access modifier determines the visibility of the constructor. 78 | 79 | // Example of constructors with access modifiers 80 | public class MyClass { 81 | public MyClass() { 82 | // Public constructor body 83 | } 84 | 85 | private MyClass(int value) { 86 | // Private constructor body 87 | } 88 | } 89 | 90 | 6)Initialization Block: 91 | -In addition to constructors, initialization blocks are also used to initialize instance variables. 92 | -Static initialization blocks are executed when the class is loaded, while instance initialization blocks are executed when an object is created. 93 | 94 | */ 95 | 96 | 97 | public class Constructor { 98 | private int value; 99 | 100 | // Default constructor 101 | public Constructor() { 102 | value = 0; 103 | } 104 | 105 | // Parameterized constructor 106 | public Constructor(int value) { 107 | this.value = value; 108 | } 109 | 110 | // Copy constructor 111 | public Constructor(Constructor obj) { 112 | this.value = obj.value; 113 | } 114 | 115 | // Constructor overloading 116 | public Constructor(double value) { 117 | this.value = (int) value; 118 | } 119 | 120 | // Initialization block 121 | { 122 | // Initialization block 123 | // Executed each time when an object is created 124 | System.out.println("Object initialized"); 125 | } 126 | 127 | public static void main(String[] args) { 128 | // Creating objects using different constructors 129 | Constructor obj1 = new Constructor(); // Default constructor 130 | Constructor obj2 = new Constructor(10); // Parameterized constructor 131 | Constructor obj3 = new Constructor(obj2); // Copy constructor 132 | Constructor obj4 = new Constructor(3.14); // Constructor overloading 133 | 134 | // Printing values 135 | System.out.println(obj1.value); // Output: 0 136 | System.out.println(obj2.value); // Output: 10 137 | System.out.println(obj3.value); // Output: 10 (Copied value) 138 | System.out.println(obj4.value); // Output: 3 (Type casted from double to int) 139 | } 140 | } 141 | 142 | 143 | 144 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/ControlFlow.java: -------------------------------------------------------------------------------- 1 | // Main class 2 | public class ControlFlow { 3 | public static void main(String[] args) { 4 | 5 | System.out.println("WhileLoop"); 6 | WhileLoop whileExample = new WhileLoop(); 7 | whileExample.runWhileLoop(); 8 | 9 | System.out.println("--------------"); 10 | 11 | System.out.println("DoWhileLoop"); 12 | DoWhileLoop doWhileExample = new DoWhileLoop(); 13 | doWhileExample.runDoWhileLoop(); 14 | 15 | System.out.println("--------------"); 16 | 17 | System.out.println("ForLoop"); 18 | ForLoop ForLoopExample = new ForLoop(); 19 | ForLoopExample.runForLoop(); 20 | } 21 | } 22 | 23 | class WhileLoop { 24 | public void runWhileLoop() { 25 | int i = 1; 26 | // while loop 27 | while (i <= 5) { 28 | System.out.println("Count is: " + i); 29 | i++; 30 | } 31 | } 32 | } 33 | 34 | class DoWhileLoop { 35 | public void runDoWhileLoop() { 36 | int i = 1; 37 | // do-while loop 38 | do { 39 | System.out.println("Count is: " + i); 40 | i++; 41 | } while (i > 5); 42 | } 43 | } 44 | 45 | class ForLoop { 46 | public void runForLoop() { 47 | // for loop 48 | for (int i = 5; i > 0; --i) { 49 | System.out.println("Count is: " + i); 50 | } 51 | } 52 | } 53 | 54 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/EnumConcept.java: -------------------------------------------------------------------------------- 1 | // Enums 2 | /* 3 | Enums, short for "enumerations," in Java are a special type of data type that allows for a variable to be a set of predefined constants. 4 | Enumerations make code more readable and maintainable by providing a way to represent a fixed set of constants. 5 | 6 | Definition: 7 | -Enums are declared using the enum keyword in Java. 8 | -They can contain one or more constants, separated by commas. 9 | -Each constant represents an instance of the enum type and is implicitly declared as a public static final field within the enum. 10 | Example: 11 | enum Day { 12 | SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY 13 | } 14 | 15 | Constants: 16 | -Enum constants are implicitly declared as public static final fields within the enum. 17 | -They are typically named using uppercase letters to distinguish them from regular variables. 18 | -Enum constants are accessed using the dot notation (Day.MONDAY, for example). 19 | 20 | Methods: 21 | -Enums can contain methods, constructors, and fields like regular classes. 22 | -You can define custom methods within an enum to perform operations specific to the enum constants. 23 | 24 | Ordinal and Values: 25 | -Each enum constant has an ordinal value, which represents its position in the enum declaration (starting from zero). 26 | -The ordinal() method returns the ordinal value of an enum constant. 27 | -The values() method returns an array containing all the enum constants in the order they are declared. 28 | */ 29 | 30 | // Define an enum representing different days of the week 31 | enum Day { 32 | // Enum constants 33 | SUNDAY("Sunday"), 34 | MONDAY("Monday"), 35 | TUESDAY("Tuesday"), 36 | WEDNESDAY("Wednesday"), 37 | THURSDAY("Thursday"), 38 | FRIDAY("Friday"), 39 | SATURDAY("Saturday"); 40 | 41 | // Enum fields 42 | private final String displayName; 43 | 44 | // Constructor to initialize enum fields 45 | Day(String displayName) { 46 | this.displayName = displayName; 47 | } 48 | 49 | // Method to get display name of the day 50 | public String getDisplayName() { 51 | return displayName; 52 | } 53 | 54 | // Static method to get enum constant by display name 55 | public static Day getByDisplayName(String displayName) { 56 | for (Day day : values()) { 57 | if (day.displayName.equals(displayName)) { 58 | return day; 59 | } 60 | } 61 | throw new IllegalArgumentException("Invalid display name: " + displayName); 62 | } 63 | } 64 | 65 | public class EnumConcept { 66 | public static void main(String[] args) { 67 | // Accessing enum constants 68 | Day today = Day.SATURDAY; 69 | System.out.println("Today is: " + today); // Output: SATURDAY 70 | 71 | // Using switch statement with enum 72 | switch (today) { 73 | case MONDAY: 74 | case TUESDAY: 75 | case WEDNESDAY: 76 | case THURSDAY: 77 | case FRIDAY: 78 | System.out.println("It's a weekday"); 79 | break; 80 | case SATURDAY: 81 | case SUNDAY: 82 | System.out.println("It's a weekend"); 83 | break; 84 | } 85 | 86 | // Accessing enum fields and methods 87 | System.out.println("Display name of SATURDAY: " + Day.SATURDAY.getDisplayName()); // Output: Saturday 88 | 89 | // Using static method to get enum constant by display name 90 | Day holiday = Day.getByDisplayName("Sunday"); 91 | System.out.println("Holiday is: " + holiday); // Output: SUNDAY 92 | 93 | // Displaying ordinal and values of enum constants 94 | for (Day day : Day.values()) { 95 | System.out.println("Ordinal of " + day + ": " + day.ordinal()); // Output: Ordinal of DAY: 0, Ordinal of SATURDAY: 6 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/ExceptionHandlingConcept.java: -------------------------------------------------------------------------------- 1 | // 2 | /* 3 | Exception handling in Java is a mechanism to handle runtime errors or exceptional conditions that may occur during the execution of a program. 4 | It helps in maintaining the normal flow of the program by providing a way to deal with unexpected situations gracefully. 5 | To ensure that the code runs smoothly without abruptly terminating, all critical statements are managed through exception handling. This approach allows the program to handle unexpected errors gracefully, preventing it from crashing prematurely. 6 | Here are the key aspects related to exception handling in Java: 7 | 8 | 1. Types of Exceptions: 9 | 10 | 1) Checked Exceptions: 11 | - These are the exceptions that are checked at compile-time. 12 | - They must be either caught using try-catch blocks or declared using the throws keyword in the method signature. 13 | 14 | 2) Unchecked Exceptions (Runtime Exceptions): 15 | - These are exceptions that are not checked at compile-time. 16 | - They typically occur due to programming errors and do not require explicit handling. 17 | - Examples include NullPointerException, ArrayIndexOutOfBoundsException, etc. 18 | 19 | 2. Exception Hierarchy: 20 | |- Error(Can't be handled), Ex. Thread Death, IO Error, virtualMachineError,OutOfMemory 21 | - Object(Class) -> Throwable(Class)-> 22 | |- Exception(can be handled) -> Checked(IO,Sql Exceptions) & Unchecked(RunTime Exception,Ex: Arithmetic, ArrayIndexOutOfBound, NullPointer) 23 | - All exception classes in Java are subclasses of the Throwable class. 24 | - Throwable has two main subclasses: Exception and Error. 25 | - Exceptions are further divided into checked and unchecked exceptions. 26 | 27 | 3. Exception Handling Keywords and Constructs: 28 | 29 | 1) try-catch Block: 30 | - It is used to enclose the code that may throw an exception. 31 | - If an exception occurs within the try block, it is caught by the corresponding catch block. 32 | 33 | 2) throw Keyword: 34 | - It is used to explicitly throw an exception from a method or block of code. 35 | - when you use the throw keyword to manually throw an exception, it is typically used in conjunction with the new keyword to create an instance of the exception object that you want to throw. 36 | - new: Keyword used to create a new instance of the exception object. 37 | 38 | 3) throws Keyword: 39 | - It is used in method signatures to declare that the method may throw certain exceptions. 40 | - It delegates the responsibility of handling exceptions to the caller method. 41 | - declared in the header of the method to throws to caller method. 42 | 43 | 4) finally Block: 44 | - It is used to execute code that must be run regardless of whether an exception occurs or not. 45 | - It is typically used for resource cleanup. 46 | 47 | 4. Handling Exceptions: 48 | 49 | 1) Catching Exceptions: 50 | - Exceptions are caught using try-catch blocks. 51 | - Multiple catch blocks can be used to handle different types of exceptions. 52 | 53 | 2) Throwing Exceptions: 54 | - Exceptions can be thrown explicitly using the throw keyword. 55 | 56 | 3) Propagating Exceptions: 57 | - Exceptions can be propagated to the caller method using the throws keyword. 58 | 59 | 4) Cleanup with finally: 60 | - Resources like file handles, database connections, etc., can be safely closed in the finally block to ensure proper cleanup. 61 | 62 | */ 63 | 64 | // Custom exception class 65 | class CustomException extends Exception //extends from inBuild Exception class 66 | { 67 | // Constructor 68 | public CustomException(String message) { 69 | super(message); 70 | } 71 | } 72 | 73 | // Class to demonstrate try-catch block 74 | class TryCatchExample { 75 | @SuppressWarnings("null") //just used to avoid shown null pointer compile time error to get it from exception 76 | public void demonstrateTryCatch() { 77 | try 78 | { 79 | // ArithmeticException 80 | @SuppressWarnings("unused") 81 | int result = 10 / 0; // Division by zero to trigger ArithmeticException 82 | // ArrayIndexOutOfBoundsException 83 | int arr[] = {1,2,3,4,5}; 84 | System.out.println(arr[5]); 85 | // NullPointerException 86 | String str = null; 87 | System.out.println(str.length()); 88 | 89 | } 90 | catch (ArithmeticException e) { 91 | System.out.println("Exception caught: ArithmeticException" + e.getMessage()); 92 | } 93 | catch(ArrayIndexOutOfBoundsException e) { 94 | System.out.println("Exception caught: ArrayIndexOutOfBound "+ e.getMessage()); 95 | } 96 | catch(NullPointerException e){ 97 | System.out.println("Exception caught: NullPointerException "+ e.getMessage()); 98 | } 99 | catch(Exception e) //general exception catch always at the last 100 | { 101 | System.out.println("Exception Caught: "+ e); 102 | } 103 | finally{ 104 | System.out.println("Done"); 105 | } 106 | } 107 | } 108 | 109 | // Class to demonstrate throw keyword 110 | class ThrowExample { 111 | public void demonstrateThrow() { 112 | try { 113 | throw new NullPointerException("Message- Custom NullPointerException"); //Explicitly pass exception with message 114 | } catch (NullPointerException e) { 115 | System.out.println("Exception caught: " + e.getMessage()); //getMessage() is used to get the message 116 | } 117 | } 118 | } 119 | 120 | // Class to demonstrate throws keyword 121 | class ThrowsExample { 122 | // Method declaration with throws clause 123 | public void demonstrateThrows() throws Exception { 124 | // Code that might potentially throw an exception 125 | @SuppressWarnings("unused") 126 | int result = 10 / 0; // This line will throw an ArithmeticException 127 | } 128 | } 129 | 130 | // Class to demonstrate try-catch-finally block 131 | class TryCatchFinallyExample { 132 | public void demonstrateTryCatchFinally() { 133 | try { 134 | @SuppressWarnings("unused") 135 | int result = 10 / 0; // Division by zero to trigger ArithmeticException 136 | } catch (ArithmeticException e) { 137 | System.out.println("Exception caught: " + e.getMessage()); 138 | } finally { 139 | System.out.println("Finally block executed"); 140 | } 141 | } 142 | } 143 | 144 | public class ExceptionHandlingConcept { 145 | public static void main(String[] args) { 146 | 147 | System.out.println("TryCatchExample--------------------------------"); 148 | // Demonstrate try-catch block 149 | TryCatchExample tryCatchExample = new TryCatchExample(); 150 | tryCatchExample.demonstrateTryCatch(); 151 | 152 | System.out.println("ThrowExample--------------------------------"); 153 | // Demonstrate throw keyword 154 | ThrowExample throwExample = new ThrowExample(); 155 | throwExample.demonstrateThrow(); 156 | 157 | System.out.println("ThrowsExample--------------------------------"); 158 | // Demonstrate throws keyword 159 | ThrowsExample throwsExample = new ThrowsExample(); 160 | try { 161 | throwsExample.demonstrateThrows(); 162 | } catch (Exception e) { 163 | System.out.println("Exception caught: " + e); 164 | } 165 | 166 | System.out.println("CustomException--------------------------------"); 167 | // Demonstrate custom exception (just use throw, obj creation is not needed for constructor) 168 | try { 169 | throw new CustomException("Custom Exception occurred"); //we can pass our the message with it 170 | } catch (CustomException e) { 171 | System.out.println("Exception caught: " + e.getMessage()); 172 | } 173 | 174 | System.out.println("TryCatchFinallyExample--------------------------------"); 175 | // Demonstrate try-catch-finally block 176 | TryCatchFinallyExample tryCatchFinallyExample = new TryCatchFinallyExample(); 177 | tryCatchFinallyExample.demonstrateTryCatchFinally(); 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/GenericClass.java: -------------------------------------------------------------------------------- 1 | // Generic class (same as Template in c++) 2 | /* 3 | A generic class in Java is a class that can work with any data type. 4 | It allows you to define a class with placeholders for data types, which are specified when the class is instantiated. 5 | Generics provide type safety and enable code reusability by allowing you to create classes and methods that operate on different data types without having to rewrite the code for each type. 6 | 7 | Declaration: 8 | To declare a generic class, you use angle brackets (<>) to specify one or more type parameters. 9 | These parameters represent the types that the class will work with. 10 | For example: 11 | ```java 12 | public class MyClass { 13 | // Class definition goes here 14 | } 15 | ``` 16 | 17 | Type Parameters: 18 | Type parameters are placeholders for actual data types. 19 | They are usually represented by single uppercase letters, such as T, E, or K, but you can use any valid Java identifier. 20 | You can specify multiple type parameters separated by commas. 21 | 22 | Instantiation: 23 | When you create an object of a generic class, you specify the actual data types to be used in place of the type parameters. 24 | For example: 25 | ```java 26 | MyClass myObject = new MyClass<>(); 27 | ``` 28 | Here, Integer is the actual type used for the type parameter T. 29 | 30 | Type Safety: 31 | Generics provide compile-time type safety, ensuring that you only use the correct data types with generic classes. 32 | This helps catch type-related errors at compile time rather than runtime. 33 | 34 | Code Reusability: 35 | Generic classes promote code reusability by allowing you to write classes and methods that operate on different data types without duplicating code. 36 | This makes the code more maintainable and reduces redundancy. 37 | 38 | Generic Methods: 39 | In addition to generic classes, Java also supports generic methods, which are methods that can accept and return generic types. 40 | Generic methods are declared similarly to generic classes but are defined within regular classes or interfaces. 41 | */ 42 | 43 | public class GenericClass { 44 | private T content; 45 | 46 | public void setContent(T content) { 47 | this.content = content; 48 | } 49 | 50 | public T getContent() { 51 | return content; 52 | } 53 | 54 | public static void main(String[] args) { 55 | GenericClass intBox = new GenericClass<>(); 56 | intBox.setContent(10); 57 | System.out.println("Integer Box Content: " + intBox.getContent()); 58 | 59 | GenericClass strBox = new GenericClass<>(); 60 | strBox.setContent("Hello, Generics!"); 61 | System.out.println("String Box Content: " + strBox.getContent()); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/MethodOverloading.java: -------------------------------------------------------------------------------- 1 | // Main class 2 | public class MethodOverloading { 3 | public static void main(String[] a){ 4 | MethodOverloadingCalculator obj = new MethodOverloadingCalculator(); 5 | 6 | // Call the methods 7 | System.out.println("Sum of 5 and 7: " + obj.add(5, 7)); 8 | System.out.println("Sum of 2, 3, and 4: " + obj.add(2, 3, 4)); 9 | System.out.println("Sum of 2.5 and 3.7: " + obj.add(2.5, 3.7)); 10 | System.out.println("Sum of 1.1, 2.2, and 3.3: " + obj.add(1.1, 2.2, 3.3)); 11 | } 12 | } 13 | 14 | class MethodOverloadingCalculator 15 | { 16 | // Method to add two integers 17 | public int add(int a, int b) { 18 | return a + b; 19 | } 20 | 21 | // Method to add three integers 22 | public int add(int a, int b, int c) { 23 | return a + b + c; 24 | } 25 | 26 | // Method to add two doubles 27 | public double add(double a, double b) { 28 | return a + b; 29 | } 30 | 31 | // Method to add three doubles 32 | public double add(double a, double b, double c) { 33 | return a + b + c; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/NestedClass.java: -------------------------------------------------------------------------------- 1 | // Nested Class 2 | /* 3 | Oops_NestedClass is OuterClass 4 | */ 5 | public class NestedClass { 6 | private int outerVariable; 7 | 8 | public NestedClass(int outerVariable) { 9 | this.outerVariable = outerVariable; 10 | } 11 | 12 | // Nested class 13 | public class InnerClass { 14 | private int innerVariable; 15 | 16 | public InnerClass(int innerVariable) { 17 | this.innerVariable = innerVariable; 18 | } 19 | 20 | public void display() { 21 | System.out.println("Outer variable: " + outerVariable); 22 | System.out.println("Inner variable: " + innerVariable); 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | // Creating an object of the outer class 28 | NestedClass outerObj = new NestedClass(10); 29 | 30 | // Creating an object of the inner class using the outer class object 31 | NestedClass.InnerClass innerObj = outerObj.new InnerClass(20); 32 | 33 | // Calling the display method of the inner class 34 | innerObj.display(); 35 | } 36 | } 37 | 38 | /* 39 | The NestedClass(OuterClass) contains an instance variable outerVariable and a nested class InnerClass. 40 | The InnerClass contains an instance variable innerVariable and a method display() to print both outer and inner variables. 41 | Inside the main method, an object of the outer class outerObj is created. 42 | Then, using the outer class object, an object of the inner class innerObj is created. 43 | Finally, the display() method of the inner class is called to print the values of both outer and inner variables. 44 | */ 45 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/ObjectClassConcept.java: -------------------------------------------------------------------------------- 1 | // Object class 2 | /* 3 | The Object class is the root class of all Java classes. It is automatically inherited by all other classes in Java. 4 | It resides in the java.lang package and is automatically imported into every Java program. 5 | Some of the commonly used Object methods: 6 | 7 | 1)toString() Method: 8 | -The toString() method returns a string representation of the object. 9 | -By default, the toString() method returns a string that consists of the class name followed by the "@" symbol and the hashcode of the object. 10 | -It is often overridden in user-defined classes to provide meaningful string representations of objects. 11 | 2)equals() Method: 12 | -The equals() method compares two objects for equality. 13 | -By default, the equals() method in the Object class compares object references for equality (i.e., whether they refer to the same object in memory). 14 | -It is often overridden in user-defined classes to provide custom equality comparisons based on object attributes. 15 | 3)hashCode() Method: 16 | -The hashCode() method returns the hashcode value of the object. 17 | -The hashcode value is used in hash-based data structures like HashMap to determine the storage location of objects. 18 | -It is often overridden in user-defined classes to provide custom hashcode implementations that are consistent with the equals() method. 19 | 4)getClass() Method: 20 | -The getClass() method returns the runtime class of the object. 21 | -It returns an object of type Class, which provides information about the class. 22 | */ 23 | 24 | 25 | // Custom class for demonstrating toString() method 26 | class ToStringDemo { 27 | private int value; 28 | 29 | // Constructor 30 | public ToStringDemo(int value) { 31 | this.value = value; 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return "Value: " + value; 37 | } 38 | } 39 | 40 | // Custom class for demonstrating equals() method 41 | class EqualsDemo { 42 | private int value; 43 | 44 | public EqualsDemo(int value) { 45 | this.value = value; 46 | } 47 | 48 | @Override 49 | public boolean equals(Object obj) { 50 | if (this == obj) { 51 | return true; 52 | } 53 | if (obj == null || getClass() != obj.getClass()) { 54 | return false; 55 | } 56 | EqualsDemo other = (EqualsDemo) obj; 57 | return value == other.value; 58 | } 59 | } 60 | 61 | // Custom class for demonstrating hashCode() method 62 | class HashCodeDemo { 63 | private int value; 64 | 65 | public HashCodeDemo(int value) { 66 | this.value = value; 67 | } 68 | 69 | @Override 70 | public int hashCode() { 71 | return Integer.hashCode(value); 72 | } 73 | } 74 | 75 | // Main class to demonstrate usage of custom and built-in object methods 76 | public class ObjectClassConcept { 77 | public static void main(String[] args) { 78 | // Demo of toString() method 79 | ToStringDemo toStringDemo = new ToStringDemo(42); 80 | System.out.println("toString() method result: " + toStringDemo); // Output: Value: 42 81 | 82 | // Demo of equals() method 83 | EqualsDemo obj1 = new EqualsDemo(10); 84 | EqualsDemo obj2 = new EqualsDemo(10); 85 | System.out.println("equals() method result: " + obj1.equals(obj2)); // Output: true 86 | 87 | // Demo of hashCode() method 88 | HashCodeDemo hashCodeDemo = new HashCodeDemo(42); 89 | System.out.println("hashCode() method result: " + hashCodeDemo.hashCode()); // Output: 42 90 | 91 | // Demo of getClass() method 92 | Object obj = new Object(); 93 | System.out.println("getClass() method result: " + obj.getClass()); // Output: class java.lang.Object 94 | } 95 | } 96 | 97 | /* 98 | code demonstrates the usage of toString(), equals(), and hashCode() methods in separate classes, along with the getClass() method. 99 | Each custom class overrides the respective method to provide custom behavior. 100 | The main method in the ObjectClassConcept class calls and uses these methods to demonstrate their functionality. 101 | */ 102 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/ReadingUserInput.java: -------------------------------------------------------------------------------- 1 | // Reading input from User 2 | /* 3 | Reading input from the user in Java can be done using various methods provided by the Scanner class(commonly used) or BufferedReader class. 4 | 5 | 1)Using Scanner class: 6 | The Scanner class, available in the java.util package, 7 | provides various methods to read different types of input from the user. 8 | 9 | 2) Using BufferedReader class: 10 | The BufferedReader class, available in the java.io package, is used to 11 | read text from a character-input stream with efficiency and provides more flexibility than Scanner for reading large volumes of text. 12 | 13 | ----- 14 | 15 | next(): Reads the next token (sequence of characters separated by whitespace) from the input. It stops reading when it encounters whitespace (space, tab, or newline). The newline character (Enter key) is not consumed and remains in the input buffer. 16 | nextLine(): Reads the entire line of input until it encounters a newline character (Enter key). It consumes the newline character. 17 | */ 18 | 19 | import java.util.Scanner; 20 | import java.io.BufferedReader; 21 | import java.io.IOException; 22 | import java.io.InputStreamReader; 23 | 24 | 25 | // Class to read user input using Scanner 26 | 27 | class ScannerInputReader { 28 | void readInput() { 29 | @SuppressWarnings("resource") 30 | Scanner scanner = new Scanner(System.in); 31 | 32 | // Reading a string 33 | System.out.print("Enter a string (using Scanner): "); 34 | String inputString = scanner.nextLine(); 35 | System.out.println("You entered: " + inputString); 36 | 37 | // Reading an integer 38 | System.out.print("Enter an integer (using Scanner): "); 39 | int inputInt = scanner.nextInt(); 40 | System.out.println("You entered: " + inputInt); 41 | 42 | // Reading a floating-point number 43 | System.out.print("Enter a floating-point number (using Scanner): "); 44 | double inputDouble = scanner.nextDouble(); 45 | System.out.println("You entered: " + inputDouble); 46 | 47 | // Closing the scanner 48 | // scanner.close(); //must use 49 | } 50 | } 51 | 52 | // Class to read user input using BufferedReader 53 | class BufferedReaderInputReader { 54 | void readInput() throws IOException { 55 | 56 | // InputStreamReader in = new InputStreamReader(System.in); 57 | // BufferedReader reader = new BufferedReader(in); 58 | // OR 59 | // OneLine Implementation of BufferReader 60 | BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 61 | 62 | // Reading a string 63 | System.out.print("Enter a string (using BufferedReader): "); 64 | String inputString = reader.readLine(); 65 | System.out.println("You entered: " + inputString); 66 | 67 | // Reading an integer 68 | System.out.print("Enter an integer (using BufferedReader): "); 69 | int inputInt = Integer.parseInt(reader.readLine()); 70 | System.out.println("You entered: " + inputInt); 71 | 72 | // Reading a floating-point number 73 | System.out.print("Enter a floating-point number (using BufferedReader): "); 74 | double inputDouble = Double.parseDouble(reader.readLine()); 75 | System.out.println("You entered: " + inputDouble); 76 | 77 | // Closing the BufferedReader 78 | // reader.close(); 79 | } 80 | } 81 | 82 | // Main class to demonstrate both methods of reading user input 83 | public class ReadingUserInput { 84 | public static void main(String[] args) throws IOException { 85 | ScannerInputReader scannerReader = new ScannerInputReader(); 86 | scannerReader.readInput(); 87 | 88 | BufferedReaderInputReader bufferedReaderReader = new BufferedReaderInputReader(); 89 | bufferedReaderReader.readInput(); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/RegexConcept.java: -------------------------------------------------------------------------------- 1 | // Regex 2 | /* 3 | Regular expressions are powerful tools for pattern matching and text manipulation, often abbreviated as regex or regexp. 4 | They provide a concise and flexible syntax for specifying search patterns within strings. 5 | 6 | Syntax: 7 | - Regex patterns are defined as strings in Java. 8 | - Special characters in regex patterns have special meanings, such as: 9 | - . (matches any character) 10 | - * (matches zero or more occurrences) 11 | - + (matches one or more occurrences) 12 | - ? (matches zero or one occurrence) 13 | - [] (matches any character within the brackets) 14 | - {} (specifies the number of occurrences), etc. 15 | 16 | Character Class: 17 | - A character class in regex allows you to match any one of a set of characters. 18 | - It is defined within square brackets []. 19 | - For example, [aeiou] matches any vowel, [0-9] matches any digit, [a-zA-Z] matches any letter (both lowercase and uppercase). 20 | - Inside a character class, certain metacharacters like ., *, +, etc., lose their special meaning and are treated as literal characters. 21 | 22 | Quantifiers: 23 | - Quantifiers specify how many times a character or group of characters can occur in a regex pattern. 24 | - Common quantifiers include: 25 | - *: Matches zero or more occurrences of the preceding character or group. 26 | - +: Matches one or more occurrences of the preceding character or group. 27 | - ?: Matches zero or one occurrence of the preceding character or group. 28 | - {n}: Matches exactly n occurrences of the preceding character or group. 29 | - {n,}: Matches at least n occurrences of the preceding character or group. 30 | - {n,m}: Matches between n and m occurrences of the preceding character or group. 31 | - Quantifiers are greedy by default, meaning they match as much as possible. Adding ? after a quantifier makes it reluctant, matching as little as possible. 32 | 33 | Metacharacters: 34 | - Metacharacters are characters in a regex pattern that have a special meaning. 35 | - Some common metacharacters include: 36 | - .: Matches any single character except newline. 37 | - ^: Anchors the match to the beginning of the string. 38 | - $: Anchors the match to the end of the string. 39 | - \b: Word boundary, matches the position between a word character and a non-word character. 40 | - \d: Matches any digit (equivalent to [0-9]). 41 | - \D: Matches any non-digit character (equivalent to [^\d]). 42 | - \w: Matches any word character (equivalent to [a-zA-Z0-9_]). 43 | - \s: Matches any whitespace character (space, tab, newline, etc.). 44 | - \S: Matches any non-whitespace character (equivalent to [^\s]). 45 | - |: Alternation, matches either the pattern before or after the pipe symbol. 46 | - (): Grouping, groups multiple patterns together. 47 | - [ ]: Character class, matches any single character within the brackets. 48 | - -: Range, specifies a range of characters within a character class. 49 | - ^: Negation, matches any character not within the brackets when used as the first character inside a character class. 50 | - \: Escape, escapes the following character, allowing you to match metacharacters as literals. 51 | 52 | Commonly Used Constructs: 53 | - \d: Matches any digit (equivalent to [0-9]). 54 | - \w: Matches any word character (equivalent to [a-zA-Z0-9_]). 55 | - \s: Matches any whitespace character (space, tab, newline, etc.). 56 | - .: Matches any single character except newline. 57 | - []: Matches any single character within the brackets. 58 | - |: Alternation, matches either the pattern before or after the pipe symbol. 59 | - (): Grouping, groups multiple patterns together. 60 | - ^: Anchors the match to the beginning of the string. 61 | - $: Anchors the match to the end of the string. 62 | - \b: Word boundary, matches the position between a word character and a non-word character. 63 | 64 | groups(): 65 | - When a regular expression pattern contains capturing groups (defined by parentheses ()), each capturing group captures a portion of the input string that matches the pattern within the parentheses. 66 | - After a successful match, you can use the group() method on a Matcher object to retrieve the substring that matched a specific capturing group. 67 | - The group() method takes an integer argument representing the index of the capturing group to retrieve. Index 0 represents the entire match, while indexes 1 and above represent individual capturing groups. 68 | - If the regular expression pattern contains multiple capturing groups, you can call group(1), group(2), and so on to access the substrings captured by each group. 69 | - If the pattern contains no capturing groups, calling group() or group(0) will return the entire match. 70 | 71 | Example Usage: 72 | - Validating email addresses: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ 73 | - Matching phone numbers: \d{3}-\d{3}-\d{4} 74 | - Finding words containing "java": \bjava\b 75 | - Extracting numbers from a string: \d+ 76 | 77 | Java API: 78 | - In Java, regex functionalities are provided by the java.util.regex package. 79 | - Key classes include Pattern and Matcher. 80 | - Pattern: Represents a compiled regex pattern. 81 | - Matcher: Used to perform matching operations on a character sequence. 82 | */ 83 | 84 | import java.util.regex.Matcher; 85 | import java.util.regex.Pattern; 86 | 87 | public class RegexConcept { 88 | public static void main(String[] args) { 89 | // Define a regex pattern to match email addresses 90 | String emailPattern = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"; 91 | 92 | // Define a regex pattern to match phone numbers 93 | String phonePattern = "\\d{3}-\\d{3}-\\d{4}"; 94 | 95 | // Define a sample text 96 | String text = "Contact us at email@example.com or call 123-456-7890 for assistance. Another email address is john.doe@example.com"; 97 | 98 | // Compile the patterns 99 | Pattern emailRegex = Pattern.compile(emailPattern); 100 | Pattern phoneRegex = Pattern.compile(phonePattern); 101 | 102 | // Match email addresses in the text 103 | Matcher emailMatcher = emailRegex.matcher(text); 104 | while (emailMatcher.find()) { 105 | System.out.println("Email found: " + emailMatcher.group()); 106 | } 107 | 108 | // Match phone numbers in the text 109 | Matcher phoneMatcher = phoneRegex.matcher(text); 110 | while (phoneMatcher.find()) { 111 | System.out.println("Phone number found: " + phoneMatcher.group()); 112 | } 113 | } 114 | } 115 | 116 | 117 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/Stack_vs_Heap.java: -------------------------------------------------------------------------------- 1 | // Stack Memory vs Heap Memory 2 | /* 3 | Stack Memory: 4 | 5 | Definition: 6 | Stack memory is used for storing method frames, local variables, and method call information. 7 | Usage: 8 | Each thread in a Java program has its own stack memory. 9 | When a method is called, a new frame is pushed onto the stack to store local variables and method parameters. 10 | When the method completes, its frame is popped off the stack. 11 | Characteristics: 12 | Stack memory is fast and has a limited size. 13 | Memory allocation and deallocation are managed automatically by the JVM. 14 | Variables stored on the stack have a short lifespan and are destroyed as soon as their method exits. 15 | 16 | Heap Memory: 17 | 18 | Definition: 19 | Heap memory is used for dynamic memory allocation, primarily for objects and arrays. 20 | Usage: 21 | All objects in Java are allocated memory from the heap. 22 | When an object is created using the new keyword, memory is allocated from the heap, and a reference to that memory location is returned. 23 | Characteristics: 24 | Heap memory is larger than stack memory and is shared among all threads. 25 | Objects stored on the heap have a longer lifespan and persist until they are no longer referenced or garbage collected. 26 | Memory allocation and deallocation are managed automatically by the JVM's garbage collector. 27 | */ 28 | 29 | public class Stack_vs_Heap { 30 | public static void main(String[] a){ 31 | StackMemory obj1 = new StackMemory(); 32 | obj1.runStackMemory(); 33 | 34 | HeapMemory obj2 = new HeapMemory(); 35 | obj2.runHeapMemory(); 36 | } 37 | } 38 | 39 | class StackMemory { 40 | public void runStackMemory() { 41 | int x = 5; // Stored on the stack 42 | int y = 10; // Stored on the stack 43 | int z = add(x, y); // Method call, a new frame is pushed onto the stack 44 | System.out.println("Sum: " + z); 45 | } 46 | 47 | public static int add(int a, int b) { // Method definition, a new frame is pushed onto the stack 48 | return a + b; // Temporary variables 'a' and 'b' are stored on the stack 49 | } // Method completes, frame is popped off the stack 50 | } 51 | 52 | class HeapMemory { 53 | public void runHeapMemory() { 54 | // Object allocation on the heap 55 | Heap_Person RunHeap_Person = new Heap_Person("John", 25); // Memory allocated on the heap 56 | System.out.println("Name: " + RunHeap_Person.getName() + ", Age: " + RunHeap_Person.getAge()); 57 | } 58 | } 59 | 60 | class Heap_Person { 61 | private String name; 62 | private int age; 63 | 64 | // Constructor 65 | public Heap_Person(String name, int age) { 66 | this.name = name; 67 | this.age = age; 68 | } 69 | 70 | // Getter methods 71 | public String getName() { 72 | return name; 73 | } 74 | 75 | public int getAge() { 76 | return age; 77 | } 78 | } 79 | 80 | /* 81 | An object of the Heap_Person class is allocated memory on the heap using the new keyword. 82 | The object's attributes (name and age) are stored in memory allocated on the heap. 83 | The object's reference (RunHeap_Person) is stored on the stack, and its lifespan is determined by the scope of the variable holding the reference. 84 | */ 85 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/StaticConcepts.java: -------------------------------------------------------------------------------- 1 | // static keyword 2 | /* 3 | static keyword is used to define members (variables, methods, and blocks) that belong to the class itself, rather than to individual instances of the class. 4 | 5 | 1)Static Variable: 6 | -A static variable, also known as a class variable, is shared among all instances of a class. 7 | -There is only one copy of a static variable, regardless of how many instances of the class are created. 8 | -Static variables are initialized only once, at the start of the execution, and retain their values throughout the program's lifetime. 9 | -They are accessed using the class name followed by the dot (.) operator. 10 | 2)Static Method: 11 | -A static method belongs to the class rather than to any specific instance of the class. 12 | -Static methods can be invoked directly using the class name, without the need to create an instance of the class. 13 | -They cannot access non-static (instance) variables and methods directly, but can access other static members. 14 | -Static methods are commonly used for utility functions or operations that do not require access to instance-specific data. 15 | 3)Static Block: 16 | -A static block is a special type of block that executes only once when the class is loaded into memory. 17 | -It is used to initialize static variables or perform any one-time initialization tasks for the class. 18 | -Static blocks are executed in the order they appear in the class, from top to bottom 19 | -A static block is executed when the class is loaded into the JVM, regardless of whether any objects of that class are created or not. 20 | -This behavior ensures that static initialization tasks are performed before any instances of the class are created or any static members are accessed. 21 | Common Use Cases: 22 | -Static variables are often used for constants, counters, or shared resources across instances. 23 | -Static methods are used for utility functions, factory methods, or helper functions that do not require access to instance-specific data. 24 | -Static blocks are used for one-time initialization tasks, such as loading configuration files or initializing static variables. 25 | */ 26 | 27 | public class StaticConcepts { 28 | 29 | // Static variable 30 | static int staticVar = 10; // Shared among all instances 31 | 32 | // Normal variable 33 | int normalVar = 20; // Instance-specific 34 | 35 | // Static block 36 | static { 37 | System.out.println("Static block executed."); 38 | } 39 | 40 | // Normal block 41 | { 42 | System.out.println("Normal block executed."); 43 | } 44 | 45 | // Static method 46 | static void staticMethod() { 47 | System.out.println("Static method called."); 48 | } 49 | 50 | // Normal method 51 | void normalMethod() { 52 | System.out.println("Normal method called."); 53 | } 54 | 55 | // Main method 56 | public static void main(String[] args) { 57 | // Creating an instance of the class 58 | StaticConcepts obj = new StaticConcepts(); 59 | 60 | // Accessing static variable and method directly using class name 61 | System.out.println("Static variable: " + StaticConcepts.staticVar); 62 | staticMethod(); 63 | 64 | // Accessing normal variable and method using object 65 | System.out.println("Normal variable: " + obj.normalVar); 66 | obj.normalMethod(); 67 | } 68 | } 69 | 70 | /* 71 | Static Keyword in main(): 72 | -Entry Point: The main method is where the Java program starts running. It's the first method executed by the JVM. 73 | -No Object Creation: Since the main method is called by the JVM before any objects are created, it must be static. Non-static methods require an object to be called, but the main method is invoked without creating any objects. 74 | -Access Without Instantiation: Declaring the main method as static allows it to be called directly using the class name. This makes the syntax simpler and emphasizes that the main method is a class-level entry point. 75 | */ 76 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/SwitchCase.java: -------------------------------------------------------------------------------- 1 | public class SwitchCase { 2 | public static void main(){ 3 | 4 | // Ṣwitch Case 5 | 6 | int a = 3; 7 | switch(a){ 8 | case 1: 9 | System.out.println("Monday"); 10 | break; 11 | case 2: 12 | System.out.println("Tuesday"); 13 | break; 14 | case 3: 15 | System.out.println("Wednesday"); 16 | break; 17 | case 4: 18 | System.out.println("Thursday"); 19 | break; 20 | case 5: 21 | System.out.println("Friday"); 22 | break; 23 | case 6: 24 | System.out.println("Saturday"); 25 | break; 26 | case 7: 27 | System.out.println("Sunday"); 28 | break; 29 | default: 30 | System.out.println("Invalid Input"); 31 | } 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/TernaryOperator.java: -------------------------------------------------------------------------------- 1 | public class TernaryOperator { 2 | public static void main(String[] args){ 3 | int a = 8; 4 | int b = 9; 5 | byte c = 7; 6 | 7 | // Ternary Operator 8 | System.out.println("Largest: " + ((a>b&&a>c)?a:(b>c)?b:c) ); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/Up_down_Casting.java: -------------------------------------------------------------------------------- 1 | // Upcasting/downcasting 2 | /* 3 | Upcasting and downcasting are concepts related to inheritance in object-oriented programming, particularly in Java. 4 | 5 | Upcasting: 6 | - Upcasting refers to the process of casting a subclass reference to a superclass reference. 7 | - It is always safe and does not require an explicit cast operator. 8 | - Upcasting allows you to treat an object of a subclass as an object of its superclass. 9 | - Upcasting is implicitly performed by the compiler. 10 | 11 | Downcasting: 12 | - Downcasting refers to the process of casting a superclass reference to a subclass reference. 13 | - It is not safe and requires an explicit cast operator. 14 | - Downcasting is used when you want to access members specific to the subclass. 15 | - It may result in a ClassCastException at runtime if the object being casted is not actually an instance of the subclass. 16 | */ 17 | 18 | 19 | // Class for upcasting 20 | class cast_Animal { 21 | void makeSound() { 22 | System.out.println("cast_Animal makes a sound"); 23 | } 24 | } 25 | 26 | // Subclass of cast_Animal 27 | class cast_Dog extends cast_Animal { 28 | void bark() { 29 | System.out.println("cast_Dog barks"); 30 | } 31 | } 32 | 33 | public class Up_down_Casting { 34 | public static void main(String[] args) { 35 | // Upcasting: Subclass object to superclass reference 36 | cast_Dog dog = new cast_Dog(); // Creating a cast_Dog object 37 | cast_Animal animal = dog; // Upcasting cast_Dog to cast_Animal 38 | 39 | // Accessing method using cast_Animal reference 40 | animal.makeSound(); // Output: cast_Animal makes a sound 41 | 42 | // Downcasting: Superclass reference to subclass reference 43 | // Must be done explicitly and may throw ClassCastException if not valid 44 | cast_Animal animal2 = new cast_Dog(); // Upcasting cast_Dog to cast_Animal 45 | cast_Dog dog2 = (cast_Dog) animal2; // Downcasting cast_Animal to cast_Dog (explicit cast) 46 | 47 | // Accessing method specific to cast_Dog class 48 | dog2.bark(); // Output: cast_Dog barks 49 | } 50 | } 51 | 52 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/_HelloWorld.java: -------------------------------------------------------------------------------- 1 | /* 2 | // Structure of a Java Program: 3 | 4 | 1.Package Declaration (Optional): 5 | package com.example.myProject; 6 | -A package is a namespace that organizes a set of related classes and interfaces. 7 | -It helps in avoiding naming conflicts and provides better organization. 8 | 2.Import Statements (Optional): 9 | import java.util.Scanner; 10 | -Import statements are used to import classes, interfaces, or entire packages into the current program. 11 | 3.Class Declaration: 12 | public class MyClass { 13 | // Class members (fields and methods) go here 14 | } 15 | -A class is the basic building block of Java programs. 16 | -It encapsulates data for the object and methods to operate on that data. 17 | 4.Main Method: 18 | public static void main(String[] args) { 19 | // Program logic goes here 20 | } 21 | -The main method serves as the entry point of the Java program. 22 | -It has a specific signature (public static void main(String[] args)) and is where program execution begins. 23 | 5.Other Class Members: 24 | public class MyClass { 25 | int number; // Field 26 | public void display() { // Method 27 | System.out.println("Number: " + number); 28 | }} 29 | -Inside the class declaration, you can define fields (variables) and methods (functions) that define the behavior of the class. 30 | */ 31 | 32 | // Compiling and Running Java Programs: 33 | /* 34 | Compiling Java Programs: 35 | 1.Write Code: 36 | Create a Java source file with a .java extension containing your Java code. 37 | 2.Compile Code: 38 | javac MyClass.java 39 | -Use the javac command to compile the Java source file into bytecode. 40 | -Use cd comment in the terminal to change directory 41 | 3.Generated Files: 42 | -If there are no errors, the compiler generates one or more .class files containing bytecode. 43 | 44 | Running Java Programs: 45 | 1.Run Compiled Program: 46 | java MyClass 47 | -Use the java command to run the compiled Java program. 48 | 2.Main Method Execution: 49 | -The java command looks for the main method in the specified class and starts program execution from there. 50 | 3.ClassPath and Package Names: 51 | java -cp . com.example.myProject.MyClass 52 | -If your program uses classes from other packages or directories, you need to specify the classPath using the -cp option. 53 | -For example, if your class is in a package, you need to specify the package name along with the class name when running the program. 54 | */ 55 | 56 | //-------------------------------------------------------------- 57 | 58 | // Hello World! 59 | 60 | public class _HelloWorld { 61 | public static void main(String[] args) { 62 | System.out.println("Hello World!"); 63 | } 64 | } 65 | 66 | // 67 | /* 68 | public class HelloWorld: 69 | Declares a class named HelloWorld. In Java, every application consists of at least one class. 70 | public static void main(String[] args): 71 | Every Java program must have a main method, which serves as the entry point of the program. 72 | It has a specific signature (public static void main(String[] args)) and is where program execution begins. 73 | System.out.println("Hello, World!");: 74 | This statement prints "Hello, World!" to the console. System.out refers to the standard output stream, and println() is a method to print a line of text. 75 | 76 | Static Keyword in main(): 77 | -Entry Point: The main method is where the Java program starts running. It's the first method executed by the JVM. 78 | -No Object Creation: Since the main method is called by the JVM before any objects are created, it must be static. Non-static methods require an object to be called, but the main method is invoked without creating any objects. 79 | -Access Without Instantiation: Declaring the main method as static allows it to be called directly using the class name. This makes the syntax simpler and emphasizes that the main method is a class-level entry point. 80 | String[] args: 81 | -String[] args is the parameter list, which allows the program to accept command-line arguments as an array of strings 82 | */ 83 | 84 | //-------------------------------------------------------------- 85 | 86 | // Findings: 87 | 88 | // Naming convention: 89 | /* 90 | - PascalNamingConvention - Classes, Interface 91 | - camelNamingConvention - Methods, Variables 92 | - ALLCAPITAL - Constants 93 | */ 94 | 95 | // In Java, you can have multiple classes in the same file, but only one of them can be public, and the filename must match the name of the public class. 96 | 97 | // The process of object creation in Java into two steps: class loading and object instantiation. 98 | 99 | /* 100 | // 'Class' Class in Java: 101 | In Java, the Class class is a fundamental part of the language and runtime environment, providing a way to represent classes and interfaces at runtime. 102 | It allows developers to examine and manipulate the runtime properties of classes dynamically. 103 | */ 104 | 105 | //Findings: Avoiding Class Name Conflicts in Java: Organizing Files in Separate Directories 106 | /* 107 | -If you have two Java files in the same directory with classes having the same name, but you are trying to compile or run one of them individually, you might encounter errors due to class name conflicts. 108 | -When you compile Java files, the compiler generates corresponding .class files for each class, and if you have two classes with the same name, they will overwrite each other in the same directory. 109 | -To resolve this issue and compile/run both sets of files independently, you can place each set of Java files in its own separate directory. This way, the compiler will generate separate .class files in each directory, avoiding conflicts. , give me suitable title for it 110 | */ 111 | -------------------------------------------------------------------------------- /Java_Concepts/Basic/_Intro.java: -------------------------------------------------------------------------------- 1 | //Java - JDK 21 2 | /* 3 | Java was developed by James Gosling and his team at Sun Microsystems in the early 1990s. 4 | Java is a multi-platform, object-oriented, and network-centric language that can be used as a platform in itself. 5 | Java - Just Another Virtual Accelerator. 6 | It was originally designed for interactive television, but its developers soon realized its potential for Internet applications. 7 | In 1995, Java 1.0 was released to the public, and it quickly gained popularity due to its key features like platform independence, object-oriented nature, robustness, and security. 8 | */ 9 | 10 | // Java is Platform Independent (WORA - Write Once Run Anywhere) 11 | /* 12 | -JDK (Java Development Kit): Used by developers for writing, compiling, and packaging Java applications. Includes compiler, JRE, and development tools. 13 | -JRE (Java Runtime Environment): Used by end-users for running Java applications. Includes JVM and Java class libraries. 14 | -JVM (Java Virtual Machine): Executes Java bytecode and provides a runtime environment for Java applications. Handles memory management and platform independence. 15 | In short, JDK is for development, JRE is for running applications, and JVM is the runtime environment executing the Java bytecode. 16 | 17 | Java is a platform-independent programming language. 18 | You can run your application on any machine regardless of its hardware or operating system. 19 | However, the machine must have a Java Virtual Machine (JVM), which itself is platform-dependent. 20 | This means that while your Java code is platform-independent, the JVM required to execute it is not. 21 | To run Java programs, you need additional libraries during runtime. 22 | The Java Runtime Environment (JRE) combines the JVM with these extra libraries. 23 | When running programs on another machine, only the JRE and JVM are necessary; the Java Development Kit (JDK) is not required. 24 | This characteristic is why Java is known as 'Write Once, Run Anywhere' (WORA)." 25 | */ 26 | 27 | //Key Features: 28 | /* 29 | 1)Platform Independence: Java programs are compiled into bytecode, which is platform-independent. 30 | This bytecode can be executed on any device with a Java Virtual Machine (JVM), making Java applications highly portable. 31 | 2)Object-Oriented: Java is a fully object-oriented programming language, meaning it supports concepts like encapsulation, inheritance, and polymorphism. 32 | This promotes code reusability, modularity, and easier maintenance. 33 | 3)Robustness: Java was designed with a strong emphasis on reliability and error handling. 34 | Features like strong type checking, automatic memory management (garbage collection), and exception handling contribute to the robustness of Java programs. 35 | 4)Security: Java's security model protects users from harmful code. 36 | The JVM enforces security restrictions, such as preventing unauthorized access to system resources and executing untrusted code in a sandboxed environment. 37 | 5)Multi-threading: Java provides built-in support for multi-threading, allowing concurrent execution of multiple tasks within a single program. 38 | This enables developers to create responsive and efficient applications. 39 | 6)Rich API: Java comes with an extensive library of classes and APIs (Application Programming Interfaces) known as the Java API. 40 | This library provides ready-to-use components for tasks like I/O operations, networking, GUI development, and more, saving developers time and effort. 41 | */ 42 | 43 | //Applications of Java: 44 | /* 45 | Enterprise Applications: Java's scalability, reliability, and portability make it popular for developing large-scale enterprise applications, 46 | including banking systems, e-commerce platforms, and customer relationship management (CRM) software. 47 | Web Development: Java is commonly used for server-side web development. 48 | Technologies like Servlets, JavaServer Pages (JSP), and JavaServer Faces (JSF) enable developers to create dynamic and interactive web applications. 49 | Mobile Development: With platforms like Android being powered by Java, the language is extensively used for developing mobile applications. 50 | Android Studio, the official IDE for Android development, uses Java as its primary language. 51 | Desktop Applications: Java's Swing and JavaFX libraries facilitate the development of cross-platform desktop applications with rich graphical user interfaces (GUIs). 52 | Embedded Systems: Java's portability and security features make it suitable for developing embedded systems, such as smart cards, set-top boxes, and industrial automation 53 | */ 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /Java_Concepts/Collection/CollectionConcept.java: -------------------------------------------------------------------------------- 1 | // Collection 2 | /* 3 | 1.Introduction to Collections: 4 | - Collections in Java represent a group of objects known as elements. It provides a framework for storing, manipulating, and accessing groups of objects efficiently. 5 | - They offer a wide range of data structures and algorithms to efficiently manage collections of elements. 6 | - Java Collections Framework (JCF) is a set of classes and interfaces provided in the java.util package for working with collections. 7 | 8 | 2.Interfaces: 9 | - Collection: The root interface in the collection hierarchy. It defines the basic operations supported by all collection types, such as adding, removing, and querying elements. 10 | - List: An ordered collection that allows duplicate elements. Lists maintain the order of elements based on their insertion sequence. Implementations include ArrayList, LinkedList, etc. 11 | - Set: A collection that does not allow duplicate elements. Sets are used when the uniqueness of elements is important. Implementations include HashSet, TreeSet, etc. 12 | - Queue: A collection designed for holding elements prior to processing. Queues typically order elements in a FIFO (First-In-First-Out) manner. Implementations include LinkedList, PriorityQueue, etc. 13 | - Map: An object that maps keys to values. Maps do not allow duplicate keys and each key can map to at most one value. Implementations include HashMap, TreeMap, etc. 14 | 15 | 3.Classes: 16 | - ArrayList: A resizable array implementation of the List interface. It provides dynamic resizing and fast random access. 17 | - LinkedList: A doubly linked list implementation of the List interface. It provides efficient insertion and deletion operations. 18 | - HashSet: An implementation of the Set interface using a hash table. It provides constant-time performance for basic operations. 19 | - TreeSet: An implementation of the Set interface based on a Red-Black tree. It maintains elements in sorted order. 20 | - HashMap: An implementation of the Map interface using a hash table. It provides constant-time performance for basic operations. 21 | - TreeMap: An implementation of the Map interface based on a Red-Black tree. It maintains key-value pairs in sorted order. 22 | 23 | 4.Common Methods: 24 | - add(E element): Adds the specified element to the collection. 25 | - remove(Object obj): Removes the specified element from the collection. 26 | - contains(Object obj): Returns true if the collection contains the specified element. 27 | - size(): Returns the number of elements in the collection. 28 | - iterator(): Returns an iterator over the elements in the collection. 29 | 30 | 5.Iteration: 31 | - Collections support iteration through various mechanisms such as iterators, enhanced for loops, and forEach method. 32 | - Iterators provide a way to traverse through the elements of a collection. 33 | - The Iterator interface defines methods like next(), hasNext(), and remove() for iterating over collections. 34 | 35 | 6.Sorting: 36 | - Collections can be sorted using the Collections.sort() method or by implementing the Comparable or Comparator interfaces. 37 | - The Collections.sort() method for List implementations or by using a SortedSet or TreeMap for automatic sorting. 38 | 39 | 7.Generics: 40 | - Java Collections Framework uses generics to ensure type safety. 41 | - Generics allow collections to store elements of a specific type, providing compile-time type checking and eliminating the need for explicit type casting. 42 | */ 43 | 44 | 45 | import java.util.ArrayList; 46 | import java.util.HashMap; 47 | import java.util.HashSet; 48 | import java.util.List; 49 | import java.util.Map; 50 | import java.util.Set; 51 | 52 | public class CollectionConcept { 53 | public static void main(String[] args) { 54 | // List Example 55 | List list = new ArrayList<>(); 56 | list.add("Java"); 57 | list.add("Python"); 58 | list.add("C++"); 59 | list.add("JavaScript"); 60 | 61 | System.out.println("List Example:"); 62 | // Enhanced For loop 63 | for (String language : list) { 64 | System.out.println(language); 65 | } 66 | 67 | // forEach 68 | // list.forEach(language -> System.out.println(language)); 69 | System.out.println(); 70 | 71 | // Set Example 72 | Set set = new HashSet<>(); 73 | set.add(10); 74 | set.add(20); 75 | set.add(30); 76 | set.add(40); 77 | set.add(20); // Duplicate element, automatically removed 78 | 79 | System.out.println("Set Example:"); 80 | // for (int number : set) { 81 | // System.out.println(number); 82 | // } 83 | 84 | // forEach 85 | set.forEach(number -> System.out.println(number)); 86 | System.out.println(); 87 | 88 | // Map Example 89 | Map map = new HashMap<>(); 90 | map.put("One", 1); 91 | map.put("Two", 2); 92 | map.put("Three", 3); 93 | map.put("Four", 4); 94 | 95 | System.out.println("Map Example:"); 96 | // for (Map.Entry entry : map.entrySet()) { 97 | // System.out.println(entry.getKey() + " - " + entry.getValue()); 98 | // } 99 | 100 | // forEach 101 | map.forEach((key, value) -> System.out.println(key + " - " + value)); 102 | } 103 | } 104 | 105 | /* 106 | List: Stores a list of elements in a specific order. 107 | Set: Stores a collection of unique elements (no duplicates). 108 | Map: Stores key-value pairs where each key maps to a corresponding value. 109 | It creates instances of ArrayList, HashSet, and HashMap, adds elements to them, and then iterates over each collection to print its contents. 110 | */ -------------------------------------------------------------------------------- /Java_Concepts/Collection/Collection_List_Interface.java: -------------------------------------------------------------------------------- 1 | // Collection_List_Interface 2 | /* 3 | List: 4 | - An ordered collection that allows duplicate elements. 5 | - Lists maintain the order of elements based on their insertion sequence. 6 | - Implementations include ArrayList, LinkedList, etc. 7 | 8 | ArrayList: 9 | - ArrayList is a resizable array implementation of the List interface in Java. 10 | - It stores elements sequentially in memory and allows random access to elements based on their index. 11 | - Provides dynamic resizing, automatically growing or shrinking as needed. 12 | - Offers fast access to elements but slower insertion and deletion operations, especially in the middle. 13 | - Suitable for scenarios where random access and iteration are frequent, but insertion and deletion operations are less common. 14 | Some commonly used methods: 15 | add(): Adds an element to the ArrayList. 16 | get(): Retrieves the element at the specified index. 17 | size(): Returns the number of elements in the ArrayList. 18 | remove(): Removes the first occurrence of the specified element from the ArrayList. 19 | contains(): Returns true if the ArrayList contains the specified element. 20 | 21 | LinkedList: 22 | - LinkedList is a doubly-linked list implementation of the List interface in Java. 23 | - It consists of nodes, where each node contains a reference to the previous and next nodes in the sequence. 24 | - Allows fast insertion and deletion operations anywhere in the list, as it only requires adjusting the references of neighboring nodes. 25 | - Provides slower access to elements compared to ArrayList because it requires traversing the list from the beginning or end to reach a specific index. 26 | - Suitable for scenarios where frequent insertion and deletion operations are required, especially in the middle of the list, but random access is less common. 27 | Some commonly used methods: 28 | add(): Adds an element to the LinkedList. 29 | get(): Retrieves the element at the specified index. 30 | size(): Returns the number of elements in the LinkedList. 31 | remove(): Removes the first occurrence of the specified element from the LinkedList. 32 | contains(): Returns true if the LinkedList contains the specified element. 33 | */ 34 | 35 | import java.util.*; 36 | 37 | // Interface for demonstrating List interface 38 | interface ListInterfaceExample { 39 | void demonstrateList(); 40 | } 41 | 42 | // Class demonstrating ArrayList implementation of List interface 43 | class ArrayListExample implements ListInterfaceExample { 44 | @Override 45 | public void demonstrateList() { 46 | // Creating an ArrayList 47 | List arrayList = new ArrayList<>(); 48 | 49 | // Adding elements to the ArrayList 50 | arrayList.add("Apple"); 51 | arrayList.add("Banana"); 52 | arrayList.add("Orange"); 53 | 54 | // Accessing elements using index 55 | System.out.println("Elements of ArrayList:"); 56 | for (String fruit : arrayList) { 57 | System.out.println(fruit); 58 | } 59 | 60 | // Getting the size of the ArrayList 61 | System.out.println("Size of ArrayList: " + arrayList.size()); 62 | 63 | // Removing an element 64 | arrayList.remove("Banana"); 65 | System.out.println("Elements of ArrayList after removing 'Banana': " + arrayList); 66 | 67 | // Checking if an element exists 68 | boolean containsApple = arrayList.contains("Apple"); 69 | System.out.println("ArrayList contains 'Apple': " + containsApple); 70 | 71 | // Adding elements at specific index 72 | arrayList.add(1, "Grapes"); 73 | System.out.println("ArrayList after adding 'Grapes' at index 1: " + arrayList); 74 | } 75 | } 76 | 77 | // Class demonstrating LinkedList implementation of List interface 78 | class LinkedListExample implements ListInterfaceExample { 79 | @Override 80 | public void demonstrateList() { 81 | // Creating a LinkedList 82 | List linkedList = new LinkedList<>(); 83 | 84 | // Adding elements to the LinkedList 85 | linkedList.add(10); 86 | linkedList.add(20); 87 | linkedList.add(30); 88 | 89 | // Accessing elements using index 90 | System.out.println("Elements of LinkedList:"); 91 | for (int num : linkedList) { 92 | System.out.println(num); 93 | } 94 | 95 | // Getting the size of the LinkedList 96 | System.out.println("Size of LinkedList: " + linkedList.size()); 97 | 98 | // Removing an element 99 | linkedList.remove(Integer.valueOf(20)); 100 | System.out.println("Elements of LinkedList after removing 20: " + linkedList); 101 | 102 | // Checking if an element exists 103 | boolean contains30 = linkedList.contains(30); 104 | System.out.println("LinkedList contains 30: " + contains30); 105 | 106 | // Adding elements at specific index 107 | linkedList.add(1, 25); 108 | System.out.println("LinkedList after adding 25 at index 1: " + linkedList); 109 | } 110 | } 111 | 112 | // Main class to demonstrate List interface and its implementations 113 | public class Collection_List_Interface { 114 | public static void main(String[] args) { 115 | // Demonstrating ArrayList 116 | ListInterfaceExample arrayListExample = new ArrayListExample(); 117 | System.out.println("ArrayList Example:"); 118 | arrayListExample.demonstrateList(); 119 | System.out.println(); 120 | 121 | System.out.println("-----------------------------------------------------------------"); 122 | 123 | // Demonstrating LinkedList 124 | ListInterfaceExample linkedListExample = new LinkedListExample(); 125 | System.out.println("LinkedList Example:"); 126 | linkedListExample.demonstrateList(); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /Java_Concepts/Collection/Collection_Map_Interface.java: -------------------------------------------------------------------------------- 1 | // Collection_Map_Interface 2 | /* 3 | Map: 4 | - A collection that maps keys to values. 5 | - Each key must be unique, and it can map to at most one value. 6 | - Implementations include HashMap, TreeMap, LinkedHashMap, etc. 7 | 8 | HashMap: 9 | - HashMap is an implementation of the Map interface in Java. 10 | - It uses a hash table for storage, providing constant-time performance for basic operations (put, get, remove). 11 | - 'Does not guarantee the order of elements'. 12 | - Allows one null key and multiple null values. 13 | Some commonly used methods: 14 | put(): Associates the specified value with the specified key in the HashMap. 15 | get(): Returns the value to which the specified key is mapped, or null if the key is not present. 16 | remove(): Removes the mapping for the specified key from the HashMap if present. 17 | containsKey(): Returns true if the HashMap contains the specified key. 18 | containsValue(): Returns true if the HashMap maps one or more keys to the specified value. 19 | size(): Returns the number of key-value mappings in the HashMap. 20 | 21 | TreeMap: 22 | - TreeMap is an implementation of the SortedMap interface in Java. 23 | - It stores key-value pairs in sorted order (natural ordering or by a Comparator). 24 | - Provides efficient operations for finding keys and iterating in sorted order. 25 | - Does not allow null keys but can have multiple null values. 26 | Some commonly used methods: 27 | put(): Associates the specified value with the specified key in the TreeMap. 28 | get(): Returns the value to which the specified key is mapped, or null if the key is not present. 29 | remove(): Removes the mapping for the specified key from the TreeMap if present. 30 | containsKey(): Returns true if the TreeMap contains the specified key. 31 | containsValue(): Returns true if the TreeMap maps one or more keys to the specified value. 32 | size(): Returns the number of key-value mappings in the TreeMap. 33 | firstKey(): Returns the first (lowest) key currently in the TreeMap. 34 | lastKey(): Returns the last (highest) key currently in the TreeMap. 35 | 36 | LinkedHashMap: 37 | - LinkedHashMap is an implementation of the Map interface in Java. 38 | - It maintains insertion order, meaning the elements are ordered based on their insertion sequence. 39 | - Provides predictable iteration order. 40 | - Allows one null key and multiple null values. 41 | Some commonly used methods: 42 | put(): Associates the specified value with the specified key in the LinkedHashMap. 43 | get(): Returns the value to which the specified key is mapped, or null if the key is not present. 44 | remove(): Removes the mapping for the specified key from the LinkedHashMap if present. 45 | containsKey(): Returns true if the LinkedHashMap contains the specified key. 46 | containsValue(): Returns true if the LinkedHashMap maps one or more keys to the specified value. 47 | size(): Returns the number of key-value mappings in the LinkedHashMap. 48 | 49 | HahMap vs HashTable: 50 | - HashMap and Hashtable are both implementations of the Map interface in Java, but they have some differences: 51 | - HashMap is preferred in most cases due to its better performance and flexibility, while Hashtable is used in situations where thread safety is critical. 52 | 53 | HashMap: 54 | - HashMap is not synchronized, meaning it is not thread-safe. Multiple threads can access and modify a HashMap concurrently, but if it's not properly synchronized, it may lead to unexpected behavior. 55 | - Allows null values and one null key. 56 | - Iteration through the elements is not guaranteed to be in any particular order. 57 | - HashMap is generally preferred for most applications due to its performance and flexibility. 58 | 59 | Hashtable: 60 | - Hashtable is synchronized, making it thread-safe. Access to a Hashtable is synchronized on the Hashtable object itself, which means only one thread can access it at a time. This synchronization comes with a performance cost. 61 | - Does not allow null values or null keys. If you try to insert null as a key or value, it will throw a NullPointerException. 62 | - Iteration through the elements is in the order in which they were inserted. 63 | - Hashtable is considered legacy and has largely been replaced by HashMap in modern Java applications, unless thread safety is explicitly required. 64 | */ 65 | 66 | import java.util.*; 67 | 68 | // Interface for demonstrating Map interface 69 | interface MapInterfaceExample { 70 | void demonstrateMap(); 71 | } 72 | 73 | // Class demonstrating HashMap implementation of Map interface 74 | class HashMapExample implements MapInterfaceExample { 75 | @Override 76 | public void demonstrateMap() { 77 | // Creating a HashMap 78 | Map hashMap = new HashMap<>(); 79 | 80 | // Adding key-value pairs to the HashMap 81 | hashMap.put("Apple", 10); 82 | hashMap.put("Banana", 20); 83 | hashMap.put("Orange", 30); 84 | 85 | // Accessing elements 86 | System.out.println("Elements of HashMap:"); 87 | for (Map.Entry entry : hashMap.entrySet()) { 88 | System.out.println(entry.getKey() + ": " + entry.getValue()); 89 | } 90 | 91 | // Getting the size of the HashMap 92 | System.out.println("Size of HashMap: " + hashMap.size()); 93 | 94 | // Removing a key-value pair 95 | hashMap.remove("Banana"); 96 | System.out.println("Elements of HashMap after removing 'Banana': " + hashMap); 97 | 98 | // Checking if a key exists 99 | boolean containsKey = hashMap.containsKey("Apple"); 100 | System.out.println("HashMap contains key 'Apple': " + containsKey); 101 | 102 | // Checking if a value exists 103 | boolean containsValue = hashMap.containsValue(30); 104 | System.out.println("HashMap contains value 30: " + containsValue); 105 | } 106 | } 107 | 108 | // Class demonstrating TreeMap implementation of Map interface 109 | class TreeMapExample implements MapInterfaceExample { 110 | @Override 111 | public void demonstrateMap() { 112 | // Creating a TreeMap 113 | Map treeMap = new TreeMap<>(); 114 | 115 | // Adding key-value pairs to the TreeMap 116 | treeMap.put(3, "Apple"); 117 | treeMap.put(1, "Banana"); 118 | treeMap.put(2, "Orange"); 119 | 120 | // Accessing elements 121 | System.out.println("Elements of TreeMap:"); 122 | for (Map.Entry entry : treeMap.entrySet()) { 123 | System.out.println(entry.getKey() + ": " + entry.getValue()); 124 | } 125 | 126 | // Getting the size of the TreeMap 127 | System.out.println("Size of TreeMap: " + treeMap.size()); 128 | 129 | // Removing a key-value pair 130 | treeMap.remove(1); 131 | System.out.println("Elements of TreeMap after removing key 1: " + treeMap); 132 | 133 | // Checking if a key exists 134 | boolean containsKey = treeMap.containsKey(3); 135 | System.out.println("TreeMap contains key 3: " + containsKey); 136 | 137 | // Getting the first and last keys 138 | System.out.println("First key of TreeMap: " + ((TreeMap) treeMap).firstKey()); 139 | System.out.println("Last key of TreeMap: " + ((TreeMap) treeMap).lastKey()); 140 | } 141 | } 142 | 143 | // Class demonstrating LinkedHashMap implementation of Map interface 144 | class LinkedHashMapExample implements MapInterfaceExample { 145 | @Override 146 | public void demonstrateMap() { 147 | // Creating a LinkedHashMap 148 | Map linkedHashMap = new LinkedHashMap<>(); 149 | 150 | // Adding key-value pairs to the LinkedHashMap 151 | linkedHashMap.put('A', 1); 152 | linkedHashMap.put('B', 2); 153 | linkedHashMap.put('C', 3); 154 | 155 | // Accessing elements 156 | System.out.println("Elements of LinkedHashMap:"); 157 | for (Map.Entry entry : linkedHashMap.entrySet()) { 158 | System.out.println(entry.getKey() + ": " + entry.getValue()); 159 | } 160 | 161 | // Getting the size of the LinkedHashMap 162 | System.out.println("Size of LinkedHashMap: " + linkedHashMap.size()); 163 | 164 | // Removing a key-value pair 165 | linkedHashMap.remove('B'); 166 | System.out.println("Elements of LinkedHashMap after removing key 'B': " + linkedHashMap); 167 | 168 | // Checking if a key exists 169 | boolean containsKey = linkedHashMap.containsKey('A'); 170 | System.out.println("LinkedHashMap contains key 'A': " + containsKey); 171 | } 172 | } 173 | 174 | // Main class to demonstrate Map interface and its implementations 175 | public class Collection_Map_Interface { 176 | public static void main(String[] args) { 177 | // Demonstrating HashMap 178 | MapInterfaceExample hashMapExample = new HashMapExample(); 179 | System.out.println("HashMap Example:"); 180 | hashMapExample.demonstrateMap(); 181 | System.out.println(); 182 | 183 | System.out.println("-----------------------------------------------------------------"); 184 | 185 | // Demonstrating TreeMap 186 | MapInterfaceExample treeMapExample = new TreeMapExample(); 187 | System.out.println("TreeMap Example:"); 188 | treeMapExample.demonstrateMap(); 189 | System.out.println(); 190 | 191 | System.out.println("-----------------------------------------------------------------"); 192 | 193 | // Demonstrating LinkedHashMap 194 | MapInterfaceExample linkedHashMapExample = new LinkedHashMapExample(); 195 | System.out.println("LinkedHashMap Example:"); 196 | linkedHashMapExample.demonstrateMap(); 197 | } 198 | } 199 | 200 | -------------------------------------------------------------------------------- /Java_Concepts/Collection/Collection_Queue_Interface.java: -------------------------------------------------------------------------------- 1 | // Collection_Queue_Interface 2 | /* 3 | Queue: 4 | - A collection designed for holding elements prior to processing. 5 | - Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. 6 | - Implementations include LinkedList, PriorityQueue, etc. 7 | 8 | LinkedList: 9 | - LinkedList can be used as a Queue implementation in Java. 10 | - It provides FIFO (First-In-First-Out) ordering. 11 | - Allows elements to be added and removed from both ends of the Queue. 12 | - Suitable for scenarios where insertion and removal operations are frequent. 13 | Some commonly used methods: 14 | offer(): Adds an element to the end of the Queue. 15 | poll(): Retrieves and removes the head of the Queue. 16 | peek(): Retrieves, but does not remove, the head of the Queue. 17 | size(): Returns the number of elements in the Queue. 18 | 19 | PriorityQueue: 20 | - PriorityQueue is an unbounded priority Queue based on a priority heap. 21 | - Elements are ordered based on their natural ordering or by a Comparator provided at queue construction time. 22 | - Offers elements with the highest priority (as determined by their ordering) first. 23 | - Suitable for scenarios where elements need to be processed based on priority. 24 | Some commonly used methods: 25 | offer(): Adds an element to the PriorityQueue. 26 | poll(): Retrieves and removes the highest priority element from the PriorityQueue. 27 | peek(): Retrieves, but does not remove, the highest priority element from the PriorityQueue. 28 | size(): Returns the number of elements in the PriorityQueue. 29 | */ 30 | 31 | import java.util.*; 32 | 33 | // Interface for demonstrating Queue interface 34 | interface QueueInterfaceExample { 35 | void demonstrateQueue(); 36 | } 37 | 38 | // Class demonstrating LinkedList implementation of Queue interface 39 | class LinkedListQueueExample implements QueueInterfaceExample { 40 | @Override 41 | public void demonstrateQueue() { 42 | // Creating a LinkedList Queue 43 | Queue linkedListQueue = new LinkedList<>(); 44 | 45 | // Adding elements to the Queue 46 | linkedListQueue.offer("Apple"); 47 | linkedListQueue.offer("Banana"); 48 | linkedListQueue.offer("Orange"); 49 | 50 | // Accessing elements 51 | System.out.println("Elements of LinkedList Queue:"); 52 | for (String fruit : linkedListQueue) { 53 | System.out.println(fruit); 54 | } 55 | 56 | // Getting the size of the Queue 57 | System.out.println("Size of LinkedList Queue: " + linkedListQueue.size()); 58 | 59 | // Removing an element 60 | String removedElement = linkedListQueue.poll(); 61 | System.out.println("Removed element from LinkedList Queue: " + removedElement); 62 | 63 | // Peeking at the next element 64 | String nextElement = linkedListQueue.peek(); 65 | System.out.println("Next element in LinkedList Queue: " + nextElement); 66 | } 67 | } 68 | 69 | // Class demonstrating PriorityQueue implementation of Queue interface 70 | class PriorityQueueExample implements QueueInterfaceExample { 71 | @Override 72 | public void demonstrateQueue() { 73 | // Creating a PriorityQueue 74 | Queue priorityQueue = new PriorityQueue<>(); 75 | 76 | // Adding elements to the Queue 77 | priorityQueue.offer(30); 78 | priorityQueue.offer(10); 79 | priorityQueue.offer(20); 80 | 81 | // Accessing elements 82 | System.out.println("Elements of PriorityQueue:"); 83 | for (int num : priorityQueue) { 84 | System.out.println(num); 85 | } 86 | 87 | // Getting the size of the Queue 88 | System.out.println("Size of PriorityQueue: " + priorityQueue.size()); 89 | 90 | // Removing an element 91 | int removedElement = priorityQueue.poll(); 92 | System.out.println("Removed element from PriorityQueue: " + removedElement); 93 | 94 | // Peeking at the next element 95 | int nextElement = priorityQueue.peek(); 96 | System.out.println("Next element in PriorityQueue: " + nextElement); 97 | } 98 | } 99 | 100 | // Main class to demonstrate Queue interface and its implementations 101 | public class Collection_Queue_Interface { 102 | public static void main(String[] args) { 103 | // Demonstrating LinkedList Queue 104 | QueueInterfaceExample linkedListQueueExample = new LinkedListQueueExample(); 105 | System.out.println("LinkedList Queue Example:"); 106 | linkedListQueueExample.demonstrateQueue(); 107 | System.out.println(); 108 | 109 | System.out.println("-----------------------------------------------------------------"); 110 | 111 | // Demonstrating PriorityQueue 112 | QueueInterfaceExample priorityQueueExample = new PriorityQueueExample(); 113 | System.out.println("PriorityQueue Example:"); 114 | priorityQueueExample.demonstrateQueue(); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /Java_Concepts/Collection/Collection_Set_Interface.java: -------------------------------------------------------------------------------- 1 | // Collection_Set_Interface 2 | /* 3 | Set: 4 | - A collection that does not allow duplicate elements. 5 | - Sets do not maintain the order of elements. 6 | - Implementations include HashSet, TreeSet, LinkedHashSet, etc. 7 | 8 | HashSet: 9 | - HashSet is an implementation of the Set interface in Java. 10 | - It uses a hash table for storage, which provides constant-time performance for basic operations (add, remove, contains). 11 | - Does not guarantee the order of elements. 12 | - Does not allow duplicate elements. 13 | Some commonly used methods: 14 | add(): Adds an element to the HashSet. 15 | remove(): Removes the specified element from the HashSet. 16 | contains(): Returns true if the HashSet contains the specified element. 17 | size(): Returns the number of elements in the HashSet. 18 | 19 | TreeSet: 20 | - TreeSet is an implementation of the SortedSet interface in Java. 21 | - It stores elements in sorted order (natural ordering or by a Comparator). 22 | - Offers efficient operations for finding elements and iterating in sorted order. 23 | - Does not allow duplicate elements. 24 | Some commonly used methods: 25 | add(): Adds an element to the TreeSet. 26 | remove(): Removes the specified element from the TreeSet. 27 | contains(): Returns true if the TreeSet contains the specified element. 28 | size(): Returns the number of elements in the TreeSet. 29 | first(): Returns the first (lowest) element currently in the TreeSet. 30 | last(): Returns the last (highest) element currently in the TreeSet. 31 | 32 | LinkedHashSet: 33 | - LinkedHashSet is an implementation of the Set interface in Java. 34 | - It maintains insertion order, which means the elements are ordered based on their insertion sequence. 35 | - Offers constant-time performance for basic operations (add, remove, contains). 36 | - Does not allow duplicate elements. 37 | Some commonly used methods: 38 | add(): Adds an element to the LinkedHashSet. 39 | remove(): Removes the specified element from the LinkedHashSet. 40 | contains(): Returns true if the LinkedHashSet contains the specified element. 41 | size(): Returns the number of elements in the LinkedHashSet. 42 | */ 43 | 44 | import java.util.*; 45 | 46 | // Interface for demonstrating Set interface 47 | interface SetInterfaceExample { 48 | void demonstrateSet(); 49 | } 50 | 51 | // Class demonstrating HashSet implementation of Set interface 52 | class HashSetExample implements SetInterfaceExample { 53 | @Override 54 | public void demonstrateSet() { 55 | // Creating a HashSet 56 | Set hashSet = new HashSet<>(); 57 | 58 | // Adding elements to the HashSet 59 | hashSet.add("Apple"); 60 | hashSet.add("Banana"); 61 | hashSet.add("Orange"); 62 | 63 | // Accessing elements 64 | System.out.println("Elements of HashSet:"); 65 | for (String fruit : hashSet) { 66 | System.out.println(fruit); 67 | } 68 | 69 | // Getting the size of the HashSet 70 | System.out.println("Size of HashSet: " + hashSet.size()); 71 | 72 | // Removing an element 73 | hashSet.remove("Banana"); 74 | System.out.println("Elements of HashSet after removing 'Banana': " + hashSet); 75 | 76 | // Checking if an element exists 77 | boolean containsApple = hashSet.contains("Apple"); 78 | System.out.println("HashSet contains 'Apple': " + containsApple); 79 | } 80 | } 81 | 82 | // Class demonstrating TreeSet implementation of Set interface 83 | class TreeSetExample implements SetInterfaceExample { 84 | @Override 85 | public void demonstrateSet() { 86 | // Creating a TreeSet 87 | Set treeSet = new TreeSet<>(); 88 | 89 | // Adding elements to the TreeSet 90 | treeSet.add(10); 91 | treeSet.add(30); 92 | treeSet.add(20); 93 | 94 | // Accessing elements 95 | System.out.println("Elements of TreeSet:"); 96 | for (int num : treeSet) { 97 | System.out.println(num); 98 | } 99 | 100 | // Getting the size of the TreeSet 101 | System.out.println("Size of TreeSet: " + treeSet.size()); 102 | 103 | // Removing an element 104 | treeSet.remove(20); 105 | System.out.println("Elements of TreeSet after removing 20: " + treeSet); 106 | 107 | // Checking if an element exists 108 | boolean contains30 = treeSet.contains(30); 109 | System.out.println("TreeSet contains 30: " + contains30); 110 | 111 | // Getting the first and last elements 112 | System.out.println("First element of TreeSet: " + ((TreeSet) treeSet).first()); 113 | System.out.println("Last element of TreeSet: " + ((TreeSet) treeSet).last()); 114 | } 115 | } 116 | 117 | // Class demonstrating LinkedHashSet implementation of Set interface 118 | class LinkedHashSetExample implements SetInterfaceExample { 119 | @Override 120 | public void demonstrateSet() { 121 | // Creating a LinkedHashSet 122 | Set linkedHashSet = new LinkedHashSet<>(); 123 | 124 | // Adding elements to the LinkedHashSet 125 | linkedHashSet.add('A'); 126 | linkedHashSet.add('B'); 127 | linkedHashSet.add('C'); 128 | 129 | // Accessing elements 130 | System.out.println("Elements of LinkedHashSet:"); 131 | for (char letter : linkedHashSet) { 132 | System.out.println(letter); 133 | } 134 | 135 | // Getting the size of the LinkedHashSet 136 | System.out.println("Size of LinkedHashSet: " + linkedHashSet.size()); 137 | 138 | // Removing an element 139 | linkedHashSet.remove('B'); 140 | System.out.println("Elements of LinkedHashSet after removing 'B': " + linkedHashSet); 141 | 142 | // Checking if an element exists 143 | boolean containsA = linkedHashSet.contains('A'); 144 | System.out.println("LinkedHashSet contains 'A': " + containsA); 145 | } 146 | } 147 | 148 | // Main class to demonstrate Set interface and its implementations 149 | public class Collection_Set_Interface { 150 | public static void main(String[] args) { 151 | // Demonstrating HashSet 152 | SetInterfaceExample hashSetExample = new HashSetExample(); 153 | System.out.println("HashSet Example:"); 154 | hashSetExample.demonstrateSet(); 155 | System.out.println(); 156 | 157 | System.out.println("-----------------------------------------------------------------"); 158 | 159 | // Demonstrating TreeSet 160 | SetInterfaceExample treeSetExample = new TreeSetExample(); 161 | System.out.println("TreeSet Example:"); 162 | treeSetExample.demonstrateSet(); 163 | System.out.println(); 164 | 165 | System.out.println("-----------------------------------------------------------------"); 166 | 167 | // Demonstrating LinkedHashSet 168 | SetInterfaceExample linkedHashSetExample = new LinkedHashSetExample(); 169 | System.out.println("LinkedHashSet Example:"); 170 | linkedHashSetExample.demonstrateSet(); 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /Java_Concepts/Collection/Comparable_vs_Comparator.java: -------------------------------------------------------------------------------- 1 | // Sorting: Comparable_vs_Comparator 2 | /* 3 | Comparable provides a way for objects of a class to define their natural ordering, 4 | while Comparator allows for custom sorting logic to be applied externally to objects of a class 5 | 6 | Comparable Interface: 7 | - Comparable is an interface in Java that defines a single method compareTo(). 8 | - It allows objects of a class to be sorted automatically based on their natural ordering. 9 | - The class whose objects need to be sorted must implement the Comparable interface and override the compareTo() method to define the natural ordering of its objects. 10 | - The compareTo() method returns a negative integer, zero, or a positive integer if the current object is less than, equal to, or greater than the specified object, respectively. 11 | - The natural ordering is defined by the class itself, which means the sorting logic is embedded within the class. 12 | - Examples of classes that implement Comparable include String, Integer, and other wrapper classes. 13 | 14 | Comparator Interface: 15 | - Comparator is a functional interface in Java that defines a single method compare(). 16 | - It provides an external comparison logic separate from the class whose objects need to be sorted. 17 | - Classes that implement Comparator can define multiple comparison strategies. 18 | - Comparator objects can be passed to sorting methods to customize the sorting order. 19 | - Comparator is useful when: 20 | - Sorting objects of classes that do not implement Comparable. 21 | - Customizing the sorting order of classes that do implement Comparable. 22 | - Comparator allows for flexibility in sorting logic without modifying the class being sorted. 23 | - Comparator objects can be used for sorting, searching, and other operations. 24 | - Examples of classes that use Comparator for sorting include Collections.sort(), Arrays.sort(), etc. 25 | */ 26 | 27 | import java.util.*; 28 | 29 | // Class representing a Book 30 | class Book implements Comparable { 31 | private String title; 32 | private int pageCount; 33 | 34 | public Book(String title, int pageCount) { 35 | this.title = title; 36 | this.pageCount = pageCount; 37 | } 38 | 39 | public String getTitle() { 40 | return title; 41 | } 42 | 43 | public int getPageCount() { 44 | return pageCount; 45 | } 46 | 47 | // Implementing Comparable interface to define natural ordering based on pageCount 48 | @Override 49 | public int compareTo(Book other) { 50 | return this.pageCount - other.pageCount; 51 | } 52 | 53 | // Overriding toString() for better output representation 54 | @Override 55 | public String toString() { 56 | return "Book{title='" + title + "', pageCount=" + pageCount + "}"; 57 | } 58 | } 59 | 60 | // Comparator for sorting books based on title 61 | class TitleComparator implements Comparator { 62 | @Override 63 | public int compare(Book b1, Book b2) { 64 | return b1.getTitle().compareTo(b2.getTitle()); // return 1:swap, -1:UnSwap 65 | } 66 | } 67 | 68 | public class Comparable_vs_Comparator { 69 | public static void main(String[] args) { 70 | // Creating a list of books 71 | List books = new ArrayList<>(); 72 | books.add(new Book("Java Programming", 500)); 73 | books.add(new Book("Python Basics", 400)); 74 | books.add(new Book("C++ Essentials", 350)); 75 | 76 | // Sorting books based on natural ordering (pageCount) 77 | System.out.println("Books sorted by pageCount (natural ordering):"); 78 | Collections.sort(books); 79 | for (Book book : books) { 80 | System.out.println(book); 81 | } 82 | 83 | // Sorting books based on title using Comparator 84 | System.out.println("\nBooks sorted by title:"); 85 | Collections.sort(books, new TitleComparator()); 86 | for (Book book : books) { 87 | System.out.println(book); 88 | } 89 | } 90 | } 91 | 92 | /* 93 | The Book class implements the Comparable interface to define natural ordering based on the number of pages (pageCount). 94 | The TitleComparator class implements the Comparator interface to define a custom sorting order based on the book titles. 95 | In the main method, we create a list of Book objects and demonstrate sorting using both natural ordering and the custom comparator. 96 | */ 97 | -------------------------------------------------------------------------------- /Java_Concepts/DSA/Algorithm_BinarySearch.java: -------------------------------------------------------------------------------- 1 | // Binary search 2 | /* 3 | Binary search is a widely-used algorithm for finding a target value within a sorted array. 4 | It works by repeatedly dividing the search interval in half. 5 | 6 | Algorithm: 7 | 1. Binary search starts by examining the middle element of the sorted array. 8 | 2. If the middle element is equal to the target value, the search is successful, and the index of the target is returned. 9 | 3. If the middle element is greater than the target value, the search continues on the left half of the array. 10 | 4. If the middle element is less than the target value, the search continues on the right half of the array. 11 | 5. The process repeats until the target value is found or the search interval becomes empty. 12 | 13 | Implementation: 14 | Binary search can be implemented iteratively or recursively. 15 | 16 | Iterative approach: 17 | public int binarySearch(int[] arr, int target) { 18 | int left = 0; 19 | int right = arr.length - 1; 20 | while (left <= right) { 21 | int mid = left + (right - left) / 2; 22 | if (arr[mid] == target) { 23 | return mid; // Found the target 24 | } else if (arr[mid] < target) { 25 | left = mid + 1; // Search in the right half 26 | } else { 27 | right = mid - 1; // Search in the left half 28 | } 29 | } 30 | return -1; // Target not found 31 | } 32 | 33 | Recursive approach: 34 | public int binarySearch(int[] arr, int target, int left, int right) { 35 | if (left <= right) { 36 | int mid = left + (right - left) / 2; 37 | if (arr[mid] == target) { 38 | return mid; // Found the target 39 | } else if (arr[mid] < target) { 40 | return binarySearch(arr, target, mid + 1, right); // Search in the right half 41 | } else { 42 | return binarySearch(arr, target, left, mid - 1); // Search in the left half 43 | } 44 | } 45 | return -1; // Target not found 46 | } 47 | 48 | Time Complexity: 49 | Binary search has a time complexity of O(log n), where n is the number of elements in the array. 50 | This makes it significantly faster than linear search for large arrays, as the search space is halved in each step. 51 | 52 | Requirements: 53 | Binary search requires the array to be sorted in ascending order for it to work correctly. 54 | If the array is not sorted, the results of binary search will be unpredictable. 55 | 56 | Usage: 57 | Binary search is commonly used in scenarios where fast searching in sorted arrays is required, such as searching in dictionaries, phonebooks, or databases. 58 | 59 | */ 60 | 61 | // Code: 62 | 63 | /* 64 | The Arrays.binarySearch() method in Java is a utility method provided in the java.util.Arrays class. 65 | It performs a binary search on a sorted array to find the index of a specified target element efficiently. 66 | 67 | Syntax: 68 | public static int binarySearch(int[] a, int key) 69 | 70 | Parameters: 71 | a: The sorted array to be searched. 72 | key: The value to be searched for in the array. 73 | 74 | Return Value: 75 | If the key value is found in the array, the method returns the index of the matching element. 76 | If the key value is not found in the array, the method returns a 'negative value', which is the insertion point (index where the key would be inserted to maintain the sorted order). 77 | */ 78 | 79 | import java.util.Arrays; 80 | 81 | public class Algorithm_BinarySearch { 82 | 83 | public static void main(String[] args) { 84 | int[] sortedArray = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; 85 | int target = 13; 86 | 87 | // Using Arrays.binarySearch() method 88 | int index = Arrays.binarySearch(sortedArray, target); 89 | 90 | if (index >= 0) { 91 | System.out.println("Element " + target + " found at index " + index); 92 | } else { 93 | System.out.println("Element " + target + " not found in the array"); 94 | } 95 | 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Java_Concepts/Interface/InterfaceConcept.java: -------------------------------------------------------------------------------- 1 | // Interface 2 | /* 3 | In Java, An interface in Java is a blueprint of a class. 4 | It can have only static constants and abstract methods. 5 | 6 | Definition: 7 | -An interface in Java is declared using the interface keyword. 8 | -It defines a set of methods that a class must implement. 9 | -It is a blueprint of a class, but unlike classes, interfaces cannot be instantiated. 10 | -An interface can also include constants, default methods, static methods, and nested types. 11 | 12 | Purpose: 13 | -Encapsulation: Interfaces allow you to define a contract for behavior without exposing the implementation details. 14 | -Abstraction: They help in achieving abstraction by separating the definition of a method from its implementation. 15 | -Polymorphism: Interfaces facilitate polymorphism, allowing objects of different classes to be treated interchangeably if they implement the same interface. 16 | 17 | Implementation: 18 | -A class implements an interface using the 'implements' keyword. 19 | -A class can implement multiple interfaces, separated by commas. 20 | -When a class implements an interface, it must provide concrete implementations for all the methods declared in the interface. 21 | 22 | Abstract Methods: 23 | -An abstract method in an interface does not have a method body. It only provides a method signature (name, parameters, return type). 24 | -All methods declared in an interface are implicitly public and abstract (except for static and default methods introduced in Java 8). 25 | 26 | Default Methods: 27 | -Default methods were introduced in Java 8 to provide a way to add new methods to interfaces without breaking existing implementations. 28 | -A default method in an interface has a method body and is declared using the default keyword. 29 | -Default methods are used to provide a default implementation that can be overridden by implementing classes. 30 | 31 | Static Methods: 32 | -Static methods in interfaces were introduced in Java 8 to provide utility methods that are not tied to specific instances of implementing classes. 33 | -They are declared using the static keyword and can be invoked using the interface name. 34 | 35 | Constant Variables: 36 | -Interfaces can contain constant variables, which are implicitly public, static, and final. 37 | -Constant variables must be initialized with a value, and their values cannot be changed once assigned. 38 | 39 | Multiple Inheritance: 40 | -Java does not support multiple inheritance of classes, but it allows multiple inheritance of interfaces. 41 | -A class can implement multiple interfaces, inheriting the abstract methods and default implementations from all of them. 42 | 43 | Polymorphism: 44 | -Interfaces enable polymorphism in Java, allowing objects of different classes to be treated uniformly based on the interface they implement. 45 | -This promotes "loose coupling(Independency)" and flexibility in software design. 46 | --- 47 | Class-Class: extends 48 | Class-Interface: implements 49 | Interface-Interface: extends 50 | */ 51 | 52 | // Interface with abstract method 53 | interface Ic_Animal { 54 | void sound(); // Abstract method 55 | } 56 | 57 | // Interface with default method 58 | interface Ic_Walkable { 59 | default void walk() { 60 | System.out.println("Walking"); 61 | } 62 | } 63 | 64 | // Interface with static method 65 | interface Ic_Jumpable { 66 | static void jump() { 67 | System.out.println("Jumping"); 68 | } 69 | } 70 | 71 | // Interface with constant variable 72 | interface Ic_Constants { 73 | String MESSAGE = "Hello, Interfaces!"; // Constant variable 74 | } 75 | 76 | // Class implementing interfaces 77 | class Dog implements Ic_Animal, Ic_Walkable { 78 | @Override 79 | public void sound() { 80 | System.out.println("Dog barks"); 81 | } 82 | } 83 | 84 | public class InterfaceConcept { 85 | public static void main(String[] args) { 86 | // Implementing interface with abstract method 87 | Ic_Animal dog = new Dog(); 88 | dog.sound(); // Output: Dog barks 89 | 90 | // Implementing interface with default method 91 | Ic_Walkable walker = new Dog(); 92 | walker.walk(); // Output: Walking 93 | 94 | // Implementing interface with static method directly 95 | Ic_Jumpable.jump(); // Output: Jumping 96 | 97 | // Accessing constant variable from interface directly 98 | System.out.println(Ic_Constants.MESSAGE); // Output: Hello, Interfaces! 99 | } 100 | } 101 | 102 | /* 103 | We define four interfaces: Ic_Animal, Ic_Walkable, Ic_Jumpable, and Ic_Constants, each illustrating a different aspect of interfaces 104 | (abstract method, default method, static method, and constant variable). 105 | We implement the Animal interface in the Dog class, providing an implementation for the sound() method. 106 | In the main class InterfaceConcept, we demonstrate: 107 | Implementing the Animal interface with the Dog class and calling the sound() method. 108 | Implementing the Walkable interface with the Dog class and calling the walk() default method. 109 | Calling the jump() static method from the Jumpable interface 'directly'. 110 | Accessing the constant variable MESSAGE from the Constants interface. 111 | */ 112 | -------------------------------------------------------------------------------- /Java_Concepts/Interface/InterfaceTypes.java: -------------------------------------------------------------------------------- 1 | //Type of interface 2 | /* 3 | 1) Normal Interface: 4 | -Normal interfaces in Java are the most common type of interfaces. 5 | -They can contain any number of abstract methods, default methods, static methods, and constant variables. 6 | -Normal interfaces are used to define a set of methods that classes must implement. 7 | -Implementing classes provide concrete implementations for all abstract methods defined in the interface. 8 | -Normal interfaces can also include default methods and static methods, providing flexibility in interface design. 9 | 10 | 2) Functional Interface: 11 | -A functional interface is an interface that contains exactly one abstract method. 12 | -Java 8 introduced functional interfaces to support lambda expressions and method references, which provide a concise way to represent anonymous functions. 13 | -Functional interfaces can also contain default methods and static methods, as long as they have only one abstract method. 14 | -The '@FunctionalInterface' annotation is used to indicate that an interface is intended to be a functional interface. 15 | -Examples of functional interfaces include Runnable, Comparator, and Callable. 16 | 17 | Lambda expressions: 18 | 19 | Lambda expressions are a feature introduced in Java 8 that allow you to treat functionality as a method argument, or to create an anonymous function, which can be passed around your code. 20 | Syntax: 21 | -Lambda expressions consist of parameters, an arrow (->), and a body. 22 | -The body can be a single expression or a block of code. 23 | Functional Interfaces: 24 | -Lambda expressions are used primarily in the context of functional interfaces, which are interfaces that contain exactly one abstract method. 25 | -The lambda expression provides an implementation for this single abstract method. 26 | Example: 27 | // 28 | Runnable runnable = () -> { 29 | System.out.println("This is a lambda expression"); 30 | }; 31 | // 32 | Limitations: 33 | -Lambda expressions can only be used with functional interfaces, i.e., interfaces with exactly one abstract method. 34 | -They cannot access non-final local variables from the enclosing scope unless those variables are effectively final. 35 | 36 | 3) Marker Interface: 37 | -Marker interfaces are interfaces with no methods or constants. 38 | -They are used to mark or tag classes to provide some specific behavior or capability. 39 | -Marker interfaces serve as a way for the Java runtime environment or other frameworks to identify classes that implement them and provide specialized behavior accordingly. 40 | -Classes implementing marker interfaces inherit some behavior or functionality defined by the interface. 41 | -Examples of marker interfaces include Serializable, Cloneable, and Remote. 42 | 43 | In summary, normal interfaces are the standard interfaces that define a set of methods for classes to implement, functional interfaces contain exactly one abstract method and support lambda expressions, and marker interfaces are used to tag classes to provide specialized behavior. 44 | */ 45 | 46 | // Normal interface 47 | interface NormalInterfaceDemo { 48 | // Abstract method 49 | void method1(); 50 | 51 | // Default method 52 | default void defaultMethod() { 53 | System.out.println("Default method in NormalInterface"); 54 | } 55 | 56 | // Static method 57 | static void staticMethod() { 58 | System.out.println("Static method in NormalInterface"); 59 | } 60 | } 61 | 62 | // Functional interface 63 | @FunctionalInterface 64 | interface FunctionalInterfaceDemo { 65 | // Abstract method (only one) 66 | void method(); 67 | } 68 | 69 | // Marker interface 70 | interface MarkerInterface { 71 | // No methods or constants 72 | } 73 | 74 | // Implementation of NormalInterface 75 | class NormalImplementation implements NormalInterfaceDemo { 76 | @Override 77 | public void method1() { 78 | System.out.println("Implementation of method1 in NormalInterface"); 79 | } 80 | } 81 | 82 | public class InterfaceTypes { 83 | public static void main(String[] args) { 84 | // Normal interface usage 85 | NormalImplementation normalImplementation = new NormalImplementation(); 86 | normalImplementation.method1(); // Output: Implementation of method1 in NormalInterface 87 | normalImplementation.defaultMethod(); // Output: Default method in NormalInterface 88 | NormalInterfaceDemo.staticMethod(); // Output: Static method in NormalInterface 89 | 90 | // Functional interface usage (implemented with lambda expression) 91 | FunctionalInterfaceDemo functionalInterface = () -> { 92 | System.out.println("Implementation of method in FunctionalInterface"); 93 | }; 94 | functionalInterface.method(); // Output: Implementation of method in FunctionalInterface 95 | 96 | // Marker interface usage 97 | if (MarkerInterface.class.isAssignableFrom(NormalImplementation.class)) { 98 | System.out.println("NormalImplementation implements MarkerInterface"); 99 | } else { 100 | System.out.println("NormalImplementation does not implement MarkerInterface"); 101 | } 102 | } 103 | } 104 | 105 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/DateClass.java: -------------------------------------------------------------------------------- 1 | import java.util.Date; 2 | import java.text.SimpleDateFormat; 3 | 4 | public class DateClass { 5 | public static void main(String a[]){ 6 | Date today1 = new Date(); 7 | SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy HH:mm:ss"); 8 | 9 | String formattedDateOutput1 = formatter.format(today1); 10 | System.out.println(formattedDateOutput1); 11 | 12 | // New 2nd date 13 | // Date today2 = new Date(); 14 | Date today2 = new Date(1550000000L); 15 | 16 | String formattedDateOutput2 = formatter.format(today2); 17 | System.out.println(formattedDateOutput2); 18 | 19 | // Compare dates(after/before) 20 | boolean isAfter = today1.after(today2); 21 | System.out.println(isAfter); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/FinalKeyword.java: -------------------------------------------------------------------------------- 1 | // final keyword 2 | /* 3 | The final keyword in Java is used to restrict the user from modifying the variable, method, or class it is applied to. 4 | 5 | Final Variables: 6 | -When applied to a variable, it means that the variable's value cannot be changed once it has been assigned. 7 | -Final variables must be initialized either at the time of declaration or in the constructor. 8 | -Once initialized, any attempt to reassign a value to a final variable will result in a compilation error. 9 | 10 | Final Methods: 11 | -When applied to a method, it means that the method cannot be overridden by subclasses. 12 | -Final methods are useful when you want to prevent subclasses from changing the behavior of a method. 13 | 14 | Final Classes: 15 | -When applied to a class, it means that the class cannot be subclassed. 16 | -Final classes are often used to create immutable classes or utility classes that should not be extended. 17 | */ 18 | 19 | 20 | // Class with final variable, method, and class 21 | public class FinalKeyword { 22 | 23 | // Final variable 24 | final int FINAL_NUMBER = 10; 25 | 26 | // Final method 27 | final void display() { 28 | System.out.println("Inside final method"); 29 | } 30 | 31 | // Final class 32 | final class FinalClass { 33 | // Class implementation 34 | } 35 | 36 | // Main method to demonstrate usage 37 | public static void main(String[] args) { 38 | // Create an instance of FinalKeyword class 39 | FinalKeyword obj = new FinalKeyword(); 40 | 41 | // Access final variable 42 | System.out.println("Final number: " + obj.FINAL_NUMBER); 43 | 44 | // Call final method 45 | obj.display(); 46 | 47 | // Attempt to extend final class 48 | // Compilation error: Cannot subclass final class 49 | // class SubClass extends FinalClass {} 50 | } 51 | } 52 | 53 | /* 54 | The FINAL_NUMBER variable is declared as final, indicating that its value cannot be changed after initialization. 55 | The display method is declared as final, preventing subclasses from overriding it. 56 | The FinalClass is declared as final, meaning it cannot be subclassed. 57 | */ 58 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/OopsConcepts.java: -------------------------------------------------------------------------------- 1 | // Object-oriented programming (OOP) 2 | /* 3 | Object-oriented programming (OOP) is a programming paradigm that revolves around the concept of objects, which are instances of classes. 4 | In Java, OOP is fundamental, and it encompasses several key concepts 5 | 1. Classes and Objects: 6 | - Class: A blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) that objects of the class will have. 7 | - Object: An instance of a class. It encapsulates data and behaviors defined by its class. 8 | 9 | 2. Encapsulation: 10 | - Encapsulation is the bundling of data (attributes) and methods (behaviors) that operate on the data into a single unit (class). 11 | - It hides the internal state of objects and only allows access through well-defined interfaces (public methods), thereby protecting the integrity of the data. 12 | 13 | 3. Inheritance: 14 | - Inheritance is a mechanism where a class (subclass) can inherit properties and behaviors from another class (superclass). 15 | - It promotes code reusability and establishes an "is-a" relationship between classes. 16 | 17 | 4. Polymorphism: 18 | - Polymorphism allows objects to be treated as instances of their superclass. 19 | - It enables methods to be implemented in various ways in different subclasses. 20 | - Types of polymorphism: 21 | - Compile-time (Static) Polymorphism: Method overloading 22 | - Runtime (Dynamic) Polymorphism: Method overriding 23 | 24 | 5. Abstraction: 25 | - Abstraction is the process of hiding the complex implementation details and showing only the essential features of an object. 26 | - It focuses on what an object does rather than how it achieves it. 27 | - Abstract classes and interfaces are used to achieve abstraction in Java. 28 | 29 | 6. Association, Aggregation, and Composition: 30 | - Association: Represents a relationship between two or more classes. 31 | - Aggregation: Represents a "has-a" relationship where one class contains references to another class. 32 | - Composition: Represents a strong form of aggregation where the lifecycle of the contained object is managed by the container. 33 | 34 | 7. Access Modifiers: 35 | - Access modifiers control the visibility and accessibility of classes, methods, and variables. 36 | - Types of access modifiers in Java: 37 | - Public: Accessible from anywhere. 38 | - Protected: Accessible within the same package or subclass. 39 | - Default (Package-private): Accessible only within the same package. 40 | - Private: Accessible only within the same class. 41 | 42 | 8. Constructor and Destructor: 43 | - Constructor: A special method used to initialize objects of a class. It has the same name as the class and is called when an object is created. 44 | - Destructor: Java does not have explicit destructors like some other languages. Garbage collection automatically deallocates memory when an object is no longer referenced. 45 | 46 | 9. Method Overriding and Overloading: 47 | - Method Overriding: Allows a subclass to provide a specific implementation of a method that is already defined in its superclass. 48 | - Method Overloading: Allows multiple methods with the same name but different parameters in the same class. 49 | 50 | 10. Final Keyword: 51 | - The final keyword can be applied to classes, methods, and variables. 52 | - A final class cannot be subclassed, a final method cannot be overridden, and a final variable cannot be reassigned. 53 | 54 | */ 55 | 56 | 57 | 58 | // Encapsulation: Using private access modifiers to encapsulate data 59 | class Oops_Person { 60 | private String name; 61 | private int age; 62 | 63 | // Constructor: Initializing object state during instantiation 64 | public Oops_Person(String name, int age) { 65 | this.name = name; 66 | this.age = age; 67 | } 68 | 69 | // Getter methods: Allowing controlled access to private data 70 | public String getName() { 71 | return name; 72 | } 73 | 74 | public int getAge() { 75 | return age; 76 | } 77 | 78 | // Inheritance: Creating a subclass that extends the Oops_Person class 79 | static class Oops_Student extends Oops_Person { 80 | // Constructor of subclass 81 | public Oops_Student(String name, int age) { 82 | super(name, age); // Calling superclass constructor 83 | } 84 | 85 | // Method Overriding: Providing a specific implementation of a method from superclass 86 | @Override 87 | public String getName() { 88 | return "Student Name: " + super.getName(); // Calling superclass method 89 | } 90 | } 91 | 92 | // Main class containing the main method 93 | public static class OopsConcepts { 94 | // Polymorphism: Using superclass reference to refer to subclass object 95 | public static void main(String[] args) { 96 | Oops_Person person = new Oops_Person("Alice", 30); 97 | System.out.println("Name: " + person.getName() + ", Age: " + person.getAge()); 98 | 99 | Oops_Student student = new Oops_Student("Bob", 20); 100 | System.out.println(student.getName()); // Output: "Student Name: Bob" 101 | } 102 | } 103 | } 104 | 105 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/Oops_Abstraction.java: -------------------------------------------------------------------------------- 1 | // Abstraction 2 | /* 3 | Abstraction is a fundamental concept in object-oriented programming (OOP) that focuses on 4 | representing the essential features of an object while hiding the unnecessary details of its implementation. 5 | It allows developers to create models that mimic real-world entities by emphasizing what an object does rather than how it does it. 6 | In OOP, abstraction is implemented using abstract classes and interfaces. 7 | 1. Abstract Classes: 8 | - An abstract class is a class that cannot be instantiated directly but can be subclassed. 9 | - It may contain abstract methods (methods without a body) that subclasses must implement. 10 | - Abstract classes can also have concrete methods with implementations. 11 | - They serve as a blueprint for other classes and are used to define common behavior shared by multiple subclasses. 12 | 13 | 2. Interfaces: 14 | - An interface is a reference type in Java that defines a set of abstract methods. 15 | - Like abstract classes, interfaces cannot be instantiated directly. 16 | - Classes can implement one or more interfaces, inheriting the abstract methods declared in those interfaces. 17 | - Interfaces are used to achieve multiple inheritance of type and to provide a contract for classes to adhere to. 18 | 19 | 3. Encapsulation: 20 | - Encapsulation is closely related to abstraction and involves bundling the data (attributes) and methods (behaviors) that operate on the data into a single unit (a class). 21 | - It hides the internal state of objects and exposes only the necessary functionality through methods, thus promoting information hiding and modularity. 22 | */ 23 | /* 24 | 1. Abstract Keyword: 25 | -The abstract keyword is used to declare abstract classes and methods in Java. 26 | -Abstract classes cannot be instantiated directly and may contain both abstract and concrete methods. 27 | -Abstract methods are declared without implementation and must be overridden by subclasses. 28 | 29 | 2. Abstract Classes with Abstract Methods: 30 | - Abstract classes are classes that cannot be instantiated and may contain abstract methods(only declarations). 31 | - Abstract methods are declared without implementation and must be overridden by subclasses. 32 | - Abstract methods only belongs to abstract classes. 33 | - We can't create a object of abstract class, only can create reference of abstract class. 34 | - They are used to define a common interface for a group of related subclasses. 35 | - Example: 36 | ```java 37 | abstract class AbstractClass { 38 | abstract void abstractMethod(); 39 | } 40 | ``` 41 | 42 | 3. Concrete Class with Inner Classes: 43 | - Concrete Class are used to define all the abstract methods in the abstract class. Concrete class always extends abstract class. 44 | - Its Compulsory to define all the declared abstract methods, if it not use all of it, then that class will also becomes an abstract, so then we need new Concrete class. 45 | - Inner classes are classes defined within another class. 46 | - They can access members of the outer class, including private members. 47 | - Inner classes can be of different types: static inner class, non-static inner class (also known as nested class), local inner class, and anonymous inner class. 48 | - Example: 49 | ```java 50 | class ConcreteClass { 51 | // Inner class 52 | class InnerClass { 53 | // Inner class method 54 | void display() { 55 | System.out.println("Inner class method"); 56 | } 57 | } 58 | } 59 | ``` 60 | 61 | 4. Anonymous Inner Classes: 62 | - Anonymous inner classes are inner classes without a name that are declared and instantiated at the same time. 63 | - They are typically used for one-time use cases, such as event handling or implementing interfaces. 64 | - They can access members of the enclosing class as well as local variables of the enclosing method (if declared final or effectively final). 65 | - Example: 66 | ```java 67 | interface HelloWorld { 68 | void greet(); 69 | } 70 | 71 | class Main { 72 | public static void main(String[] args) { 73 | HelloWorld hello = new HelloWorld() { 74 | public void greet() { 75 | System.out.println("Hello, World!"); 76 | } 77 | }; 78 | hello.greet(); 79 | } 80 | } 81 | ``` 82 | 83 | 5. Abstract Classes with Anonymous Inner Classes: 84 | - Anonymous inner classes allow you to quickly and directly implement abstract methods as needed, without the need to create separate named classes beforehand. 85 | - They allow defining the implementation of abstract methods without explicitly creating a subclass. 86 | - They are useful when a simple, one-time implementation is needed. 87 | - Example: 88 | ```java 89 | abstract class AbstractClass { 90 | abstract void abstractMethod(); 91 | } 92 | 93 | class Main { 94 | public static void main(String[] args) { 95 | AbstractClass obj = new AbstractClass() { 96 | void abstractMethod() { 97 | System.out.println("Implemented abstract method"); 98 | } 99 | }; 100 | obj.abstractMethod(); 101 | } 102 | } 103 | ``` 104 | */ 105 | 106 | 107 | // Abstract class with abstract method 108 | abstract class AbstractClass { 109 | abstract void abstractMethod(); //only declaration in abstract class 110 | } 111 | 112 | // Concrete class implementing abstract method 113 | class ConcreteClass extends AbstractClass { 114 | // Implementing abstract method 115 | void abstractMethod() { 116 | System.out.println("Abstract method implemented in ConcreteClass"); 117 | } 118 | 119 | // Inner class 120 | class InnerClass { 121 | // Inner class method 122 | void display() { 123 | System.out.println("Inner class method"); 124 | } 125 | } 126 | } 127 | 128 | // Main class to demonstrate abstract classes, inner classes, and anonymous inner classes 129 | public class Oops_Abstraction { 130 | public static void main(String[] args) { 131 | // Concrete class instance 132 | ConcreteClass concrete = new ConcreteClass(); 133 | concrete.abstractMethod(); // Call concrete method 134 | 135 | // Inner class instance 136 | ConcreteClass.InnerClass inner = concrete.new InnerClass(); // To Access innerClass we need to mention OuterClass with '.' and assign with object of OuterClass with InnerClass 137 | inner.display(); // Call inner class method 138 | 139 | // Anonymous inner class implementing interface 140 | HelloWorld hello = new HelloWorld() { 141 | // Implementing interface method 142 | public void greet() { 143 | System.out.println("Hello from Anonymous inner class"); 144 | } 145 | }; 146 | hello.greet(); // Call interface method 147 | 148 | // Anonymous inner class extending abstract class 149 | AbstractClass obj = new AbstractClass() { 150 | // Implementing abstract method 151 | void abstractMethod() { 152 | System.out.println("Implemented abstract method by Anonymous inner class"); 153 | } 154 | }; 155 | obj.abstractMethod(); // Call abstract method 156 | } 157 | 158 | // Interface with one method 159 | interface HelloWorld { 160 | void greet(); 161 | } 162 | } 163 | 164 | 165 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/Oops_Encapsulation.java: -------------------------------------------------------------------------------- 1 | // Encapsulation 2 | /* 3 | Encapsulation is a fundamental concept in object-oriented programming (OOP) that combines data (attributes) and methods (behaviors) into a single unit called a class. 4 | It involves hiding the internal state of objects and only allowing access to the data through well-defined interfaces (methods). 5 | Encapsulation is crucial for achieving data abstraction, data hiding, and access control in OOP. 6 | 7 | 1)Data Hiding: 8 | - Encapsulation hides the internal state (data) of an object from the outside world. 9 | - Data members (attributes) of a class are typically declared as private, making them inaccessible from outside the class. 10 | 11 | 2)Access Modifiers: 12 | - Access modifiers control the visibility and accessibility of classes, methods, and variables in Java. 13 | - In encapsulation, data members are often marked as private to restrict direct access and modification. 14 | - Common access modifiers: 15 | - public: Accessible from anywhere. 16 | - private: Accessible only within the same class. 17 | - protected: Accessible within the same package or subclass. 18 | - Default (package-private): Accessible only within the same package. 19 | 20 | 3)Getter and Setter Methods: 21 | - Getter methods: Also known as accessor methods, they provide read-only access to private data members. 22 | - Setter methods: Also known as mutator methods, they provide write access to private data members and enable controlled modification of data. 23 | - Getter and setter methods encapsulate the access to private data, allowing controlled interaction with the object's state. 24 | 25 | 4)"this" keyword: 26 | -"this" keyword in Java refers to the current object instance within a class. 27 | -It is used to differentiate between instance variables and parameters or local variables with the same name. 28 | -Accessing instance variables or methods: this.variableName or this.methodName(). 29 | */ 30 | 31 | 32 | // Base class 33 | public class Oops_Encapsulation { 34 | public static void main(String[] args) { 35 | // Create an Employee object 36 | Employee emp = new Employee("Sanillu Bhai", 50000); 37 | 38 | // Access and modify data using public methods 39 | System.out.println("Employee Name: " + emp.getName()); 40 | System.out.println("Employee Salary: Rs." + emp.getSalary()); 41 | 42 | System.out.println("---------------"); 43 | 44 | emp.setName("Sanillu Sai"); 45 | emp.setSalary(60000); 46 | 47 | // Print updated data 48 | System.out.println("Updated Employee Name: " + emp.getName()); 49 | System.out.println("Updated Employee Salary: Rs." + emp.getSalary()); 50 | } 51 | } 52 | 53 | // Employee class with private data and public methods 54 | class Employee { 55 | // Private data members (attributes) 56 | private String name; 57 | private double salary; 58 | 59 | 60 | // Constructor to initialize data 61 | public Employee(String name, double salary) { 62 | this.name = name; 63 | this.salary = salary; 64 | } 65 | 66 | // Getter method to retrieve employee name 67 | public String getName() { 68 | return name; 69 | } 70 | 71 | // Setter method to update employee name 72 | public void setName(String name) { 73 | this.name = name; 74 | } 75 | 76 | // Getter method to retrieve employee salary 77 | public double getSalary() { 78 | return salary; 79 | } 80 | 81 | // Setter method to update employee salary 82 | public void setSalary(double salary) { 83 | if (salary >= 0) { // Ensure salary is non-negative 84 | this.salary = salary; 85 | } else { 86 | System.out.println("Invalid salary! Salary cannot be negative."); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/Oops_Inheritance.java: -------------------------------------------------------------------------------- 1 | // Oops_Inheritance 2 | /* 3 | Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class (subclass or derived class) 4 | to inherit properties and behavior (methods and fields) from an existing class (superclass or base class). 5 | In Inheritance , whenever we create a obj for any class, it will call its Constructor of subclass and suprclass. 6 | This enables code reuse, promotes modularity, and facilitates the creation of hierarchical relationships between classes. 7 | 8 | Key aspects of inheritance include: 9 | 1) Base Class (Superclass): 10 | -The base class is the existing class from which properties and behavior are inherited. 11 | -It serves as the template or blueprint for creating new classes. 12 | -It encapsulates common attributes and methods shared by its subclasses. 13 | 2) Derived Class (Subclass): 14 | -The derived class is the new class that inherits properties and behavior from the base class. 15 | -It extends or specializes the functionality of the base class by adding new features or overriding existing methods. 16 | -It can also define additional fields and methods specific to its requirements. 17 | Syntax: 18 | -In Java, inheritance is declared using the extends keyword. 19 | -Syntax: class SubclassName extends SuperclassName { ... } 20 | -The subclass inherits all non-private fields and methods from the superclass. 21 | 3) Access Modifiers: 22 | -Inherited members retain their original access modifiers (e.g., public, protected, or default). 23 | -Subclasses can access inherited members based on their visibility: 24 | -Public members are accessible to all classes. 25 | -Protected members are accessible within the same package and by subclasses. 26 | -Default (package-private) members are accessible within the same package only. 27 | 28 | 4) Types of Inheritance: 29 | ->1.Single Inheritance: 30 | A subclass inherits from only one superclass. 31 | ->2.Multilevel Inheritance: 32 | A subclass inherits from another subclass, creating a chain of inheritance. 33 | ->3.Hierarchical Inheritance: 34 | Multiple subclasses inherit from the same superclass. 35 | ->4.Multiple Inheritance (Not supported in Java): 36 | Multiple inheritance refers to a subclass inheriting from multiple superclasses. 37 | It can lead to the diamond problem and is not supported in Java, Will rise Ambiguity Problem. 38 | A subclass inherits from multiple superclasses. Java supports multiple inheritance through interfaces, where a class can implement multiple interfaces. 39 | ->5.Hybrid Inheritance (Combination of above types): 40 | Hybrid inheritance is a combination of two or more types of inheritance. 41 | It can include any combination of single, multilevel, hierarchical, or multiple inheritance (through interfaces). 42 | 43 | 5) Method Overriding: 44 | -Subclasses can override (redefine) methods inherited from the superclass to provide specialized implementations. 45 | -The method signature (name, parameters, and return type) must match the overridden method in the superclass. 46 | -Annotations such as @Override can be used to indicate that a method is intended to override a superclass method. 47 | 6) Super Keyword: 48 | -The super keyword is used to access members of the superclass from within the subclass. 49 | -It is used to invoke superclass constructors, methods, or access superclass fields that are hidden by the subclass. 50 | 51 | Inheritance promotes code reuse, enhances maintainability, and enables polymorphic behavior, where objects of different subclasses can be treated interchangeably based on their common superclass type. 52 | However, it's essential to design inheritance hierarchies carefully to ensure proper encapsulation, cohesion, and adherence to the "is-a" relationship between classes. 53 | */ 54 | 55 | 56 | // Base class (Superclass) 57 | class i_Animal { 58 | // Method in the superclass 59 | public void sound() { 60 | System.out.println("Animal makes a sound"); 61 | } 62 | } 63 | 64 | // Derived class (Subclass) 65 | class i_Dog extends i_Animal { 66 | // Method overridden in the subclass 67 | @Override 68 | public void sound() { 69 | System.out.println("Dog barks"); 70 | } 71 | 72 | // Additional method specific to i_Dog class 73 | public void wagTail() { 74 | System.out.println("Dog wags tail"); 75 | } 76 | } 77 | 78 | public class Oops_Inheritance { 79 | public static void main(String[] args) { 80 | // Create an object of subclass (i_Dog) 81 | i_Dog dog = new i_Dog(); 82 | 83 | // Call methods from the superclass and subclass 84 | dog.sound(); // Output: Dog barks (overridden method) 85 | dog.wagTail(); // Output: Dog wags tail (method specific to i_Dog class) 86 | 87 | // Create an object of the superclass (Animal) 88 | i_Animal animal = new i_Animal(); 89 | 90 | // Call method from the superclass 91 | animal.sound(); // Output: Animal makes a sound 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/Oops_Inheritance_Hierarchical.java: -------------------------------------------------------------------------------- 1 | //Hierarchical Inheritance 2 | /* 3 | In hierarchical inheritance, multiple subclasses inherit from the same superclass. 4 | It forms a tree-like structure where a single superclass has multiple subclasses. 5 | */ 6 | 7 | 8 | // Superclass 9 | class HI_Animal { 10 | void eat() { 11 | System.out.println("HI_Animal is eating"); 12 | } 13 | } 14 | 15 | // Subclass inheriting from HI_Animal 16 | class HI_Dog extends HI_Animal { 17 | void bark() { 18 | System.out.println("Dog is barking"); 19 | } 20 | } 21 | 22 | // Another subclass inheriting from HI_Animal 23 | class HI_Cat extends HI_Animal { 24 | void meow() { 25 | System.out.println("Cat is meowing"); 26 | } 27 | } 28 | 29 | // Main class 30 | public class Oops_Inheritance_Hierarchical { 31 | public static void main(String[] args) { 32 | HI_Dog dog = new HI_Dog(); 33 | dog.eat(); // Output: HI_Animal is eating 34 | dog.bark(); // Output: Dog is barking 35 | 36 | HI_Cat cat = new HI_Cat(); 37 | cat.eat(); // Output: HI_Animal is eating 38 | cat.meow(); // Output: Cat is meowing 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/Oops_Inheritance_Hybrid.java: -------------------------------------------------------------------------------- 1 | // OOPS_Hybrid inheritance 2 | /* 3 | Hybrid inheritance (a combination of different types of inheritance) can be achieved 4 | by using a combination of single, multilevel, and hierarchical inheritance. 5 | */ 6 | 7 | 8 | // Superclass 9 | class HYI_Animal { 10 | void eat() { 11 | System.out.println("HYI_Animal is eating"); 12 | } 13 | } 14 | 15 | // Subclass inheriting from HYI_Animal 16 | class HYI_Dog extends HYI_Animal { 17 | void bark() { 18 | System.out.println("HYI_Dog is barking"); 19 | } 20 | } 21 | 22 | // Another subclass inheriting from HYI_Animal 23 | class Cat extends HYI_Animal { 24 | void meow() { 25 | System.out.println("Cat is meowing"); 26 | } 27 | } 28 | 29 | // Subclass inheriting from Dog and Cat (Hybrid Inheritance) 30 | class HYI_DogCat extends HYI_Dog { 31 | void purr() { 32 | System.out.println("DogCat is purring"); 33 | } 34 | } 35 | 36 | // Main class 37 | public class Oops_Inheritance_Hybrid { 38 | public static void main(String[] args) { 39 | HYI_DogCat dogCat = new HYI_DogCat(); 40 | dogCat.eat(); // Output: HYI_Animal is eating (inherited from HYI_Animal) 41 | dogCat.bark(); // Output: HYI_Dog is barking (inherited from HYI_Dog) 42 | dogCat.purr(); // Output: DogCat is purring (specific to DogCat) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/Oops_Inheritance_MultiLevel.java: -------------------------------------------------------------------------------- 1 | // Multilevel Inheritance 2 | /* 3 | -In multilevel inheritance, a subclass inherits from another subclass, creating a chain of inheritance. 4 | -It forms a hierarchy of classes where each subclass inherits from its immediate superclass. 5 | */ 6 | 7 | 8 | // Superclass 9 | class MLI_Animal { 10 | void eat() { 11 | System.out.println("MLI_Animal is eating"); 12 | } 13 | } 14 | 15 | // Subclass inheriting from MLI_Animal 16 | class MLI_Dog extends MLI_Animal { 17 | void bark() { 18 | System.out.println("MLI_Dog is barking"); 19 | } 20 | } 21 | 22 | // Subclass inheriting from MLI_Dog 23 | class MLI_Labrador extends MLI_Dog { 24 | void color() { 25 | System.out.println("Labrador is golden"); 26 | } 27 | } 28 | 29 | // Main class 30 | public class Oops_Inheritance_MultiLevel { 31 | public static void main(String[] args) { 32 | MLI_Labrador labrador = new MLI_Labrador(); 33 | labrador.eat(); // Output: MLI_Animal is eating 34 | labrador.bark(); // Output: MLI_Dog is barking 35 | labrador.color(); // Output: Labrador is golden 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/Oops_Inheritance_Single.java: -------------------------------------------------------------------------------- 1 | // Single Inheritance 2 | /* 3 | -In single inheritance, a subclass inherits from only one superclass. 4 | -It forms a single chain of inheritance. 5 | -It is the most common type of inheritance. 6 | */ 7 | 8 | 9 | // Superclass 10 | class SI_Animal { 11 | void eat() { 12 | System.out.println("SI_Animal is eating"); 13 | } 14 | } 15 | 16 | // Subclass inheriting from SI_Animal 17 | class SI_Dog extends SI_Animal { 18 | void bark() { 19 | System.out.println("SI_Dog is barking"); 20 | } 21 | } 22 | 23 | // Main class 24 | public class Oops_Inheritance_Single { 25 | public static void main(String[] args) { 26 | SI_Dog dog = new SI_Dog(); 27 | dog.eat(); // Output: SI_Animal is eating 28 | dog.bark(); // Output: SI_Dog is barking 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/Oops_Polymorphism.java: -------------------------------------------------------------------------------- 1 | // Oops_Polymorphism 2 | /* 3 | Polymorphism - Poly(Many) , morphism(Behavior) 4 | Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. 5 | Polymorphism allows objects of different subclasses to be treated as objects of the superclass, promoting code reusability and flexibility. 6 | It facilitates dynamic method invocation, enabling a single interface to represent multiple underlying implementations. 7 | Polymorphism is achieved through method overloading and method overriding, providing different forms of the same method signature. 8 | Polymorphism allows objects to exhibit different behaviors based on their types or classes, enabling flexible and modular design in object-oriented programming. 9 | 10 | There are two main types of polymorphism in Java: compile-time polymorphism/Early Binding (method overloading) and runtime polymorphism/Late Binding (method overriding). 11 | 12 | 1) Compile-time Polymorphism (Method Overloading): 13 | -Method overloading allows multiple methods with the same name but different parameter lists in the same class. 14 | -The compiler determines which overloaded method to call based on the number and types of arguments provided at compile time. 15 | -Overloaded methods may have different return types, but the parameter lists must differ in the number, order, or types of parameters. 16 | 17 | 2) Runtime Polymorphism (Method Overriding): 18 | -Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. 19 | -It enables dynamic dispatch, where the method to be invoked is determined at runtime based on the actual object type rather than the reference type. 20 | -The overridden method in the subclass must have the same signature (name, parameter list, and return type) as the method in the superclass. 21 | 22 | Dynamic method dispatch: 23 | -Dynamic method dispatch is a key feature of runtime polymorphism in Java. 24 | -It refers to the process of determining which implementation of an overridden method to call at runtime based on the actual type of the object rather than the reference type. 25 | -This allows for flexible and dynamic method invocation, where the method called is determined dynamically during program execution. 26 | 27 | how dynamic method dispatch works: 28 | -Inheritance Hierarchy: Dynamic method dispatch involves a superclass and one or more subclasses. 29 | - The superclass contains a method that is overridden by one or more of its subclasses. 30 | -Method Override: Subclasses override a method from the superclass with their specific implementation. 31 | - The overridden method in the subclass has the same signature (name, parameter list, and return type) as the method in the superclass. 32 | -Object Creation: Objects of the subclass are created using references of the superclass. 33 | - This allows for polymorphic behavior, where objects of different subclasses can be treated as objects of the superclass. 34 | -Method Invocation: When a method is called on the superclass reference, the JVM determines the actual type of the object at runtime. 35 | -Dynamic Dispatch: The JVM then invokes the overridden method of the actual object type, rather than the reference type. This is known as dynamic method dispatch. 36 | 37 | */ 38 | 39 | // Oops_Polymorphism.java 40 | 41 | // Class to demonstrate compile-time polymorphism (method overloading) 42 | class CompileTimePolymorphism { 43 | // Method to add two integers 44 | int add(int a, int b) { 45 | return a + b; 46 | } 47 | 48 | // Method to add three integers 49 | int add(int a, int b, int c) { 50 | return a + b + c; 51 | } 52 | } 53 | 54 | // Class to demonstrate runtime polymorphism (dynamic method dispatch) 55 | class RuntimePolymorphism { 56 | // Base class method 57 | void display() { 58 | System.out.println("Inside Base class"); 59 | } 60 | } 61 | 62 | // Derived class overriding the base class method 63 | class Derived extends RuntimePolymorphism { 64 | // Overridden method 65 | @Override 66 | void display() { 67 | System.out.println("Inside Derived class"); 68 | } 69 | } 70 | 71 | // Oops_Polymorphism class to call methods from CompileTimePolymorphism and RuntimePolymorphism classes 72 | public class Oops_Polymorphism { 73 | public static void main(String[] args) { 74 | // Compile-time polymorphism (method overloading) 75 | CompileTimePolymorphism ctp = new CompileTimePolymorphism(); 76 | System.out.println("Result of adding two numbers: " + ctp.add(5, 7)); 77 | System.out.println("Result of adding three numbers: " + ctp.add(3, 6, 9)); 78 | 79 | // Runtime polymorphism (dynamic method dispatch) 80 | RuntimePolymorphism rp = new Derived(); // Upcasting - Creating a reference of SuperClass to object of SubClass 81 | rp.display(); // Calls the overridden method in Derived class 82 | } 83 | } 84 | 85 | /* 86 | CompileTimePolymorphism class: 87 | Contains two overloaded methods add to add two or three integers. 88 | RuntimePolymorphism class: 89 | Defines a base class method display that prints "Inside Base class". 90 | Derived class: 91 | Overrides the display method from the base class to print "Inside Derived class". 92 | Oops_Polymorphism class (main): 93 | Creates an object of CompileTimePolymorphism and demonstrates method overloading by calling the add methods. 94 | Creates a reference of RuntimePolymorphism to an object of Derived class, demonstrating runtime polymorphism by calling the overridden display method. 95 | */ -------------------------------------------------------------------------------- /Java_Concepts/OOPS/Overloading_vs_OverRiding.java: -------------------------------------------------------------------------------- 1 | // Overloading vs Overriding 2 | /* 3 | Overloading: 4 | - Overloading occurs when multiple methods in the same class have the same name but different parameters. 5 | - It allows methods to perform similar tasks with different inputs. 6 | - Methods with different signatures can coexist in the same class, distinguished by the number or types of parameters. 7 | - Overloading is resolved at compile time based on the method signature. 8 | - Example: Having multiple constructors in a class with different parameter lists. 9 | 10 | Overriding: 11 | - Overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. 12 | - It allows subclasses to provide their own behavior for inherited methods. 13 | - The subclass method must have the same name, parameters, and return type as the superclass method. 14 | - Overriding is resolved at runtime based on the actual object type. 15 | - Example: Providing a different implementation for the `toString` method in a subclass. 16 | 17 | Differences: 18 | - Overloading is resolved at compile time based on method signature, while overriding is resolved at runtime based on object type. 19 | - Overloading involves multiple methods with the same name but different parameters, while overriding involves a method in a subclass with the same signature as a method in its superclass. 20 | - Overloading is used to provide multiple methods for performing similar tasks with different inputs, while overriding is used to provide a specific implementation for inherited methods. 21 | 22 | */ 23 | 24 | 25 | // Base class 26 | class OO_Animal { 27 | // Method overloading in the superclass 28 | void makeSound() { 29 | System.out.println("Animal makes a sound"); 30 | } 31 | 32 | // Method overloading with a parameter 33 | void makeSound(String sound) { 34 | System.out.println("Animal makes " + sound); 35 | } 36 | } 37 | 38 | // Subclass inheriting from Animal 39 | class OO_Dog extends OO_Animal { 40 | // Method overriding in the subclass 41 | @Override 42 | void makeSound() { 43 | System.out.println("Dog barks"); 44 | } 45 | 46 | // Method overloading in the subclass 47 | void makeSound(int count) { 48 | for (int i = 0; i < count; i++) { 49 | System.out.println("Dog barks"); 50 | } 51 | } 52 | } 53 | 54 | // Main class 55 | public class Overloading_vs_OverRiding { 56 | public static void main(String[] args) { 57 | OO_Animal animal = new OO_Animal(); 58 | animal.makeSound(); // Output: Animal makes a sound 59 | animal.makeSound("woof"); // Output: Animal makes woof 60 | 61 | System.out.println("-----------"); 62 | 63 | OO_Dog dog = new OO_Dog(); 64 | dog.makeSound(); // Output: Dog barks (overridden method) 65 | dog.makeSound(3); // Output: Dog barks (overloaded method, 3 times) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/StreamConcept.java: -------------------------------------------------------------------------------- 1 | // Stream API 2 | /* 3 | 1. Introduction to Streams: 4 | - Streams represent a sequence of elements that support aggregate operations on collections, such as filtering, mapping, and reducing. 5 | - They do not modify the original data source; instead, they allow operations to be performed on the elements of the source data.One stream can only used once, to use them first we need need assign to new stream and operate it. 6 | - Unlike collections, streams do not store elements; they provide a way to process elements from a source (e.g., a collection, array, or I/O channel) on-demand. 7 | 8 | 2. Creating Streams: 9 | - Streams can be created from various sources, including collections, arrays, I/O channels, and generator functions. 10 | - Common methods to create streams include stream() and parallelStream() for collections, Arrays.stream() for arrays, and Files.lines() for I/O channels. 11 | 12 | 3. Intermediate and Terminal Operations: 13 | - Stream operations are categorized into intermediate and terminal operations: 14 | a. Intermediate operations: These operations transform the stream into another stream, allowing for filtering, mapping, sorting, etc. Examples include filter(), map(), sorted(), etc. 15 | b. Terminal operations: These operations produce a result or side-effect and terminate the stream. Examples include forEach(), collect(), reduce(), etc. 16 | 17 | 4. Stream Pipeline: 18 | - Stream operations can be combined to form a stream pipeline, where the result of one operation is passed as input to the next operation. 19 | - Stream pipelines typically consist of zero or more intermediate operations followed by a terminal operation. 20 | 21 | 5. Lazy Evaluation: 22 | - Streams use lazy evaluation, meaning intermediate operations are not evaluated until a terminal operation is invoked. 23 | - Lazy evaluation allows for optimized processing, as only elements that are necessary for the result are computed. 24 | 25 | 6. Parallel Streams: 26 | - Streams can be processed sequentially or in parallel, depending on the source and requirements. 27 | - Parallel streams leverage multiple threads to perform operations concurrently, potentially improving performance on multi-core processors. 28 | - Parallelism can be enabled using the parallel() method on streams or by using parallel stream sources like parallelStream(). 29 | 30 | 7. Reduction Operations: 31 | - Reduction operations combine the elements of a stream into a single result, such as summing, averaging, or finding the maximum element. 32 | - Common reduction operations include reduce(), collect(), sum(), average(), max(), min(), etc. 33 | 34 | 8. Collectors: 35 | - Collectors are specialized reduction operations that collect elements from a stream into a mutable result container, such as a collection or a map. 36 | - Common collectors include toList(), toSet(), toMap(), joining(), groupingBy(), partitioningBy(), etc. 37 | 38 | 9. Error Handling: 39 | - Stream operations can throw checked exceptions, which must be handled appropriately using try-catch blocks or by propagating them to the caller. 40 | 41 | 10. Performance Considerations: 42 | - While streams offer concise and expressive code, improper use of streams can lead to performance overhead, especially when dealing with large datasets or complex operations. 43 | - It's essential to understand the characteristics of stream operations and consider performance implications when designing stream pipelines. 44 | 45 | */ 46 | 47 | import java.util.Arrays; 48 | import java.util.List; 49 | import java.util.stream.Collectors; 50 | 51 | public class StreamConcept { 52 | public static void main(String[] args) { 53 | // Create a list of integers 54 | List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 55 | 56 | // Intermediate operations: filter, map, sorted 57 | List evenNumbers = numbers.stream() 58 | .filter(n -> n % 2 == 0) // Filter even numbers 59 | .map(n -> n * 2) // Double each even number 60 | .sorted() // Sort the numbers 61 | .collect(Collectors.toList()); // Terminal operation: collect to list 62 | 63 | System.out.println("Even numbers (doubled and sorted): " + evenNumbers); 64 | 65 | // Lazy evaluation: not computed until terminal operation is invoked 66 | List names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Emily", "Frank"); 67 | 68 | System.out.println("First three names:"); 69 | names.stream() 70 | .limit(3) // Limit to first three names 71 | .forEach(System.out::println); // Terminal operation: print each name 72 | 73 | // Parallel streams: processing in parallel 74 | List squares = numbers.parallelStream() 75 | .map(n -> n * n) // Square each number 76 | .collect(Collectors.toList()); 77 | 78 | System.out.println("Squares of numbers (processed in parallel): " + squares); 79 | 80 | // Reduction operation: sum 81 | int sum = numbers.stream() 82 | .reduce(0, Integer::sum); // Terminal operation: reduce to sum 83 | System.out.println("Sum of numbers: " + sum); 84 | 85 | // Collectors: groupingBy 86 | List fruits = Arrays.asList("apple", "banana", "cherry", "date", "elderberry"); 87 | 88 | // Group fruits by their first letter 89 | System.out.println("Fruits grouped by first letter:"); 90 | fruits.stream() 91 | .collect(Collectors.groupingBy(s -> s.charAt(0))) // Group by first letter 92 | .forEach((letter, group) -> System.out.println(letter + ": " + group)); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/ThisKeyword.java: -------------------------------------------------------------------------------- 1 | // 'this' Keyword 2 | /* 3 | Using this Keyword: 4 | -The this keyword is used to refer to the current object instance within a class. 5 | -It is commonly used to differentiate between instance variables and parameters or local variables with the same name. 6 | -This approach is typically preferred when accessing or modifying instance variables within the same class. 7 | 8 | Directly Passing Object Reference: 9 | -Passing the object reference directly to a method allows access to the object's attributes and methods. 10 | -This approach is useful when you need to access attributes or methods of other objects within the same class or when you want to pass an object to another class. 11 | -It can simplify code and improve readability, especially when dealing with complex interactions between objects. 12 | */ 13 | 14 | public class ThisKeyword { 15 | public static void main(String[] a) { 16 | Human obj = new Human(); // Creating an object of Human class 17 | 18 | int age = 37; // Age value 19 | String name = "Bokkayya"; // Name value 20 | 21 | // Setting age using setter method with "this" keyword 22 | obj.setAge(age); 23 | 24 | // Setting name using setter method without "this" keyword (directly passing object) 25 | obj.setName(name, obj); 26 | 27 | // Getting and displaying age and name 28 | obj.getAge(); // Output: Age : 37 29 | obj.getName(); // Output: Name: Bokkayya 30 | } 31 | } 32 | 33 | // Human class 34 | class Human { 35 | private int humanAge; // Private instance variable for age 36 | private String humanName; // Private instance variable for name 37 | 38 | // Setter method for age 39 | public void setAge(int humanAge) { 40 | this.humanAge = humanAge; // Using "this" keyword to refer to the instance variable 41 | } 42 | 43 | // Setter method for name (directly passing object without "this" keyword) 44 | public void setName(String humanName, Human obj) { 45 | Human obj1 = obj; // Creating a local reference to the passed object 46 | obj1.humanName = humanName; // Directly accessing and setting the name 47 | } 48 | 49 | // Getter method for age 50 | public void getAge() { 51 | System.out.println("Age : " + humanAge); // Displaying age 52 | } 53 | 54 | // Getter method for name 55 | public void getName() { 56 | System.out.println("Name: " + humanName); // Displaying name 57 | } 58 | } 59 | 60 | /* 61 | In the above code: 62 | -The ThisKeyword class contains the main method where we create an object of the Human class and demonstrate setting and getting the age and name. 63 | -The Human class encapsulates the age and name as private instance variables. 64 | -The setAge method of the Human class sets the age using the this keyword. 65 | -The setName method of the Human class sets the name directly by passing the object reference without using the this keyword. 66 | -The getAge and getName methods of the Human class display the age and name, respectively. 67 | */ 68 | -------------------------------------------------------------------------------- /Java_Concepts/OOPS/This_vs_Super.java: -------------------------------------------------------------------------------- 1 | // this() vs super() 2 | /* 3 | this Keyword: 4 | - The 'this' keyword in Java is a reference variable that refers to the current object. 5 | - It can be used inside any method or constructor to refer to the current instance of the class. 6 | - Primary Uses: 7 | - Differentiating between instance variables and method parameters or local variables with the same name. 8 | - Invoking constructors within other constructors (constructor chaining). 9 | - Passing the current object as an argument in method calls or returning the current object from a method. 10 | - Usage: 11 | - Accessing instance variables: this.variableName 12 | - Invoking constructors: this() 13 | - Passing current object as an argument: method(this) 14 | - Returning current object: return this 15 | 16 | super Keyword: 17 | - The 'super' keyword in Java is a reference variable that is used to access members of the superclass. 18 | - It can be used to call superclass constructors, methods, or access superclass fields. 19 | - Primary Uses: 20 | - Calling superclass constructors: super(parameters) 21 | - Accessing superclass methods or fields: super.methodName() or super.variableName 22 | - Accessing superclass methods overridden by the subclass: super.methodName() 23 | - Usage: 24 | - Calling superclass constructor: super(parameters) 25 | - Accessing superclass method: super.methodName() 26 | - Accessing superclass field: super.variableName 27 | 28 | Key Differences: 29 | - 'this' keyword refers to the current object instance, while 'super' keyword refers to the superclass of the current object. 30 | - 'this' is used to differentiate between instance variables and method parameters or local variables with the same name, while 'super' is used to access members of the superclass. 31 | - 'this' is primarily used within the class where it is defined, while 'super' can be used within both the subclass and superclass. 32 | 33 | Object Class: 34 | - In Java, every class implicitly extends the Object class, even if it's not explicitly declared. 35 | - This means that if you don't specify a superclass for your class, Java automatically considers it to be a subclass of Object. 36 | - However, explicitly writing extends Object in a class declaration is redundant, as it doesn't change the class's behavior or inheritance hierarchy. 37 | */ 38 | 39 | 40 | public class This_vs_Super { 41 | public static void main(String[] a) { 42 | new B(); //Anonymous Object 43 | } 44 | } 45 | 46 | // Superclass A 47 | class A extends Object { 48 | // Default constructor 49 | public A() { 50 | super(); // Implicit call to superclass constructor (Object class constructor) 51 | System.out.println("In A"); 52 | } 53 | 54 | // Parameterized constructor 55 | public A(int n) { 56 | super(); // Implicit call to superclass constructor (Object class constructor) 57 | System.out.println("In A int"); 58 | } 59 | 60 | public void printInfo(){ 61 | System.out.println("Hello"); 62 | } 63 | } 64 | 65 | // Subclass B inheriting from A 66 | class B extends A { 67 | // Default constructor 68 | public B() { 69 | this(5); // Explicit call to B's parameterized constructor with value 5 70 | System.out.println("In B"); 71 | } 72 | 73 | // Parameterized constructor 74 | public B(int n) { 75 | super(); // Implicit call to superclass constructor (A class Default constructor) 76 | // super(5); // Implicit call to superclass constructor (A class Parameterized constructor) 77 | System.out.println("In B int"); 78 | super.printInfo(); 79 | } 80 | } 81 | 82 | -------------------------------------------------------------------------------- /Java_Concepts/PackageConcept/AccessModifier_PackageConcept/AccessModifierMain.java: -------------------------------------------------------------------------------- 1 | /* 2 | ClassA: 3 | - Defines variables and methods with private, default, protected, and public access modifiers. 4 | - Represents a base class showcasing encapsulation and access control in Java. 5 | - Demonstrates different levels of access for members within the same package. 6 | 7 | ClassB: 8 | - Located in the same package as ClassA (AccessModifier_Package). 9 | - Utilizes ClassA's public members to showcase access across classes in the same package. 10 | - Contains a method to print the contents of ClassA from ClassB. 11 | 12 | ClassC: 13 | - Located in a different package (AnotherAccessModifier_Package) from ClassA. 14 | - Extends ClassA, inheriting its public and protected members. 15 | - Demonstrates accessing ClassA's public members directly and inherits its protected members. 16 | - Contains additional members with public access. 17 | - Illustrates inheritance and access to superclass members from a subclass in a different package. 18 | 19 | AccessModifierMain: 20 | - Entry point for the program. 21 | - Creates instances of ClassA, ClassB, and ClassC. 22 | - Demonstrates usage of access modifiers by accessing members of ClassA, ClassB, and ClassC. 23 | - Provides a comprehensive overview of access control in Java through practical usage in the main program. 24 | */ 25 | 26 | package AccessModifier_PackageConcept; 27 | 28 | import AccessModifier_PackageConcept.AccessModifier_Package.*; 29 | import AccessModifier_PackageConcept.AnotherAccessModifier_Package.*; 30 | 31 | public class AccessModifierMain { 32 | public static void main(String[] args) { 33 | System.out.println("Main--------------------------------------------------------------"); 34 | // Create objects of classes from AccessModifier_Package 35 | ClassA objA = new ClassA(); 36 | ClassB objB = new ClassB(); 37 | 38 | // Accessing variables and methods of ClassA from AccessModifierMain 39 | System.out.println("Printing contents of ClassA from AccessModifierMain:"); 40 | // objA.defaultVarA; // Error: defaultVarA is not visible outside AccessModifier_Package 41 | // objA.protectedVarA; // Error: protectedVarA is not visible outside AccessModifier_Package 42 | System.out.println("Public variable in ClassA: " + objA.publicVarA); 43 | System.out.println("Public method in ClassA called from AccessModifierMain:"); 44 | objA.publicMethodA(); 45 | 46 | // Accessing variables and methods of ClassB from AccessModifierMain 47 | objB.printClassAContents(objA); 48 | 49 | // Create object of ClassC from AnotherAccessModifier_Package 50 | ClassC objC = new ClassC(); 51 | 52 | // Accessing variables and methods of ClassC from AccessModifierMain 53 | objC.printClassAContents(objA); 54 | 55 | // Accessing variables and methods of ClassC from AccessModifierMain 56 | System.out.println("Printing contents of ClassC from AccessModifierMain:"); 57 | System.out.println("Public variable in ClassC: " + objC.publicVarC); 58 | System.out.println("Public method in ClassC called from AccessModifierMain:"); 59 | objC.publicMethodC(); 60 | 61 | System.out.println("-------------------------------------------------------------------"); 62 | } 63 | } 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /Java_Concepts/PackageConcept/AccessModifier_PackageConcept/AccessModifier_Package/ClassA.java: -------------------------------------------------------------------------------- 1 | package AccessModifier_PackageConcept.AccessModifier_Package; 2 | 3 | public class ClassA { 4 | // Private variable accessible only within the class 5 | @SuppressWarnings("unused") 6 | private int privateVarA = 10; 7 | 8 | // Default variable accessible within the package 9 | int defaultVarA = 20; 10 | 11 | // Protected variable accessible within the package and by subclasses 12 | protected int protectedVarA = 30; 13 | 14 | // Public variable accessible from anywhere 15 | public int publicVarA = 40; 16 | 17 | // Private method accessible only within the class 18 | @SuppressWarnings("unused") 19 | private void privateMethodA() { 20 | System.out.println("Private method in ClassA called"); 21 | } 22 | 23 | // Default method accessible within the package 24 | void defaultMethodA() { 25 | System.out.println("Default method in ClassA called"); 26 | } 27 | 28 | // Protected method accessible within the package and by subclasses 29 | protected void protectedMethodA() { 30 | System.out.println("Protected method in ClassA called"); 31 | } 32 | 33 | // Public method accessible from anywhere 34 | public void publicMethodA() { 35 | System.out.println("Public method in ClassA called"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Java_Concepts/PackageConcept/AccessModifier_PackageConcept/AccessModifier_Package/ClassB.java: -------------------------------------------------------------------------------- 1 | package AccessModifier_PackageConcept.AccessModifier_Package; 2 | 3 | public class ClassB { 4 | public void printClassAContents(ClassA objA) { 5 | System.out.println("ClassB-------------------------------------------------------"); 6 | // Accessing variables and methods of ClassA 7 | System.out.println("Printing contents of ClassA from ClassB:"); 8 | //objA.privateVarA; // Error: privateVarA has private access in ClassA 9 | //objA.defaultVarA; // No error: defaultVarA is visible within the package 10 | System.out.println("Default variable in ClassA: " + objA.defaultVarA); 11 | System.out.println("Protected variable in ClassA: " + objA.protectedVarA); 12 | System.out.println("Public variable in ClassA: " + objA.publicVarA); 13 | //objA.privateMethodA(); // Error: privateMethodA() has private access in ClassA 14 | //objA.defaultMethodA(); // No error: defaultMethodA() is visible within the package 15 | System.out.println("Public method in ClassA called from ClassB:"); 16 | objA.publicMethodA(); 17 | System.out.println("-------------------------------------------------------------"); 18 | } 19 | } 20 | 21 | 22 | -------------------------------------------------------------------------------- /Java_Concepts/PackageConcept/AccessModifier_PackageConcept/AnotherAccessModifier_Package/ClassC.java: -------------------------------------------------------------------------------- 1 | package AccessModifier_PackageConcept.AnotherAccessModifier_Package; // Different package from ClassA and ClassB 2 | 3 | import AccessModifier_PackageConcept.AccessModifier_Package.ClassA; 4 | 5 | public class ClassC { 6 | // Private variable accessible only within the class 7 | @SuppressWarnings("unused") 8 | private int privateVarC = 50; 9 | 10 | // Public variable accessible from anywhere 11 | public int publicVarC = 80; 12 | 13 | // Private method accessible only within the class 14 | @SuppressWarnings("unused") 15 | private void privateMethodC() { 16 | System.out.println("Private method in ClassC called"); 17 | } 18 | 19 | // Public method accessible from anywhere 20 | public void publicMethodC() { 21 | System.out.println("Public method in ClassC called"); 22 | } 23 | 24 | // Method to print contents of ClassA from ClassC 25 | public void printClassAContents(ClassA objA) { 26 | System.out.println("ClassC-------------------------------------------------------"); 27 | // Accessing variables and methods of ClassA 28 | System.out.println("Printing contents of ClassA from ClassC:"); 29 | //objA.defaultVarA; // Error: defaultVarA is not visible from AnotherAccessModifier_Package 30 | //objA.protectedVarA; // Error: protectedVarA is not visible from AnotherAccessModifier_Package 31 | System.out.println("Public variable in ClassA: " + objA.publicVarA); 32 | System.out.println("Public method in ClassA called from ClassC:"); 33 | objA.publicMethodA(); 34 | System.out.println("-------------------------------------------------------------"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Java_Concepts/PackageConcept/Basic_PackageConcepts/AdvOperation/AdvLevel1_Operation.java: -------------------------------------------------------------------------------- 1 | package AdvOperation; 2 | 3 | public class AdvLevel1_Operation { 4 | // Method to calculate power 5 | public double power(int n1, int n2) { 6 | return Math.pow(n1, n2); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Java_Concepts/PackageConcept/Basic_PackageConcepts/AdvOperation/AdvLevel2_Operation.java: -------------------------------------------------------------------------------- 1 | package AdvOperation; 2 | 3 | public class AdvLevel2_Operation { 4 | // Method to calculate square root 5 | public double SquareRoot(int n) { 6 | return Math.sqrt(n); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Java_Concepts/PackageConcept/Basic_PackageConcepts/BasicOperation/Level1_Operation.java: -------------------------------------------------------------------------------- 1 | package BasicOperation; 2 | 3 | public class Level1_Operation { 4 | // Method to perform addition 5 | public int add(int n1, int n2) { 6 | return n1 + n2; 7 | } 8 | 9 | // Method to perform subtraction 10 | public int sub(int n1, int n2) { 11 | return n1 - n2; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Java_Concepts/PackageConcept/Basic_PackageConcepts/BasicOperation/Level2_Operation.java: -------------------------------------------------------------------------------- 1 | package BasicOperation; 2 | 3 | public class Level2_Operation extends Level1_Operation { 4 | // Method to perform multiplication 5 | public int mul(int n1, int n2) { 6 | return n1 * n2; 7 | } 8 | 9 | // Method to perform division 10 | public int div(int n1, int n2) { 11 | return n1 / n2; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Java_Concepts/PackageConcept/Basic_PackageConcepts/PackageConcept_SimpleCalculator.java: -------------------------------------------------------------------------------- 1 | // Packages 2 | /* 3 | 1. Packages in Java: 4 | 5 | - Packages in Java are used to organize and manage classes and interfaces into groups or namespaces. 6 | - They help in avoiding naming conflicts and provide a modular structure for large-scale applications. 7 | - A package is a directory that contains related Java classes and interfaces. 8 | - Packages provide a way to encapsulate classes and control access to them. 9 | - Java packages follow a hierarchical naming structure, similar to directories in a file system. 10 | 11 | 2. Advantages of Using Packages: 12 | 13 | - **Modularity**: Packages help in organizing code into logical units, making it easier to manage and maintain. 14 | - **Encapsulation**: Packages allow classes to be grouped together based on functionality, providing a level of encapsulation. 15 | - **Namespace Management**: Packages prevent naming conflicts by segregating classes into separate namespaces. 16 | - **Access Control**: Packages can control access to classes and members using access modifiers like public, protected, and private. 17 | - **Reusability**: Packages facilitate code reuse by allowing classes to be easily shared and imported into other projects. 18 | 19 | 3. Package Naming Conventions: 20 | 21 | - Package names are written in lowercase letters by convention. 22 | - Packages follow a reverse domain name convention, such as 'com.example.package' to get a unique name for packages. 23 | - The Java naming convention suggests using a company's domain name in reverse order as the package name prefix. 24 | - Package names should be short, descriptive, and meaningful to reflect the content and purpose of the classes within them. 25 | 26 | 4. Creating and Using Packages: 27 | 28 | - To create a package, you simply include a 'package' declaration at the beginning of your Java source file. 29 | - The package declaration specifies the name of the package to which the class belongs. 30 | - To use classes from another package, you need to import them using the `import` statement. 31 | - Import statements allow you to access classes and interfaces from other packages without fully qualifying their names. 32 | - You can import specific classes or the entire package using wildcards (*). 33 | 34 | 5. Package Structure in File System: 35 | 36 | - In the file system, each package corresponds to a directory, and each dot (.) in the package name corresponds to a directory separator. 37 | - For example, the package com.example.package would be stored in a directory structure like com/example/package. 38 | - The Java compiler automatically searches for classes in the directories specified by the classpath. 39 | 40 | 6. Standard Java Packages: 41 | 42 | - Java provides several standard packages, such as java.lang, java.util, java.io, etc., which contain commonly used classes and interfaces. 43 | - These packages are automatically imported into every Java program and can be used without explicit import statements. 44 | - The java.lang package, in particular, contains fundamental classes and objects that are essential for all Java programs, such as String, Object, System, etc. 45 | - Every class(inBuild) in java belongs to some packages. 46 | 47 | */ 48 | //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 49 | /* 50 | PackageConcepts Folder(main folder) 51 | - PackageConcept_SimpleCalculator.java (Main class) 52 | - BasicOperation 53 | - Level1_Operation.java (add(),sub()) 54 | - Level2_Operation.java (mul(),div()) 55 | - AdvOperation 56 | - AdvLevel1_Operation.java (pow()) 57 | - AdvLevel2_Operation.java (sqrt()) 58 | */ 59 | 60 | /* 61 | To compile and run the Java files from the terminal: 62 | 63 | Open Terminal: Open your terminal. 64 | Navigate to Project Directory: Use cd to move to the directory containing your Java files. 65 | 66 | Compile Java Files: Use javac to compile all Java files including the main class and classes in packages: 67 | javac PackageConcept_SimpleCalculator.java BasicOperation/*.java AdvOperation/*.java 68 | 69 | Run Program: After successful compilation, run the main class using java: 70 | java PackageConcept_SimpleCalculator 71 | 72 | This will execute the Java program and display the output in the terminal. 73 | */ 74 | //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 75 | 76 | // Importing classes from BasicOperation package 77 | // import BasicOperation.Level1_Operation; 78 | // import BasicOperation.Level2_Operation; 79 | import BasicOperation.*; //'*' only refers to all the files inside the Folder, not the subFolders 80 | 81 | // Importing specific classes from AdvOperation package 82 | import AdvOperation.AdvLevel1_Operation; 83 | import AdvOperation.AdvLevel2_Operation; 84 | 85 | public class PackageConcept_SimpleCalculator { 86 | public static void main(String[] args) { 87 | 88 | // Creating an object of Level2_Operation class from BasicOperation package(Level 2 inherits Level 1) 89 | Level2_Operation obj1 = new Level2_Operation(); 90 | 91 | // Performing basic operations 92 | System.out.println("Add : " + obj1.add(4, 3)); 93 | System.out.println("Sub : " + obj1.sub(4, 3)); 94 | System.out.println("Mul : " + obj1.mul(4, 3)); 95 | System.out.println("Div : " + obj1.div(4, 3)); 96 | 97 | // Creating objects of advanced operation classes from AdvOperation package 98 | AdvLevel1_Operation obj2 = new AdvLevel1_Operation(); 99 | System.out.println("Pow : " + obj2.power(4, 3)); 100 | 101 | AdvLevel2_Operation obj3 = new AdvLevel2_Operation(); 102 | System.out.println("Sqrt: " + obj3.SquareRoot(49)); 103 | 104 | } 105 | } 106 | 107 | -------------------------------------------------------------------------------- /Java_Concepts/Thread/ThreadConcept.java: -------------------------------------------------------------------------------- 1 | // Thread concept 2 | /* 3 | Thread concept in Java allows concurrent execution of tasks, enabling applications to perform multiple operations simultaneously. 4 | 5 | 1. Thread Basics: 6 | - A thread is a lightweight process within a process. It allows Java programs to perform multiple tasks simultaneously by dividing the program into multiple execution paths. 7 | - Java applications can have multiple threads running concurrently, each executing its set of instructions independently. 8 | - Threads are instances of the java.lang.Thread class or implement the java.lang.Runnable interface. 9 | 10 | 2. Concurrency: 11 | - Threads enable concurrent execution, where multiple tasks can run simultaneously within a program. 12 | - Each thread has its own stack and program counter, allowing it to execute independently of other threads. 13 | 14 | 3. Creating Threads: 15 | - There are two ways to create threads in Java: 16 | a. Extending the Thread class and overriding its run() method. 17 | - Example: 18 | class A extends Thread{ 19 | public void run() //Always thread class have run() method 20 | {// Thread logic here}} 21 | class B extends Thread{ 22 | public void run() 23 | {// Thread logic here}} 24 | public class MainLobby1{ 25 | public static void main(String[] args){ 26 | A obj1 = new A(); 27 | B obj2 = new B(); 28 | 29 | obj1.start(); //always start() method to execute the thread run() method. 30 | obj2.start(); }} 31 | 32 | b. Implementing the Runnable interface and providing implementation for the run() method. 33 | - Example: 34 | class A implements Runnable{ 35 | public void run(){// Thread logic here}} 36 | class B implements Runnable{ 37 | public void run(){// Thread logic here}} 38 | public class Main{ 39 | public static void main(String[] args){ 40 | A obj1 = new A(); 41 | B obj2 = new B(); 42 | 43 | Thread t1 = new Thread(obj1); 44 | Thread t2 = new Thread(obj2); 45 | 46 | t1.start(); 47 | t2.start(); }} 48 | 49 | 4. Starting Threads: 50 | - Threads are started using the start() method, which calls the run() method internally. 51 | - Example: 52 | MyThread thread = new MyThread(); 53 | thread.start(); 54 | 55 | 5. Thread States: 56 | - Threads in Java can be in one of the following states: 57 | a. New: The thread has been created but not started yet. 58 | b. Runnable: The thread is ready to run and waiting for CPU time. 59 | c. Blocked/Waiting: The thread is temporarily inactive, waiting for an event to occur. 60 | d. Timed Waiting: The thread is waiting for a specific period. 61 | e. Terminated: The thread has completed execution. 62 | 63 | 6. Thread Synchronization: 64 | - In a multithreaded environment, synchronization ensures that only one thread can access a resource or critical section at a time to prevent race conditions and data corruption. 65 | - Synchronization can be achieved using: 66 | a. synchronized keyword: Used to create synchronized methods or blocks. 67 | b. wait() and notify() methods: Used for inter-thread communication and coordination. 68 | c. Lock and Condition interfaces: Provides a more flexible way of synchronization. 69 | 70 | 7. Thread Interruption: 71 | - Threads can be interrupted using the interrupt() method to signal them to stop execution. 72 | - Interrupted threads can handle the interruption by catching InterruptedException and performing cleanup tasks. 73 | 74 | 8. Thread Joining: 75 | - The join() method allows one thread to wait for the completion of another thread. 76 | - This is useful for coordinating the execution sequence of threads. 77 | 78 | 9. Thread Priority: 79 | - Threads can have priorities ranging from 1 (lowest) to 10 (highest). 80 | - Higher priority threads are scheduled to run before lower priority threads, but it's not guaranteed. 81 | 82 | 10. Thread Lifecycle: 83 | - The lifecycle of a thread consists of several states, including creation, execution, and termination. 84 | - Threads transition between these states based on their execution status and actions performed by the program. 85 | - The main states of the thread lifecycle are: new, runnable, blocked, waiting, timed waiting, and terminated. 86 | 87 | 11. Thread Pooling: 88 | - Thread pooling is a technique used to manage and reuse a pool of worker threads to execute tasks asynchronously. 89 | - Java provides the Executor framework (ExecutorService and ThreadPoolExecutor) for managing thread pools efficiently. 90 | 91 | 12. Thread Safety: 92 | - Thread safety ensures that shared resources are accessed safely by multiple threads without causing data corruption or inconsistencies. 93 | - Techniques such as synchronization, atomic operations, and using thread-safe data structures (e.g., ConcurrentHashMap, CopyOnWriteArrayList) help achieve thread safety. 94 | 95 | 13. scheduler: 96 | - The scheduler in Java is responsible for managing the execution of threads within a Java Virtual Machine (JVM). 97 | - It determines which threads should run, when they should run, and for how long they should run. 98 | Thread Priority:Threads in Java can be assigned a priority ranging from 1 (lowest) to 10 (highest). 99 | The thread scheduler uses these priorities to determine the order in which threads are executed. 100 | However, the actual behavior may vary between different JVM implementations and operating systems. 101 | Time Slicing: The scheduler allocates CPU time to threads using a technique called time slicing. Each thread is given a small time slice during which it can execute. 102 | Once the time slice expires, the scheduler may switch to another thread. 103 | 104 | 14. Concurrency Utilities: 105 | - Java provides high-level concurrency utilities in the java.util.concurrent package, such as ExecutorService, Semaphore, CountDownLatch, CyclicBarrier, etc., to simplify concurrent programming tasks. 106 | 107 | */ 108 | 109 | public class ThreadConcept { 110 | public static void main(String[] args) { 111 | // Creating and starting a thread by extending the Thread class 112 | MyThreadConcept thread1 = new MyThreadConcept(); 113 | thread1.start(); 114 | 115 | // Creating and starting a thread by implementing the Runnable interface 116 | Thread thread2 = new Thread(new MyRunnableConcept()); 117 | thread2.start(); 118 | 119 | // Synchronizing access to shared data 120 | SharedDataConcept sharedData = new SharedDataConcept(); 121 | Thread thread3 = new Thread(new MyRunnableWithSyncConcept(sharedData)); 122 | Thread thread4 = new Thread(new MyRunnableWithSyncConcept(sharedData)); 123 | Thread thread5 = new Thread(new MyRunnableWithSyncConcept(sharedData)); 124 | Thread thread6 = new Thread(new MyRunnableWithSyncConcept(sharedData)); 125 | thread3.start(); 126 | thread4.start(); 127 | thread5.start(); 128 | thread6.start(); 129 | 130 | // Interrupting a thread 131 | Thread thread7 = new Thread(new MyInterruptedRunnableConcept()); 132 | thread7.start(); 133 | thread7.interrupt(); //interrupt the sleeping thread 134 | 135 | // Joining threads 136 | try { 137 | thread1.join(); 138 | thread2.join(); 139 | thread3.join(); 140 | thread4.join(); 141 | thread5.join(); 142 | thread6.join(); 143 | thread7.join(); 144 | } catch (InterruptedException e) { 145 | e.printStackTrace(); 146 | } 147 | 148 | System.out.println("Main thread exiting..."); //~ without join() main may be executed first before thread 149 | 150 | for(int i=0;i<1;i++) 151 | { 152 | for(int j=0;j<1000000000;j++){} //max int delay 153 | for(int k=0;k<1000000000;k++){} //max int delay 154 | System.out.println("Main delay thread exiting..."); //~Creating a delay, Main may be executed after the delay to the thread 155 | } 156 | } 157 | } 158 | 159 | // Thread by extending Thread class 160 | class MyThreadConcept extends Thread { 161 | @Override 162 | public void run() { 163 | System.out.println("Thread by extending Thread class: " + Thread.currentThread().getName()); 164 | } 165 | } 166 | 167 | // Thread by implementing Runnable interface 168 | class MyRunnableConcept implements Runnable { 169 | @Override 170 | public void run() { 171 | System.out.println("Thread by implementing Runnable interface: " + Thread.currentThread().getName()); 172 | } 173 | } 174 | 175 | // Synchronizing access to shared data 176 | class SharedDataConcept { 177 | private int count = 0; //initialized to zero 178 | 179 | public synchronized void increment() //synchronized keyword enables thread synchronization one after another 180 | { 181 | count++; 182 | System.out.println("Incremented count: " + count); 183 | } 184 | } 185 | 186 | class MyRunnableWithSyncConcept implements Runnable { 187 | private SharedDataConcept sharedData; 188 | 189 | // Constructor 190 | public MyRunnableWithSyncConcept(SharedDataConcept sharedData) { 191 | this.sharedData = sharedData; 192 | } 193 | 194 | @Override 195 | public void run() { 196 | sharedData.increment(); 197 | } 198 | } 199 | 200 | // Interrupting a thread 201 | class MyInterruptedRunnableConcept implements Runnable { 202 | @Override 203 | public void run() { 204 | try { 205 | Thread.sleep(1000); //thread7 is sleeping for 1000 milliseconds using Thread.sleep(1000). If the interruption occurs while the thread is sleeping, it will throw an InterruptedException, causing the thread to exit the sleep and proceed to execute the code within the catch block. 206 | } catch (InterruptedException e) { 207 | System.out.println("Thread interrupted: " + Thread.currentThread().getName()); //thread7(Thread-6) 208 | } 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /Java_Tasks/Calculator_System/AdvancedCalculator.java: -------------------------------------------------------------------------------- 1 | package Calculator_System; 2 | 3 | public class AdvancedCalculator extends BasicCalculator { 4 | 5 | public double power(double base, double exponent) { 6 | return Math.pow(base, exponent); 7 | } 8 | 9 | public double squareRoot(double num) { 10 | return Math.sqrt(num); 11 | } 12 | 13 | public double factorial(int num) { 14 | if (num < 0) { 15 | throw new IllegalArgumentException("Factorial is not defined for negative numbers"); 16 | } 17 | if (num == 0 || num == 1) { 18 | return 1; 19 | } 20 | return num * factorial(num - 1); 21 | } 22 | 23 | } 24 | 25 | -------------------------------------------------------------------------------- /Java_Tasks/Calculator_System/BasicCalculator.java: -------------------------------------------------------------------------------- 1 | package Calculator_System; 2 | 3 | public class BasicCalculator implements Calculator { 4 | @Override 5 | public double add(double num1, double num2) { 6 | return num1 + num2; 7 | } 8 | 9 | @Override 10 | public double subtract(double num1, double num2) { 11 | return num1 - num2; 12 | } 13 | 14 | @Override 15 | public double multiply(double num1, double num2) { 16 | return num1 * num2; 17 | } 18 | 19 | @Override 20 | public double divide(double num1, double num2) { 21 | if (num2 == 0) { 22 | throw new ArithmeticException("Cannot divide by zero"); 23 | } 24 | return num1 / num2; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Java_Tasks/Calculator_System/Calculator.java: -------------------------------------------------------------------------------- 1 | package Calculator_System; 2 | 3 | public interface Calculator { 4 | double add(double num1, double num2); 5 | double subtract(double num1, double num2); 6 | double multiply(double num1, double num2); 7 | double divide(double num1, double num2); 8 | } 9 | 10 | -------------------------------------------------------------------------------- /Java_Tasks/Calculator_System/CalculatorMain.java: -------------------------------------------------------------------------------- 1 | package Calculator_System; 2 | 3 | public class CalculatorMain { 4 | public static void main(String[] args) { 5 | BasicCalculator basicCalculator = new BasicCalculator(); 6 | AdvancedCalculator advancedCalculator = new AdvancedCalculator(); 7 | 8 | // Basic Calculator Operations 9 | System.out.println("Basic Calculator:"); 10 | System.out.println("Addition: " + basicCalculator.add(10, 5)); 11 | System.out.println("Subtraction: " + basicCalculator.subtract(10, 5)); 12 | System.out.println("Multiplication: " + basicCalculator.multiply(10, 5)); 13 | System.out.println("Division: " + basicCalculator.divide(10, 5)); 14 | 15 | // Advanced Calculator Operations 16 | System.out.println("\nAdvanced Calculator:"); 17 | System.out.println("Power: " + advancedCalculator.power(2, 3)); 18 | System.out.println("Square Root: " + advancedCalculator.squareRoot(16)); 19 | System.out.println("Factorial: " + advancedCalculator.factorial(5)); 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /Java_Tasks/Student_Management/Add_Student.java: -------------------------------------------------------------------------------- 1 | package Student_Management; 2 | 3 | public class Add_Student { 4 | // Instance variables 5 | private String Student_name; 6 | private int Student_rollNo; 7 | private int Student_Age; 8 | private double Student_GPA; 9 | 10 | // Constructor 11 | Add_Student(String Student_name, int Student_rollNo, int Student_Age, double Student_GPA) { 12 | this.Student_name = Student_name; 13 | this.Student_rollNo = Student_rollNo; 14 | this.Student_Age = Student_Age; 15 | this.Student_GPA = Student_GPA; 16 | } 17 | 18 | // Getters for accessing private variables 19 | public String get_Student_name() { 20 | return this.Student_name; 21 | } 22 | 23 | public int get_Student_rollNo() { 24 | return this.Student_rollNo; 25 | } 26 | 27 | public int get_Student_Age() { 28 | return this.Student_Age; 29 | } 30 | 31 | public double get_Student_GPA() { 32 | return this.Student_GPA; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Java_Tasks/Student_Management/Remove_Student.java: -------------------------------------------------------------------------------- 1 | package Student_Management; 2 | import java.util.ArrayList; 3 | 4 | public class Remove_Student { 5 | // Method to remove student details by Roll No 6 | public static void remove_Student_details(ArrayList Student_Details, int remove_by_rollNo) { 7 | boolean removed = false; // Flag to track if student is removed 8 | for (int i = 0; i < Student_Details.size(); i++) { 9 | if (Student_Details.get(i).get_Student_rollNo() == remove_by_rollNo) { // If Roll No matches 10 | Student_Details.remove(i); // Remove student from list 11 | System.out.println("Student with Roll No " + remove_by_rollNo + " removed successfully."); 12 | removed = true; // Set flag to true 13 | break; // Exit loop after removing the student 14 | } 15 | } 16 | if (!removed) { 17 | System.out.println("Student with Roll No " + remove_by_rollNo + " not found."); // If not found 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java_Tasks/Student_Management/Search_Student.java: -------------------------------------------------------------------------------- 1 | package Student_Management; 2 | import java.util.ArrayList; 3 | 4 | public class Search_Student { 5 | // Method to search for a student by name 6 | public static void search_Student_details(ArrayList Student_Details, String search_by_name) { 7 | boolean found = false; // Flag to track if the student is found 8 | // Loop through the list of students 9 | for (Add_Student student : Student_Details) { 10 | // Check if the name matches the search query (case insensitive) 11 | if (student.get_Student_name().equalsIgnoreCase(search_by_name)) { 12 | System.out.println("Student Found"); // Print message 13 | // Print student details 14 | System.out.print(" Name: " + student.get_Student_name() + " | "); 15 | System.out.print(" Roll No: " + student.get_Student_rollNo() + " | "); 16 | System.out.print(" Age: " + student.get_Student_Age() + " | "); 17 | System.out.print(" GPA: " + student.get_Student_GPA() + " | "); 18 | System.out.println(); // Move to the next line 19 | found = true; // Set the flag to true 20 | break; // Exit the loop since the student is found 21 | } 22 | } 23 | // If the student is not found 24 | if (!found) { 25 | System.out.println("Student " + search_by_name + " not Found."); // Print message 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Java_Tasks/Student_Management/Sort_Student.java: -------------------------------------------------------------------------------- 1 | package Student_Management; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Comparator; 6 | 7 | public class Sort_Student { 8 | // Method to sort student details by Roll No or GPA 9 | public static void sort_Student_details(ArrayList Student_Details, int sort_by) { 10 | switch (sort_by) { 11 | case 1: // Sort by Roll No 12 | Collections.sort(Student_Details, Comparator.comparing(Add_Student::get_Student_rollNo)); 13 | System.out.println("Students sorted by Roll No:"); 14 | View_Student.display_Students(Student_Details); // Display sorted students 15 | break; 16 | case 2: // Sort by GPA 17 | Collections.sort(Student_Details, Comparator.comparing(Add_Student::get_Student_GPA)); 18 | System.out.println("Students sorted by GPA:"); 19 | View_Student.display_Students(Student_Details); // Display sorted students 20 | break; 21 | default: // Invalid choice 22 | System.out.println("Invalid choice for sorting."); 23 | break; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Java_Tasks/Student_Management/StudentMain.java: -------------------------------------------------------------------------------- 1 | package Student_Management; 2 | import java.util.*; 3 | 4 | public class StudentMain { 5 | // Total count of students 6 | public static int student_TotalCount = 0; 7 | 8 | public static void main(String a[]) { 9 | // Welcome message 10 | System.out.println("\"Welcome to Student Management Tool\" "); 11 | // Scanner for user input 12 | Scanner scan = new Scanner(System.in); 13 | 14 | // List to store student details 15 | ArrayList Student_Details = new ArrayList<>(); 16 | 17 | // Main loop for user interaction 18 | boolean run = true; 19 | while(run) { 20 | // Menu options 21 | System.out.print("\n1.Add 2.Remove 3.Sort 4.Search 5.View 6.Exit \nEnter your Command(1-5): "); 22 | int InputCommand = scan.nextInt(); 23 | 24 | switch(InputCommand) { 25 | case 1: 26 | System.out.println("\nAdd:"); 27 | add_new_student(Student_Details); 28 | break; 29 | case 2: 30 | System.out.println("\nRemove:"); 31 | remove_student(Student_Details); 32 | break; 33 | case 3: 34 | System.out.println("\nSort:"); 35 | sort_student(Student_Details); 36 | break; 37 | case 4: 38 | System.out.println("\nSearch:"); 39 | Search_Student(Student_Details); 40 | break; 41 | case 5: 42 | System.out.println("\nView:"); 43 | System.out.println("Total Students: "+ student_TotalCount); 44 | View_Student.display_Students(Student_Details); 45 | break; 46 | case 6: 47 | System.out.println("\nExit:"); 48 | run = false; 49 | break; 50 | default: 51 | System.out.println("InValid Input, Try again.."); 52 | } 53 | } 54 | // Close scanner 55 | scan.close(); 56 | } 57 | 58 | // Method to add a new student 59 | @SuppressWarnings("resource") 60 | private static void add_new_student(ArrayList Student_Details) { 61 | Scanner scan = new Scanner(System.in); 62 | System.out.print("Enter Student Name: "); 63 | String Student_name = scan.nextLine(); 64 | System.out.print("Enter Student Roll No: "); 65 | int Student_RollNo = scan.nextInt(); 66 | System.out.print("Enter Student Age: "); 67 | int Student_Age = scan.nextInt(); 68 | System.out.print("Enter Student GPA: "); 69 | Double Student_GPA = scan.nextDouble(); 70 | 71 | // Create new student object and add to list 72 | Add_Student add_student = new Add_Student(Student_name, Student_RollNo, Student_Age, Student_GPA); 73 | Student_Details.add(add_student); 74 | // Increment total student count 75 | student_TotalCount++; 76 | System.out.println("New Student Details Successfully added"); 77 | } 78 | 79 | // Method to remove a student 80 | @SuppressWarnings("resource") 81 | private static void remove_student(ArrayList Student_Details) { 82 | Scanner scan = new Scanner(System.in); 83 | System.out.println("Enter Roll No of the Students to Remove: "); 84 | int remove_by_rollNo = scan.nextInt(); 85 | Remove_Student.remove_Student_details(Student_Details, remove_by_rollNo); 86 | // Decrement total student count 87 | student_TotalCount--; 88 | } 89 | 90 | // Method to sort students by Roll No or GPA 91 | @SuppressWarnings("resource") 92 | private static void sort_student(ArrayList Student_Details) { 93 | Scanner scan = new Scanner(System.in); 94 | System.out.println("1.RollNo 2.GPA \n Enter Sort by(1/2): "); 95 | int sort_by = scan.nextInt(); 96 | Sort_Student.sort_Student_details(Student_Details, sort_by); 97 | } 98 | 99 | // Method to search students by Name 100 | @SuppressWarnings("resource") 101 | private static void Search_Student(ArrayList Student_Details) { 102 | Scanner scan = new Scanner(System.in); 103 | System.out.println("Enter the name of the student to search: "); 104 | String search_by_name = scan.nextLine(); 105 | Search_Student.search_Student_details(Student_Details, search_by_name); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /Java_Tasks/Student_Management/View_Student.java: -------------------------------------------------------------------------------- 1 | package Student_Management; 2 | import java.util.*; 3 | 4 | public class View_Student { 5 | // Method to display student details 6 | public static void display_Students(ArrayList Student_Details) { 7 | // Loop through the list of students and display their details 8 | for(Add_Student student: Student_Details) { 9 | // Print student details 10 | System.out.print(" Name: " + student.get_Student_name() + " | "); 11 | System.out.print(" Roll No: " + student.get_Student_rollNo() + " | "); 12 | System.out.print(" Age: " + student.get_Student_Age() + " | "); 13 | System.out.print(" GPA: " + student.get_Student_GPA() + " | "); 14 | System.out.println(); // Move to the next line for the next student 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 rahulkrishy 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Welcome to the CPT(Concepts-Practices-Tasks)_Java Programming Language Learning Guide! 👨🏻‍💻🚀 2 | --- 3 | ## 📚 About This Repository 4 | ✧ Explore Java from basics to advanced Concepts.
5 | 6 | ## 📋 Table of Contents 7 | 1. [Java_Concepts](#java_concepts) 8 | 2. [Java_Practices](#java_practices) 9 | 3. [Java_Tasks](#java_tasks) 10 | --- 11 | ## 📖 Repository Content 12 | 13 | ### Java_Concepts: 14 | 15 | - **Basic:** 16 | - `_Intro` 17 | - `_HelloWorld` 18 | - `DataTypes` 19 | - `AccessModifier` 20 | - `ConditionalStatements` 21 | - `SwitchCase` 22 | - `TernaryOperator` 23 | - `ControlFlow` 24 | - `ReadingUserinput` 25 | - `Constructor` 26 | - `MethodOverloading` 27 | - `ObjectClassConcept` 28 | - `NestedClass` 29 | - `GenericClass` 30 | - `StaticConcepts` 31 | - `Stack_vs_Heap` 32 | - `Up_down_Casting` 33 | - `AnonymousObject` 34 | - `EnumConcept` 35 | - `ExceptionHandlingConcept` 36 | - `RegexConcept` 37 | 38 | - **Array:** 39 | - `Array` 40 | - `Array_2D` 41 | - `Array_ArrayOfObjects` 42 | 43 | - **String:** 44 | - `StringConcepts` 45 | 46 | - **OOPS (Object-Oriented Programming):** 47 | - `OopsConcepts` 48 | - `Oops_Encapsulation` 49 | - `Oops_Inheritance` 50 | - `Oops_Inheritance_Single` 51 | - `Oops_Inheritance_MultiLevel` 52 | - `Oops_Inheritance_Hierarchical` 53 | - `Oops_Inheritance_Hybrid` 54 | - `Oops_Abstraction` 55 | - `Oops_Polymorphism` 56 | - `Overloading_vs_OverRiding` 57 | - `ThisKeyword` 58 | - `This_vs_Super` 59 | - `FinalKeyword` 60 | - `StreamConcept` 61 | - `DateClass` 62 | 63 | - **Interface:** 64 | - `InterfaceConcept` 65 | - `InterfaceTypes` 66 | 67 | - **Collection:** 68 | - `CollectionConcept` 69 | - `Collection_List_Interface` 70 | - `Collection_Set_Interface` 71 | - `Collection_Map_Interface` 72 | - `Collection_Queue_Interface` 73 | - `Comparable_vs_Comparator` 74 | 75 | - **PackageConcept:** 76 | - `Basic_PackageConcepts` 77 | - `AccessModifier_PackageConcept` 78 | 79 | - **Thread:** 80 | - `ThreadConcept` 81 | 82 | - **DSA (Data Structures and Algorithms):** 83 | - `Algorithm_BinarySearch` 84 | 85 | --- 86 | 87 | ### Java_Practices: 88 | - `Stay Tuned...▶️` 89 | 90 | --- 91 | 92 | ### Java_Tasks: 93 | Project-based tasks to reinforce Java concepts. 94 | 95 | --- 96 | 97 | ## 📢 Stay Tuned for More Updates! 98 | 99 | I'm continuously adding new concepts, tasks, and exercises to this repository. If you have any feedback or suggestions to improve it, feel free to share your thoughts. Stay tuned for updates, and until then, keep practicing. Greets! ✌🏻 100 | 101 | --- 102 | ## 📜 License 103 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 104 | --------------------------------------------------------------------------------