From 30ad792c7ff91c985da72a463a135e4baac78aed Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 11:31:48 +0530
Subject: [PATCH 001/236] Update README.md
---
section3/HelloWorld/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index 7314a62..25492cf 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -1 +1 @@
-### Sample
+### Sample 1
From a248f4a19fe582a874043cfc9ee9591efa7eb2ad Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 13:15:30 +0530
Subject: [PATCH 002/236] Update README.md
---
section3/HelloWorld/README.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index 25492cf..ed9ce5b 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -1 +1,2 @@
-### Sample 1
+### Getting Started with Java in IntelliJ IDEA
+Welcome to our Java course! In this guide, we'll walk you through creating your first Java class using IntelliJ IDEA, a powerful integrated development environment (IDE) for Java development.
From 0e0795b0beba493431b508ab32d6d18247f0d4b5 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 14:13:44 +0530
Subject: [PATCH 003/236] Update README.md
---
section3/HelloWorld/README.md | 26 +++++++++++++++++++++++++-
1 file changed, 25 insertions(+), 1 deletion(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index ed9ce5b..e24bf86 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -1,2 +1,26 @@
-### Getting Started with Java in IntelliJ IDEA
+# Getting Started with Java in IntelliJ IDEA
Welcome to our Java course! In this guide, we'll walk you through creating your first Java class using IntelliJ IDEA, a powerful integrated development environment (IDE) for Java development.
+### Prerequisites
+Before getting started, ensure that you have the following installed on your system:
+- IntelliJ IDEA (Community or Ultimate edition)
+- Java Development Kit (JDK) installed on your machine
+ ### Steps to Create Your First Java Class
+ 1. **Open IntelliJ IDEA :** Launch IntelliJ IDEA on your system.
+ 2. **Create a New Project :**
+ - Click on Create New Project on the welcome screen or go to File > New > Project.
+ 3. #### Set Up Your Project :
+ - Enter a Project Name for your project.
+ - Choose a Project Location where you want to save your project files.
+ - Select the Language as Java.
+ - Build aystem as IntelliJ.
+ - Add JDK as corretto-21 or click on New... and locate your JDK installation directory.
+ - Click on Create to create the project.
+ 4. #### Create A Java Class :
+ - In the Project tool window (usually located on the left-hand side), right-click on the src folder.
+ - Go to New > Java Class.
+ - Enter a name for your class in the Name field (e.g., MyFirstClass).
+ - Optionally, you can specify a Package for your class. If you're just starting out, you can leave it as the default package.
+ - Click OK to create the class.
+
+
+
From b963d1b48e91e82b98ae90e2f73b8ad4592e22b2 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 14:28:16 +0530
Subject: [PATCH 004/236] Update README.md
---
section3/HelloWorld/README.md | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index e24bf86..09d0e4e 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -15,12 +15,16 @@ Before getting started, ensure that you have the following installed on your sys
- Build aystem as IntelliJ.
- Add JDK as corretto-21 or click on New... and locate your JDK installation directory.
- Click on Create to create the project.
- 4. #### Create A Java Class :
+ 4. #### Create a Java Class :
- In the Project tool window (usually located on the left-hand side), right-click on the src folder.
- Go to New > Java Class.
- Enter a name for your class in the Name field (e.g., MyFirstClass).
- Optionally, you can specify a Package for your class. If you're just starting out, you can leave it as the default package.
- Click OK to create the class.
+ 5. #### Write Your First Java Code :
+ - IntelliJ IDEA will create a Java class file with a template for you.
+ - You can start writing your Java code inside the class.
+
From 6078142c94a77007b099529f2dbc7d9e64258166 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 14:34:04 +0530
Subject: [PATCH 005/236] Update README.md
---
section3/HelloWorld/README.md | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index 09d0e4e..83b6e2c 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -24,7 +24,9 @@ Before getting started, ensure that you have the following installed on your sys
5. #### Write Your First Java Code :
- IntelliJ IDEA will create a Java class file with a template for you.
- You can start writing your Java code inside the class.
-
+ ```java
+
+
From 413b2d7b566a28a24a6eb1aa4030ef3df10f1b20 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 14:37:54 +0530
Subject: [PATCH 006/236] Update README.md
---
section3/HelloWorld/README.md | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index 83b6e2c..a749dd2 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -25,6 +25,18 @@ Before getting started, ensure that you have the following installed on your sys
- IntelliJ IDEA will create a Java class file with a template for you.
- You can start writing your Java code inside the class.
```java
+public class HelloWorld {
+
+ public static void main(String[] args) {
+ System.out.println("Hello Madan");
+ }
+
+}
+```
+6. #### Run Your Java Program :
+ - Click on the green Run icon next to the main method or right-click anywhere inside the main method and select Run 'MyFirstClass.main()'.
+7. #### View Output :
+ - You should see the output Hello, world! printed in the Run tool window at the bottom of the IntelliJ IDEA window.
From ee650f040829ce3b262491aad5ace256b54ee4d3 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 14:42:35 +0530
Subject: [PATCH 007/236] Update README.md
---
section3/HelloWorld/README.md | 14 +++++++++-----
1 file changed, 9 insertions(+), 5 deletions(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index a749dd2..01d1b9b 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -5,23 +5,23 @@ Before getting started, ensure that you have the following installed on your sys
- IntelliJ IDEA (Community or Ultimate edition)
- Java Development Kit (JDK) installed on your machine
### Steps to Create Your First Java Class
- 1. **Open IntelliJ IDEA :** Launch IntelliJ IDEA on your system.
- 2. **Create a New Project :**
+1. #### Open IntelliJ IDEA : Launch IntelliJ IDEA on your system.
+2. #### Create a New Project :
- Click on Create New Project on the welcome screen or go to File > New > Project.
- 3. #### Set Up Your Project :
+3. #### Set Up Your Project :
- Enter a Project Name for your project.
- Choose a Project Location where you want to save your project files.
- Select the Language as Java.
- Build aystem as IntelliJ.
- Add JDK as corretto-21 or click on New... and locate your JDK installation directory.
- Click on Create to create the project.
- 4. #### Create a Java Class :
+4. #### Create a Java Class :
- In the Project tool window (usually located on the left-hand side), right-click on the src folder.
- Go to New > Java Class.
- Enter a name for your class in the Name field (e.g., MyFirstClass).
- Optionally, you can specify a Package for your class. If you're just starting out, you can leave it as the default package.
- Click OK to create the class.
- 5. #### Write Your First Java Code :
+5. #### Write Your First Java Code :
- IntelliJ IDEA will create a Java class file with a template for you.
- You can start writing your Java code inside the class.
```java
@@ -33,10 +33,14 @@ public class HelloWorld {
}
```
+
6. #### Run Your Java Program :
- Click on the green Run icon next to the main method or right-click anywhere inside the main method and select Run 'MyFirstClass.main()'.
7. #### View Output :
- You should see the output Hello, world! printed in the Run tool window at the bottom of the IntelliJ IDEA window.
+ -
+
+Congratulations! You've successfully created and executed your first Java class using IntelliJ IDEA.
From 4ccd5b4121b6dfdcbf46d0f7a9886fcd7089c41d Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 14:45:11 +0530
Subject: [PATCH 008/236] Update README.md
---
section3/HelloWorld/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index 01d1b9b..c0d0c58 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -12,7 +12,7 @@ Before getting started, ensure that you have the following installed on your sys
- Enter a Project Name for your project.
- Choose a Project Location where you want to save your project files.
- Select the Language as Java.
- - Build aystem as IntelliJ.
+ - Build system as IntelliJ.
- Add JDK as corretto-21 or click on New... and locate your JDK installation directory.
- Click on Create to create the project.
4. #### Create a Java Class :
From a5063c1e0c5ee2f50db5064b74dc4f0cf5b76d88 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 14:49:10 +0530
Subject: [PATCH 009/236] Update README.md
---
section3/HelloWorld/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index c0d0c58..ae3524a 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -35,7 +35,7 @@ public class HelloWorld {
```
6. #### Run Your Java Program :
- - Click on the green Run icon next to the main method or right-click anywhere inside the main method and select Run 'MyFirstClass.main()'.
+ - Click on the green Run icon next to the main method or right-click anywhere inside the main method and select Run 'HelloWorld.main()'.
7. #### View Output :
- You should see the output Hello, world! printed in the Run tool window at the bottom of the IntelliJ IDEA window.
-
From a20cafc8b43be3fe856948ea12b2905d14f1b656 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 14:52:12 +0530
Subject: [PATCH 010/236] Update README.md
---
section3/HelloWorld/README.md | 1 -
1 file changed, 1 deletion(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index ae3524a..45ab07f 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -38,7 +38,6 @@ public class HelloWorld {
- Click on the green Run icon next to the main method or right-click anywhere inside the main method and select Run 'HelloWorld.main()'.
7. #### View Output :
- You should see the output Hello, world! printed in the Run tool window at the bottom of the IntelliJ IDEA window.
- -
Congratulations! You've successfully created and executed your first Java class using IntelliJ IDEA.
From 34405d0bd0ca9b952a8ef5b5c61cf7b573a023fb Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 15:00:47 +0530
Subject: [PATCH 011/236] Update README.md
---
section3/HelloWorld/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index 45ab07f..497d7bc 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -37,7 +37,7 @@ public class HelloWorld {
6. #### Run Your Java Program :
- Click on the green Run icon next to the main method or right-click anywhere inside the main method and select Run 'HelloWorld.main()'.
7. #### View Output :
- - You should see the output Hello, world! printed in the Run tool window at the bottom of the IntelliJ IDEA window.
+ - You should see the output Hello Madan printed in the Run tool window at the bottom of the IntelliJ IDEA window.
Congratulations! You've successfully created and executed your first Java class using IntelliJ IDEA.
From cc01a6b5d917c83ae2185ff25f64a0fec9ba40bc Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 15:30:58 +0530
Subject: [PATCH 012/236] Update README.md
---
section3/HelloWorld/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index 497d7bc..0700c81 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -4,7 +4,7 @@ Welcome to our Java course! In this guide, we'll walk you through creating your
Before getting started, ensure that you have the following installed on your system:
- IntelliJ IDEA (Community or Ultimate edition)
- Java Development Kit (JDK) installed on your machine
- ### Steps to Create Your First Java Class
+### Steps to Create Your First Java Class
1. #### Open IntelliJ IDEA : Launch IntelliJ IDEA on your system.
2. #### Create a New Project :
- Click on Create New Project on the welcome screen or go to File > New > Project.
From be50cbdebc98a58d89cdaae6e5f2658d4befb8b2 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 15:33:48 +0530
Subject: [PATCH 013/236] Update README.md
---
section3/HelloWorld/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index 0700c81..070c803 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -37,7 +37,7 @@ public class HelloWorld {
6. #### Run Your Java Program :
- Click on the green Run icon next to the main method or right-click anywhere inside the main method and select Run 'HelloWorld.main()'.
7. #### View Output :
- - You should see the output Hello Madan printed in the Run tool window at the bottom of the IntelliJ IDEA window.
+ - You should see the output "Hello Madan" printed in the Run tool window at the bottom of the IntelliJ IDEA window.
Congratulations! You've successfully created and executed your first Java class using IntelliJ IDEA.
From eb99f0e8ebb092a17b5919297c3eaca04a2a824c Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 16:10:54 +0530
Subject: [PATCH 014/236] Update README.md
---
section3/HelloWorld/README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index 070c803..e560dd0 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -9,7 +9,7 @@ Before getting started, ensure that you have the following installed on your sys
2. #### Create a New Project :
- Click on Create New Project on the welcome screen or go to File > New > Project.
3. #### Set Up Your Project :
- - Enter a Project Name for your project.
+ - Enter a Project Name for your project (HelloWorld).
- Choose a Project Location where you want to save your project files.
- Select the Language as Java.
- Build system as IntelliJ.
@@ -18,7 +18,7 @@ Before getting started, ensure that you have the following installed on your sys
4. #### Create a Java Class :
- In the Project tool window (usually located on the left-hand side), right-click on the src folder.
- Go to New > Java Class.
- - Enter a name for your class in the Name field (e.g., MyFirstClass).
+ - Enter a name for your class in the Name field (e.g., HelloWorld).
- Optionally, you can specify a Package for your class. If you're just starting out, you can leave it as the default package.
- Click OK to create the class.
5. #### Write Your First Java Code :
From 4af66e2fea22c0d8bc7896b7b678350761ab2166 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 16:39:22 +0530
Subject: [PATCH 015/236] Update README.md
---
section3/HelloWorld/README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/section3/HelloWorld/README.md b/section3/HelloWorld/README.md
index e560dd0..f9c5a93 100644
--- a/section3/HelloWorld/README.md
+++ b/section3/HelloWorld/README.md
@@ -2,8 +2,8 @@
Welcome to our Java course! In this guide, we'll walk you through creating your first Java class using IntelliJ IDEA, a powerful integrated development environment (IDE) for Java development.
### Prerequisites
Before getting started, ensure that you have the following installed on your system:
-- IntelliJ IDEA (Community or Ultimate edition)
-- Java Development Kit (JDK) installed on your machine
+- IntelliJ IDEA (Community or Ultimate edition) https://www.jetbrains.com/idea/download/?section=windows
+- Java Development Kit (JDK) installed on your machine https://docs.aws.amazon.com/corretto/latest/corretto-21-ug/downloads-list.html
### Steps to Create Your First Java Class
1. #### Open IntelliJ IDEA : Launch IntelliJ IDEA on your system.
2. #### Create a New Project :
From 38c707aa0183caff9b03e313b38acb36aefde530 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 17:52:09 +0530
Subject: [PATCH 016/236] Create README.md
---
section4/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section4/README.md
diff --git a/section4/README.md b/section4/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section4/README.md
@@ -0,0 +1 @@
+
From 67b34fb75095f49ee3428f4fbe7b773282869230 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 18:11:20 +0530
Subject: [PATCH 017/236] Update README.md
---
section4/README.md | 34 ++++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+)
diff --git a/section4/README.md b/section4/README.md
index 8b13789..51b9657 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -1 +1,35 @@
+# Exploring Core Java Concepts
+## Declaring Feilds in Java Class
+In Java, fields are declared within a class. They represent the state or attributes of objects created from that class. Fields can store data that characterize the objects and are accessible throughout the class.
+Fields are declared within the body of a class. Here's the syntax for declaring fields :
+ ```java
+ public class ClassName {
+ // Instance variables (fields)
+ dataType fieldName1;
+ dataType fieldName2;
+ // ...
+ }
+ ```
+### Example
+ ```java
+ public class Person {
+ // Instance variables (fields)
+ String name;
+ int age;
+ double height;
+ }
+ ```
+#### In the above exapmle
+- name, age, and height are fields of the Person class.
+- Each field has a data type (String, int, double) followed by the field name.
+- These fields represent the characteristics of a person object.
+
+
+
+
+
+
+
+
+
From eb5be10b5b59b79dbdf7acc2ad44e25a2dd5788e Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 18:25:31 +0530
Subject: [PATCH 018/236] Update README.md
---
section4/README.md | 28 ++++++++++++++++++++++++++--
1 file changed, 26 insertions(+), 2 deletions(-)
diff --git a/section4/README.md b/section4/README.md
index 51b9657..f9e97fe 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -21,9 +21,33 @@ Fields are declared within the body of a class. Here's the syntax for declaring
}
```
#### In the above exapmle
-- name, age, and height are fields of the Person class.
+- "name", "age", and "height" are fields of the 'Person' class.
- Each field has a data type (String, int, double) followed by the field name.
-- These fields represent the characteristics of a person object.
+- These fields represent the characteristics of a 'Person' object.
+### Field Types
+#### Instance Variables or Non-Statis variables :
+Instance variables are associated with objects of the class. Each instance (object) of the class has its own copy of instance variables.
+```java
+public class MyClass {
+ public int instanceVariable; // Instance variable
+}
+```
+#### Static Variables :
+Static variables are shared among all instances of a class. They are associated with the class rather than with any object.
+```java
+public class MyClass {
+ public static int staticVariable; // Static variable
+}
+```
+### Access Modifiers
+Java provides access modifiers to control the visibility of fields. The commonly used access modifiers are :
+- **public :** The field is accessible from any other class.
+- **private :** The field is accessible only within the same class.
+- **protected :** The field is accessible within the same package and subclasses.
+- **default (no modifier) :** The field is accessible only within the same package.
+
+
+
From 732f4804821f15e88850344f14e22d5617687fec Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 18:31:24 +0530
Subject: [PATCH 019/236] Update README.md
---
section4/README.md | 13 ++++++++++++-
1 file changed, 12 insertions(+), 1 deletion(-)
diff --git a/section4/README.md b/section4/README.md
index f9e97fe..32cc100 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -25,7 +25,7 @@ Fields are declared within the body of a class. Here's the syntax for declaring
- Each field has a data type (String, int, double) followed by the field name.
- These fields represent the characteristics of a 'Person' object.
### Field Types
-#### Instance Variables or Non-Statis variables :
+#### Instance Variables or Non-Static Variables :
Instance variables are associated with objects of the class. Each instance (object) of the class has its own copy of instance variables.
```java
public class MyClass {
@@ -45,6 +45,17 @@ Java provides access modifiers to control the visibility of fields. The commonly
- **private :** The field is accessible only within the same class.
- **protected :** The field is accessible within the same package and subclasses.
- **default (no modifier) :** The field is accessible only within the same package.
+### Example
+```java
+public class MyClass {
+ public int publicField;
+ private int privateField;
+ protected int protectedField;
+ int defaultField; // Default access modifier
+}
+```
+### Conclusion
+Declaring fields in a Java class is a fundamental aspect of object-oriented programming. Fields represent the state of objects and store data that characterize them. Understanding how to declare and use fields is crucial for building Java applications.
From 8e72f0aca642ee4fdd5b4184a26bf0da93c91ecd Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 18:54:49 +0530
Subject: [PATCH 020/236] Update README.md
---
section4/README.md | 35 +++++++++++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
diff --git a/section4/README.md b/section4/README.md
index 32cc100..b052852 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -58,6 +58,41 @@ public class MyClass {
Declaring fields in a Java class is a fundamental aspect of object-oriented programming. Fields represent the state of objects and store data that characterize them. Understanding how to declare and use fields is crucial for building Java applications.
+# Declaring Methods in Java Class
+In Java, methods are functions defined within a class. They encapsulate behavior and define what objects of that class can do. Methods are used to perform specific tasks and manipulate the state of objects.
+## Declaring Methods
+```java
+public class ClassName {
+ // Method declaration
+ public returnType methodName() {
+ // Method body
+ // Perform tasks here
+ return value; // Return statement (if returnType is not void)
+ }
+}
+```
+#### Example
+```
+public Car{
+
+String name;
+String color;
+double horsePower;
+
+public void startCar(){
+
+System.out.println("Car Started Successfully !);
+
+}
+
+public String stopCar(){
+String output = "Car stopped";
+ return output;
+}
+
+
+
+
From 47128845a821f21c487aa677fae796591634aebb Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 19:09:11 +0530
Subject: [PATCH 021/236] Update README.md
---
section4/README.md | 51 ++++++++++++++++++++++++++++++++++++----------
1 file changed, 40 insertions(+), 11 deletions(-)
diff --git a/section4/README.md b/section4/README.md
index b052852..9327d09 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -72,23 +72,52 @@ public class ClassName {
}
```
#### Example
-```
-public Car{
+```java
+public class Car {
-String name;
-String color;
-double horsePower;
+ String model;
+ String color;
+ int horsePower;
-public void startCar(){
+ public void startCar() {
+ System.out.println("Vehicle started...");
+ }
-System.out.println("Car Started Successfully !);
+ public String stopCar() {
+ String output = "Vehicle stopped...";
+ return output;
+ }
}
-
-public String stopCar(){
-String output = "Car stopped";
- return output;
+```
+## Method With Parameters
+```java
+public class ClassName {
+ // Method declaration
+ public returnType methodName(parameterType parameter1, parameterType parameter2, ...) {
+ // Method body
+ // Perform tasks here
+ return value; // Return statement (if returnType is not void)
+ }
}
+```
+### Example
+```java
+public class AithmeticOperations {
+
+ public returnType add(int num1, int num2) {
+ int sum=num1+num2;
+ return sum;
+ }
+}
+```
+##### In the above example :
+- 'add' is a method of the 'AithmeticOperations' class.
+- It takes two parameters (num1 and num2) of type int.
+-
+
+
+
From 40d1a56063fe3f9c1516cc7e97c0ff52beff4f53 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 19:11:35 +0530
Subject: [PATCH 022/236] Update README.md
---
section4/README.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/section4/README.md b/section4/README.md
index 9327d09..9ff6032 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -105,8 +105,8 @@ public class ClassName {
```java
public class AithmeticOperations {
- public returnType add(int num1, int num2) {
- int sum=num1+num2;
+ public int add(int num1, int num2) {
+ int sum =num1+num2;
return sum;
}
}
@@ -114,7 +114,7 @@ public class AithmeticOperations {
##### In the above example :
- 'add' is a method of the 'AithmeticOperations' class.
- It takes two parameters (num1 and num2) of type int.
--
+- It returns the sum of num1 and num2 as an int.
From c055b786058d0385132d39e8f7f922752657cbde Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 20:03:25 +0530
Subject: [PATCH 023/236] Update README.md
---
section4/README.md | 70 +++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 69 insertions(+), 1 deletion(-)
diff --git a/section4/README.md b/section4/README.md
index 9ff6032..e5ec48e 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -104,7 +104,7 @@ public class ClassName {
### Example
```java
public class AithmeticOperations {
-
+
public int add(int num1, int num2) {
int sum =num1+num2;
return sum;
@@ -116,6 +116,74 @@ public class AithmeticOperations {
- It takes two parameters (num1 and num2) of type int.
- It returns the sum of num1 and num2 as an int.
+## Method Invocation
+
+If method is static and present in the same class then call that method with method name.
+```java
+public class AithmeticOperations {
+ public static void main(String[]args){
+ int result=add(10, 20); // Method Invocation
+ }
+ public int add(int num1, int num2) {
+ return num1 + num2;
+ }
+}
+```
+If method is static and present outside of the class then call that with ClassName.methodName.
+```java
+public class AithmeticOperations {
+ public static void main(String[]args){
+ int result=Addition.add(10, 20); // Method Invocation
+ System.out.println(result);
+ }
+}
+
+public class Addition{
+ public int add(int num1, int num2) {
+ return num1 + num2;
+ }
+}
+```
+## Object Creation
+Once you have defined the class, you can create an object of that class using 'new' keyword.
+If the method is Non-Static and present inside the same calss then call that method with ObjectReferenceVariable.methodName
+```java
+public class AithmeticOperations {
+ public static void main(String[]args){
+ // Create Object of class where the method is present.
+ AithmeticOperations aithmeticOperations=new AithmeticOperations(); //Object Creation
+ // aithmeticOperations is Object reference variable
+ int result=aithmeticOperations.add(10, 20); // Method Invocation
+ System.out.println(result);
+ }
+ public int add(int num1, int num2) {
+ return num1 + num2;
+ }
+}
+```
+If the method is Non-Static and present outside calss then call that method with ObjectReferenceVariable.methodName
+```java
+public class AithmeticOperations {
+ public static void main(String[]args){
+ // Create Object of class where the method is present.
+ Addition addition=new Addition(); //Object Creation
+ // addition is Object reference variable
+ int result=addition.add(10, 20); // Method Invocation
+ System.out.println(result);
+ }
+}
+
+public class Addition{
+ public int add(int num1, int num2) {
+ return num1 + num2;
+ }
+}
+
+
+
+
+
+
From f328755c5bc9914833ac25df65e746fb8c5bc95b Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 20:07:22 +0530
Subject: [PATCH 024/236] Update README.md
---
section4/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section4/README.md b/section4/README.md
index e5ec48e..bcb2508 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -145,7 +145,7 @@ public class Addition{
}
```
## Object Creation
-Once you have defined the class, you can create an object of that class using 'new' keyword.
+Once you have defined the class, you can create an object of that class using 'new' keyword. The new keyword allocates memory for the object and returns to a reference it.
If the method is Non-Static and present inside the same calss then call that method with ObjectReferenceVariable.methodName
```java
public class AithmeticOperations {
From 3e67499751f7d216c7ba64f39d93c5f0de80d26c Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 21:03:19 +0530
Subject: [PATCH 025/236] Update README.md
---
section4/README.md | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/section4/README.md b/section4/README.md
index bcb2508..0fb3ce6 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -146,6 +146,22 @@ public class Addition{
```
## Object Creation
Once you have defined the class, you can create an object of that class using 'new' keyword. The new keyword allocates memory for the object and returns to a reference it.
+```java
+public class Employee {
+ public static void main(String[]args){
+ Employee obj=new Employee();// Object Creation
+
+ //obj is the Object reference variable.
+ // The Object reference variable name should always a class name but in camel case.
+ Employee employee=new Employee();// Objcet creation
+
+ //This creates a new object of the Employee class and assigns its to the employee variable. The new keyword calls the constructor of the class to intialize the object.
+
+ }
+}
+```
+
+
If the method is Non-Static and present inside the same calss then call that method with ObjectReferenceVariable.methodName
```java
public class AithmeticOperations {
From c906f3abe72362003b86b4f145ea1db72c8477cf Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 21:04:58 +0530
Subject: [PATCH 026/236] Update README.md
---
section4/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section4/README.md b/section4/README.md
index 0fb3ce6..42a3d2f 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -145,7 +145,7 @@ public class Addition{
}
```
## Object Creation
-Once you have defined the class, you can create an object of that class using 'new' keyword. The new keyword allocates memory for the object and returns to a reference it.
+Once you have defined the class, you can create an object of that class using 'new' keyword. The 'new' keyword allocates memory for the object and returns a reference to it.
```java
public class Employee {
public static void main(String[]args){
From 8260e7eca238861f81c1172d29621b368d1e082d Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 19 Feb 2024 21:07:12 +0530
Subject: [PATCH 027/236] Update README.md
---
section4/README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/section4/README.md b/section4/README.md
index 42a3d2f..6eb1013 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -162,7 +162,7 @@ public class Employee {
```
-If the method is Non-Static and present inside the same calss then call that method with ObjectReferenceVariable.methodName
+If the method is Non-Static and present inside the same calss then call that method with ObjectReferenceVariable.methodName()
```java
public class AithmeticOperations {
public static void main(String[]args){
@@ -177,7 +177,7 @@ public class AithmeticOperations {
}
}
```
-If the method is Non-Static and present outside calss then call that method with ObjectReferenceVariable.methodName
+If the method is Non-Static and present outside calss then call that method with ObjectReferenceVariable.methodName()
```java
public class AithmeticOperations {
public static void main(String[]args){
From 7472521e5526c0ebbb30e8fb3ec498237bd0ca89 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 10:30:24 +0530
Subject: [PATCH 028/236] Update README.md
---
section4/README.md | 56 ++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 56 insertions(+)
diff --git a/section4/README.md b/section4/README.md
index 6eb1013..9d5d5fa 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -194,6 +194,62 @@ public class Addition{
return num1 + num2;
}
}
+```
+# Constructors in Java
+
+In Java, a constructor is a special type of method that is automatically called when an instance of a class is created. Constructors are used to initialize the newly created object.
+
+## Types of Constructors
+
+### Default Constructor
+
+A default constructor is one that doesn't take any parameters. If you don't explicitly define a constructor for a class, Java provides a default constructor that initializes member variables to their default values (e.g., 0 for numeric types, null for reference types).
+
+```java
+public class MyClass {
+ // Default constructor
+ public MyClass() {
+ // Initialization code here
+ }
+}
+```
+#### Example
+```java
+public class Employee {
+ public Employee() {
+ System.out.println("Object is getting created");
+ }
+}
+```
+
+### Parameterized Constructor
+A parameterized constructor is one that takes one or more parameters. It allows you to initialize instance variables with values passed as arguments during object creation.
+```java
+public class MyClass {
+ private int myVariable;
+
+ // Parameterized constructor
+ public MyClass(int value) {
+ this.myVariable = value;
+ }
+}
+```
+#### Example
+```java
+public class Employee {
+ public String name;
+ public String empId;
+
+ public Employee(String empName, String id) {
+ this.name = empName;
+ this.empId=id;
+ }
+}
+```
+
+
+
+
From 6281f40e4107e671a3912645552afa9dff066b32 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 11:17:54 +0530
Subject: [PATCH 029/236] Update README.md
---
section4/README.md | 55 ++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 55 insertions(+)
diff --git a/section4/README.md b/section4/README.md
index 9d5d5fa..fd88336 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -211,6 +211,7 @@ public class MyClass {
public MyClass() {
// Initialization code here
}
+MyClass myClass= new MyClass();// Object Creation to call default constructor
}
```
#### Example
@@ -219,6 +220,7 @@ public class Employee {
public Employee() {
System.out.println("Object is getting created");
}
+Employee employee= new Employee();
}
```
@@ -232,6 +234,8 @@ public class MyClass {
public MyClass(int value) {
this.myVariable = value;
}
+MyClass myClass= new MyClass(20);// Object Creation to call parameterized constructor
+
}
```
#### Example
@@ -244,8 +248,59 @@ public class Employee {
this.name = empName;
this.empId=id;
}
+Employee employee=new Employee("Suresh","A4678");
+}
+```
+### Constructor Overloading
+Java allows you to have multiple constructors with different parameter lists in a class. This is known as constructor overloading.
+```java
+public class MyClass {
+ private int myVariable;
+
+ // Default constructor
+ public MyClass() {
+ // Initialization code here
+ }
+
+ // Parameterized constructor
+ public MyClass(int value) {
+ this.myVariable = value;
+ }
+
+ // Another parameterized constructor
+ public MyClass(String name, int age) {
+ // Initialization code here
+ }
+MyClass myClass= new MyClass();// To call default constructor
+MyClass myClass= new MyClass(20);// To call Constructor with one 'int' parameter
+MyClass myClass= new MyClass("Ramesh",20);// To call Constructor with one 'String' parameter and one 'int' parameter.
+
}
```
+#### Example
+```java
+public class Employee {
+ public int name;
+ public String age;
+
+ public Employee() {
+ // Initialization code here
+ }
+
+ public Employee(int value) {
+ this.name = value;
+ }
+
+ public Employee(String name, int age) {
+ this.name=name;
+ this.age=age;
+ }
+Employee employee=new Employee();
+Employee employee=new Employee(20);
+Employee employee=new Employee("Suresh",20);
+}
+```
+
From 04d93dcbc2dd4bc982affa2173b3d42f0768a8fc Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 11:23:10 +0530
Subject: [PATCH 030/236] Update README.md
---
section4/README.md | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/section4/README.md b/section4/README.md
index fd88336..8df2423 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -271,9 +271,9 @@ public class MyClass {
public MyClass(String name, int age) {
// Initialization code here
}
-MyClass myClass= new MyClass();// To call default constructor
-MyClass myClass= new MyClass(20);// To call Constructor with one 'int' parameter
-MyClass myClass= new MyClass("Ramesh",20);// To call Constructor with one 'String' parameter and one 'int' parameter.
+MyClass myClass1= new MyClass();// To call default constructor
+MyClass myClass2= new MyClass(20);// To call Constructor with one 'int' parameter
+MyClass myClass3= new MyClass("Ramesh",20);// To call Constructor with one 'String' parameter and one 'int' parameter.
}
```
@@ -295,9 +295,9 @@ public class Employee {
this.name=name;
this.age=age;
}
-Employee employee=new Employee();
-Employee employee=new Employee(20);
-Employee employee=new Employee("Suresh",20);
+Employee employee1=new Employee();
+Employee employee2=new Employee(20);
+Employee employee3=new Employee("Suresh",20);
}
```
From ded64b5a93cdf7cb942e74d570f053680a53d56f Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 12:03:09 +0530
Subject: [PATCH 031/236] Update README.md
---
section4/README.md | 41 +++++++++++++++++++++++++++++++++++++++++
1 file changed, 41 insertions(+)
diff --git a/section4/README.md b/section4/README.md
index 8df2423..fe016f5 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -300,6 +300,47 @@ Employee employee2=new Employee(20);
Employee employee3=new Employee("Suresh",20);
}
```
+### Constructor Chaining
+Constructor chaining allows one constructor to call another constructor in the same class. This is achieved using the 'this()' keyword.
+```java
+public class MyClass {
+ private int myVariable;
+ private String myString;
+
+ // Parameterized constructor
+ public MyClass(int value) {
+ this(value, "Default");
+ }
+
+ // Another parameterized constructor
+ public MyClass(int value, String str) {
+ this.myVariable = value;
+ this.myString = str;
+ }
+MyClass myClass=new MyClass(10);
+}
+```
+#### Example
+```java
+public class Employee {
+ private int id;
+ private String name;
+
+ public Employee() {
+ this(282717, "Suresh");
+ }
+
+ public Employee(int value, String str) {
+ this.id = value;
+ this.name = str;
+ }
+Employee employee=new Employee();
+}
+```
+#### Conclusion
+Constructors are essential for initializing objects in Java. Understanding their types and usage is crucial for creating well-structured and efficient Java programs.
+
+
From fb76228bac74bbb1e94eabf37e2967eb8019effb Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 12:28:07 +0530
Subject: [PATCH 032/236] Update README.md
---
section4/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section4/README.md b/section4/README.md
index fe016f5..5c58bbf 100644
--- a/section4/README.md
+++ b/section4/README.md
@@ -1,4 +1,4 @@
-# Exploring Core Java Concepts
+# Basic Core Java Concepts
## Declaring Feilds in Java Class
In Java, fields are declared within a class. They represent the state or attributes of objects created from that class. Fields can store data that characterize the objects and are accessible throughout the class.
Fields are declared within the body of a class. Here's the syntax for declaring fields :
From 6a89db5933fc39b667ad9d3af43cb2245d55a328 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 12:37:43 +0530
Subject: [PATCH 033/236] Create README.md
---
section5/src/README.md | 5 +++++
1 file changed, 5 insertions(+)
create mode 100644 section5/src/README.md
diff --git a/section5/src/README.md b/section5/src/README.md
new file mode 100644
index 0000000..f3544b9
--- /dev/null
+++ b/section5/src/README.md
@@ -0,0 +1,5 @@
+# Comments in Java
+Comments are essential for making your code more understandable to yourself and others who might read it later. They provide context, explanations, and documentation for your code.
+## Types of Comments
+### Single Line Comments
+Single line comments start with `//` and are used for short explanations.
From eccc98183df1fcdc39a07fd4cbc662063ef4a305 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 12:40:10 +0530
Subject: [PATCH 034/236] Delete section5/src/README.md
---
section5/src/README.md | 5 -----
1 file changed, 5 deletions(-)
delete mode 100644 section5/src/README.md
diff --git a/section5/src/README.md b/section5/src/README.md
deleted file mode 100644
index f3544b9..0000000
--- a/section5/src/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# Comments in Java
-Comments are essential for making your code more understandable to yourself and others who might read it later. They provide context, explanations, and documentation for your code.
-## Types of Comments
-### Single Line Comments
-Single line comments start with `//` and are used for short explanations.
From aa3bd762e5828707512053c04fc5bd4cecd3b469 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 12:40:49 +0530
Subject: [PATCH 035/236] Create README.md
---
section5/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section5/README.md
diff --git a/section5/README.md b/section5/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section5/README.md
@@ -0,0 +1 @@
+
From 968ece68dc8dd0cba1b49632835abfd9db1165f9 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 12:42:26 +0530
Subject: [PATCH 036/236] Update README.md
---
section5/README.md | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/section5/README.md b/section5/README.md
index 8b13789..6be5662 100644
--- a/section5/README.md
+++ b/section5/README.md
@@ -1 +1,5 @@
+# Comments in Java
+Comments are essential for making your code more understandable to yourself and others who might read it later. They provide context, explanations, and documentation for your code.
+## Types of Comments
+### Single Line Comments
From 3e9c4fea72199af2983e73b1d47700462d48e3db Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 12:43:47 +0530
Subject: [PATCH 037/236] Update README.md
---
section5/README.md | 3 +++
1 file changed, 3 insertions(+)
diff --git a/section5/README.md b/section5/README.md
index 6be5662..89dbf7b 100644
--- a/section5/README.md
+++ b/section5/README.md
@@ -2,4 +2,7 @@
Comments are essential for making your code more understandable to yourself and others who might read it later. They provide context, explanations, and documentation for your code.
## Types of Comments
### Single Line Comments
+Single line comments start with `//` and are used for short explanations.
+```java
+
From a9a09306f9d8a74cd6df267f66968856b0f3e371 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 12:45:45 +0530
Subject: [PATCH 038/236] Update README.md
---
section5/README.md | 27 +++++++++++++++++++++++++++
1 file changed, 27 insertions(+)
diff --git a/section5/README.md b/section5/README.md
index 89dbf7b..00c497d 100644
--- a/section5/README.md
+++ b/section5/README.md
@@ -4,5 +4,32 @@ Comments are essential for making your code more understandable to yourself and
### Single Line Comments
Single line comments start with `//` and are used for short explanations.
```java
+public class SingleLineCommentDemo {
+ int age; // Represent the age of the Customer
+
+ // Maximum number of login retry attempts allowed
+ static final int MAX_RETRY_ATTEMPTS = 3;
+
+ // main method is used to start the Java program
+ public static void main(String[] args) {
+
+ // Y indicates YES
+ char y = 'Y';
+ // N indicates NO
+ char n = 'N';
+
+ sum(12, 8);
+
+ }
+
+ public static void sum (int num1, int num2){
+ int num3 = num1 + num2;
+ // System.out.println(num3);
+ }
+
+}
+```
+### Multi-line Comments
+Multi-line comments are enclosed within `/* */` and are useful for longer explanations or commenting out blocks of code.
From 47fdee76dc976ab2ead037de37626a354b2ee9b3 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 12:47:14 +0530
Subject: [PATCH 039/236] Update README.md
---
section5/README.md | 32 ++++++++++++++++++++++++++++++++
1 file changed, 32 insertions(+)
diff --git a/section5/README.md b/section5/README.md
index 00c497d..0f90e23 100644
--- a/section5/README.md
+++ b/section5/README.md
@@ -32,4 +32,36 @@ public class SingleLineCommentDemo {
```
### Multi-line Comments
Multi-line comments are enclosed within `/* */` and are useful for longer explanations or commenting out blocks of code.
+```java
+public class MultiLineCommentsDemo {
+
+ /*
+ Based on business requirements, the end user is
+ allowed to retry a maximum of 3 login attempts.
+ Using the below constant, the same is going to be
+ controlled. If the requirement changes, then change
+ the below value
+ */
+ static final int MAX_RETRY_ATTEMPTS = 3;
+
+ public static void main(String[] args) {
+ MultiLineCommentsDemo obj = new MultiLineCommentsDemo();
+ double totalArea = obj.calculateRectangleArea(24.5, 34.6);
+ System.out.println(totalArea);
+ }
+
+ /*
+ This method calculates the area of the rectangle based
+ on given length and width. The logic it is going to have
+ is multiply two given input method arguments and return
+ the same to the caller
+ */
+ public double calculateRectangleArea (double length, double width) {
+ return length*width;
+ }
+
+}
+```
+### Javadoc Comments
+Javadoc comments start with `/**` and are used to generate documentation for your code.
From 71a3f2313b802ae24d6f46279c65e8268212b3df Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 13:00:04 +0530
Subject: [PATCH 040/236] Update README.md
---
section5/README.md | 45 ++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 44 insertions(+), 1 deletion(-)
diff --git a/section5/README.md b/section5/README.md
index 0f90e23..1e4987f 100644
--- a/section5/README.md
+++ b/section5/README.md
@@ -1,4 +1,4 @@
-# Comments in Java
+# Comments in Java
Comments are essential for making your code more understandable to yourself and others who might read it later. They provide context, explanations, and documentation for your code.
## Types of Comments
### Single Line Comments
@@ -64,4 +64,47 @@ public class MultiLineCommentsDemo {
```
### Javadoc Comments
Javadoc comments start with `/**` and are used to generate documentation for your code.
+```java
+/**
+ * This is a sample class to show demo about
+ * javadoc
+ *
+ *
+ * This is a sample demo of
+ * paragraph
+ *
+ *
+ * @see MultiLineCommentsDemo
+ * @author Madan Reddy
+ * @since 1.0
+ */
+public class JavaDocCommentsDemo {
+
+ public static void main(String[] args) {
+
+ }
+
+
+ /**
+ * Take two {@code int} numbers as input
+ * and add them
+ *
+ * For example, 2+3 =5
+ *
+ * @param num1 Represent first number
+ * @param num2 Represent second number
+ * @return sum value of first and second number
+ */
+ public int sum (int num1, int num2) {
+ return num1+num2;
+ }
+
+}
+```
+### Conclusion
+- In Java, comments play a crucial role in making your code understandable and maintainable. They provide insights into the logic, purpose, and functionality of your code, helping developers navigate through complex systems with ease. By using different types of comments such as single line, multi-line, and Javadoc comments, you can effectively document your codebase.
+- Remember to follow best practices such as clarity, conciseness, relevance, and keeping comments up-to-date to ensure their effectiveness
+- Keep coding, keep commenting, and make your Java projects shine! ππ©βπ»π¨βπ»
+
+
From dbadaf8394b12d46a0cce37d48500eb4c590cf61 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 14:49:26 +0530
Subject: [PATCH 041/236] Create README.md
---
section6/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section6/README.md
diff --git a/section6/README.md b/section6/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section6/README.md
@@ -0,0 +1 @@
+
From 7277b464ca3b353b3e99916af49350fc7c8305e0 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 15:27:54 +0530
Subject: [PATCH 042/236] Update README.md
---
section6/README.md | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/section6/README.md b/section6/README.md
index 8b13789..01b3915 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -1 +1,7 @@
-
+# Strings in Java
+Strings are one of the most commonly used data types in Java, representing a sequence of characters. In Java, strings are immutable, meaning their values cannot be changed after they are created.
+## Creating Strings
+### Using String Literal
+```
+String str="Hello World ! π";
+```
From 05a7f7bde78cce34d7c55bdf33d461542032ce4f Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 15:34:03 +0530
Subject: [PATCH 043/236] Update README.md
---
section6/README.md | 14 +++++++++++++-
1 file changed, 13 insertions(+), 1 deletion(-)
diff --git a/section6/README.md b/section6/README.md
index 01b3915..3b760d9 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -2,6 +2,18 @@
Strings are one of the most commonly used data types in Java, representing a sequence of characters. In Java, strings are immutable, meaning their values cannot be changed after they are created.
## Creating Strings
### Using String Literal
+```java
+String str="Hello, World! π";
```
-String str="Hello World ! π";
+### Using the new Keyword
+```java
+String str=new String("Hello, World! π";
+```
+### Using 'StringBuilder' or 'StringBuffer'
+```java
+StringBuilder stringBuilder = new StringBuilder();
+stringBuilder.append("Hello");
+stringBuilder.append(", ");
+stringBuilder.append("World! π ");
+String str = stringBuilder.toString();
```
From 73bf5b59aae6d880eae613b2144a715023df8005 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 16:52:57 +0530
Subject: [PATCH 044/236] Update README.md
---
section6/README.md | 45 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 45 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index 3b760d9..3f83731 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -17,3 +17,48 @@ stringBuilder.append(", ");
stringBuilder.append("World! π ");
String str = stringBuilder.toString();
```
+### String Pool
+```java
+public class StringPool {
+
+ public static void main(String[] args) {
+ String str1 = "Hello";
+ String str2="Hello";
+ String str3="hai";
+ Sytsem.out.println(str1==str2);// true, because content of 'str1' and 'str2' is same thats why both referring to the same memory loaction.
+
+ Sytsem.out.println(str1.hashCode());// eg. 151516
+ Sytsem.out.println(str2.hashCode()); // eg. 151516 // both 'HashCode' values are same because content of the both strings are same.
+
+
+ String obj1=new String("hello");
+ String obj2=new String("hello");
+ String Obj3=new String("hai");
+
+ Sytsem.out.println(obj1.hashCode());//eg. 121212
+ Sytsem.out.println(obj2.hashCode());//eg. 121212
+ Sytsem.out.println(obj3.hashCode());//eg. 124566
+
+ Sytsem.out.println(obj1==obj2);// false, even if HashCode values are same both objects are not stored same memory loaction.
+
+ }
+
+}
+```
+## String.intern()
+The `intern()` method in the `String` class is a useful tool for managing memory efficiently when working with strings in Java. It returns a canonical representation of the string object, which means that for any two strings `s` and `t`, `s.intern() == t.intern()` holds true if and only if `s.equals(t)`.
+### Example
+```java
+public class Main {
+ public static void main(String[] args) {
+ String s1 = "hello";
+ String s2 = new String("hello");
+
+ String internedS1 = s1.intern();
+ String internedS2 = s2.intern();
+
+ // Prints: true
+ System.out.println(internedS1 == internedS2);
+ }
+}
+```
From 5665edb0ca58642b178c6f378c6f68ebee117f15 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 17:28:44 +0530
Subject: [PATCH 045/236] Update README.md
---
section6/README.md | 56 +++++++++++++++++++++++++++++++++++++++++-----
1 file changed, 50 insertions(+), 6 deletions(-)
diff --git a/section6/README.md b/section6/README.md
index 3f83731..d72a028 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -49,16 +49,60 @@ public class StringPool {
The `intern()` method in the `String` class is a useful tool for managing memory efficiently when working with strings in Java. It returns a canonical representation of the string object, which means that for any two strings `s` and `t`, `s.intern() == t.intern()` holds true if and only if `s.equals(t)`.
### Example
```java
-public class Main {
+public class InternMethodDemo {
+
public static void main(String[] args) {
+ String hello = "Hello";
+ String obj = new String("Hello").intern();
+ System.out.println(hello==obj); // false
+
String s1 = "hello";
String s2 = new String("hello");
+ System.out.println(s1==s2);
+ String s3 = s2.intern();
+ System.out.println(s1==s3); //true
+ }
+
+}
+```
+## String.concat()
+The `concat()` method in Java is used to concatenate one string to the end of another string. It returns a new string that represents the concatenation of the two strings.
+```java
+public class Concat {
+ public static void main(String[] args) {
+ String str1 = "Hello";
+ String str2 = " World!";
- String internedS1 = s1.intern();
- String internedS2 = s2.intern();
-
- // Prints: true
- System.out.println(internedS1 == internedS2);
+ String result = str1.concat(str2);
+ System.out.println(result); // Output: Hello World!
}
}
```
+## Escape Sequence Characters and Unicode Character Values in Strings
+- In programming, especially when working with strings, it's essential to understand escape sequence characters and Unicode character values. These elements allow developers to represent special characters or control sequences within a string.
+- This repository provides a comprehensive reference guide for escape sequence characters and Unicode character values, along with examples demonstrating their usage in various programming languages.
+### Escape Sequence Characters
+Escape sequence characters are special characters that are preceded by a backslash (\) in a string. They represent characters that are difficult or impossible to represent directly in code. Common escape sequence characters include :
+- `\n` - Newline
+- `\t` - Tab
+- `\r` - Carriage return
+- `\\` - Backslash
+- `\"` - Double quote
+- `\'` - Single quote
+- `\b` - Backspace
+- `\f` - Form feed
+- `\v` - Vertical tab
+- `\xhh` - ASCII character represented by hexadecimal value `hh`
+- `\uhhhh` - Unicode character represented by hexadecimal value `hhhh`
+- `\Uhhhhhhhh` - Unicode character represented by hexadecimal value `hhhhhhhh`
+### Unicode Character Values
+Unicode character values represent characters from various writing systems and symbol sets. These values are commonly used to include special characters or symbols in strings. Examples include :
+- `\uXXXX` - Unicode character represented by hexadecimal value `XXXX`
+- `\UXXXXXXXX` - Unicode character represented by hexadecimal value `XXXXXXXX`
+#### Example
+```java
+
+
+
+
+
From 217f7b94f166aa24c9a9bec81c7eb665659d313b Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 17:36:44 +0530
Subject: [PATCH 046/236] Update README.md
---
section6/README.md | 26 ++++++++++++++++++++++++--
1 file changed, 24 insertions(+), 2 deletions(-)
diff --git a/section6/README.md b/section6/README.md
index d72a028..b312e55 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -45,7 +45,7 @@ public class StringPool {
}
```
-## String.intern()
+## String.intern() Method in Java
The `intern()` method in the `String` class is a useful tool for managing memory efficiently when working with strings in Java. It returns a canonical representation of the string object, which means that for any two strings `s` and `t`, `s.intern() == t.intern()` holds true if and only if `s.equals(t)`.
### Example
```java
@@ -65,7 +65,7 @@ public class InternMethodDemo {
}
```
-## String.concat()
+## String.concat() Method in Java
The `concat()` method in Java is used to concatenate one string to the end of another string. It returns a new string that represents the concatenation of the two strings.
```java
public class Concat {
@@ -101,6 +101,28 @@ Unicode character values represent characters from various writing systems and s
- `\UXXXXXXXX` - Unicode character represented by hexadecimal value `XXXXXXXX`
#### Example
```java
+public class EscapeSeqDemo {
+
+ public static void main(String[] args) {
+ String name = "\"Madan\"";
+ System.out.println(name);// Output : "Madan"
+
+ String m = "\u004D";
+ System.out.println(m);// Output : M
+ String unicodeName = "\u004Dadan\u0021";
+ System.out.println(unicodeName);// Output : Madan!
+ }
+
+}
+```
+## String.length() Method in Java
+The `length()` method in Java is a part of the `String` class. It returns the length of the string - the number of characters in the string.
+### Parameters
+This method does not take any parameters
+### Return Value
+The length() method returns an integer value representing the number of characters in the string.
+#### Example
+
From 0bd560c9312bd788abf96d78b7099bbcf218f387 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 17:54:06 +0530
Subject: [PATCH 047/236] Update README.md
---
section6/README.md | 35 +++++++++++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index b312e55..18bcc83 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -122,6 +122,41 @@ This method does not take any parameters
### Return Value
The length() method returns an integer value representing the number of characters in the string.
#### Example
+```java
+public class LengthMethodDemo {
+
+ public static void main(String[] args) {
+ String str1 = "Hello";
+ String str2 = "World";
+ String combined = str1+ " "+str2;
+
+ int length1 = str1.length();
+ int length2 = str2.length();
+ int length3 = combined.length();
+
+ int emptyLength = "".length();
+ int length4 = "Hello".length();
+
+ System.out.println(combined);// Output : 11
+ System.out.println(emptyLength);// Output : 0
+ }
+}
+```
+### Usage
+The length() method is commonly used to find the length of a string in Java. It is particularly useful when you need to validate input length, iterate over characters in a string, or perform other string manipulation tasks.
+### Notes
+- The length of a string is equal to the number of Unicode code units in the string.
+- This method returns 0 if the string is empty ("").
+### Conclusion π
+- The length() method in Java's String class is a simple yet powerful tool for determining the length of a string. With its straightforward syntax and predictable behavior, it provides developers with a convenient way to retrieve the number of characters in a string. Whether you're validating user input, iterating through characters, or performing string manipulation tasks, 'length()' is there to help you get the job done efficiently.
+- So go ahead, leverage the length() method in your Java projects and let it simplify your string handling tasks! π
+## String.equals() Method in Java
+The `equals()` method in Java is used to compare the contents of two strings. It returns `true` if the strings are equal, and `false` otherwise.
+#### Example
+
+
+
+
From 9ae330be11cbe2337a6b55bf3c980e1f440de46a Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 18:15:55 +0530
Subject: [PATCH 048/236] Update README.md
---
section6/README.md | 43 ++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 42 insertions(+), 1 deletion(-)
diff --git a/section6/README.md b/section6/README.md
index 18bcc83..92d944b 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -144,7 +144,7 @@ public class LengthMethodDemo {
```
### Usage
The length() method is commonly used to find the length of a string in Java. It is particularly useful when you need to validate input length, iterate over characters in a string, or perform other string manipulation tasks.
-### Notes
+### Notes βοΈ
- The length of a string is equal to the number of Unicode code units in the string.
- This method returns 0 if the string is empty ("").
### Conclusion π
@@ -152,7 +152,48 @@ The length() method is commonly used to find the length of a string in Java. It
- So go ahead, leverage the length() method in your Java projects and let it simplify your string handling tasks! π
## String.equals() Method in Java
The `equals()` method in Java is used to compare the contents of two strings. It returns `true` if the strings are equal, and `false` otherwise.
+### Return Value
+Return value of the `equals()` method is 'boolean'.
#### Example
+```java
+public class StringComparisonDemo {
+
+ public static void main(String[] args) {
+
+ String str1 = new String("Hey");
+ String str2 = new String("Hello");
+ String str3 = new String("Hey");
+
+ boolean b1 = str1.equals(str2); // false
+ boolean b2 = str1.equals(str3); // true
+
+ boolean b3 = str1.equals("Hey"); // true
+ boolean b4 = "Hey".equals(str1);// true
+ boolean b5 = "Hey".equals("Hello");// false
+
+ String str4 ="java";
+ String str5 ="JAVA";
+ boolean b6 = str4.equalsIgnoreCase(str5); // true
+
+ }
+
+}
+```
+### Important Notes βοΈ
+- The equals() method is case-sensitive.
+- It's recommended to use equals() to compare strings rather than == operator, which compares references.
+## String.compareTo() Method in Java
+The `compareTo()` method in Java is used to compare two strings lexicographically. It returns an integer value that indicates whether the current string is less than, equal to, or greater than the specified string.
+#### Return Value
+- 0 if the strings are equal.
+- A negative integer if the current string is lexicographically less than the specified string.
+- A positive integer if the current string is lexicographically greater than the specified string.
+#### Example π
+```java
+
+
+
+
From 9720e685d55b7945d5d8693de9a8409e7083ab3a Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 18:28:14 +0530
Subject: [PATCH 049/236] Update README.md
---
section6/README.md | 26 +++++++++++++++++++++-----
1 file changed, 21 insertions(+), 5 deletions(-)
diff --git a/section6/README.md b/section6/README.md
index 92d944b..8fb380c 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -47,7 +47,7 @@ public class StringPool {
```
## String.intern() Method in Java
The `intern()` method in the `String` class is a useful tool for managing memory efficiently when working with strings in Java. It returns a canonical representation of the string object, which means that for any two strings `s` and `t`, `s.intern() == t.intern()` holds true if and only if `s.equals(t)`.
-### Example
+### Example π‘
```java
public class InternMethodDemo {
@@ -99,7 +99,7 @@ Escape sequence characters are special characters that are preceded by a backsla
Unicode character values represent characters from various writing systems and symbol sets. These values are commonly used to include special characters or symbols in strings. Examples include :
- `\uXXXX` - Unicode character represented by hexadecimal value `XXXX`
- `\UXXXXXXXX` - Unicode character represented by hexadecimal value `XXXXXXXX`
-#### Example
+#### Example π‘
```java
public class EscapeSeqDemo {
@@ -121,7 +121,7 @@ The `length()` method in Java is a part of the `String` class. It returns the le
This method does not take any parameters
### Return Value
The length() method returns an integer value representing the number of characters in the string.
-#### Example
+#### Example π‘
```java
public class LengthMethodDemo {
@@ -154,7 +154,7 @@ The length() method is commonly used to find the length of a string in Java. It
The `equals()` method in Java is used to compare the contents of two strings. It returns `true` if the strings are equal, and `false` otherwise.
### Return Value
Return value of the `equals()` method is 'boolean'.
-#### Example
+#### Example π‘
```java
public class StringComparisonDemo {
@@ -188,8 +188,24 @@ The `compareTo()` method in Java is used to compare two strings lexicographicall
- 0 if the strings are equal.
- A negative integer if the current string is lexicographically less than the specified string.
- A positive integer if the current string is lexicographically greater than the specified string.
-#### Example π
+#### Example π‘
```java
+public class StringComparisonDemo {
+
+ public static void main(String[] args) {
+
+ int comparison1 = "java".compareTo("java"); // 0
+ int comparison2 = "java".compareTo("python"); // -6
+ int comparison3 = "python".compareTo("java"); // 6
+
+ }
+
+}
+```
+#### Usage π
+The compareTo() method is useful when you need to compare strings alphabetically or numerically in Java.
+#### Conclusion π
+The compareTo() method in Java is a powerful tool for comparing strings lexicographically. By returning an integer value indicating whether one string is less than, equal to, or greater than another, it facilitates various sorting and comparison tasks in Java programming. Understanding how to use compareTo() effectively can greatly enhance your ability to manipulate and analyze strings in Java applications.
From e0db744c3ce0de40b924d848568c2c24f5b3137d Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 18:34:47 +0530
Subject: [PATCH 050/236] Update README.md
---
section6/README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index 8fb380c..c58a56d 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -206,6 +206,8 @@ public class StringComparisonDemo {
The compareTo() method is useful when you need to compare strings alphabetically or numerically in Java.
#### Conclusion π
The compareTo() method in Java is a powerful tool for comparing strings lexicographically. By returning an integer value indicating whether one string is less than, equal to, or greater than another, it facilitates various sorting and comparison tasks in Java programming. Understanding how to use compareTo() effectively can greatly enhance your ability to manipulate and analyze strings in Java applications.
+## String.charAt() Method in Java
+The `String.charAt()` method in Java returns the character located at the specified index within the given string. The index value should be between 0 and `length() - 1`.
From 2900816499349fb3f38eea405144767953427b58 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 18:48:47 +0530
Subject: [PATCH 051/236] Update README.md
---
section6/README.md | 3 +++
1 file changed, 3 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index c58a56d..757229d 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -208,6 +208,9 @@ The compareTo() method is useful when you need to compare strings alphabetically
The compareTo() method in Java is a powerful tool for comparing strings lexicographically. By returning an integer value indicating whether one string is less than, equal to, or greater than another, it facilitates various sorting and comparison tasks in Java programming. Understanding how to use compareTo() effectively can greatly enhance your ability to manipulate and analyze strings in Java applications.
## String.charAt() Method in Java
The `String.charAt()` method in Java returns the character located at the specified index within the given string. The index value should be between 0 and `length() - 1`.
+#### Example π‘
+```java
+
From 6185c7fc8aa2a560d68a57feed42b939a380ef54 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 19:29:53 +0530
Subject: [PATCH 052/236] Update README.md
---
section6/README.md | 33 +++++++++++++++++++++++++++++++++
1 file changed, 33 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index 757229d..3652224 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -208,8 +208,41 @@ The compareTo() method is useful when you need to compare strings alphabetically
The compareTo() method in Java is a powerful tool for comparing strings lexicographically. By returning an integer value indicating whether one string is less than, equal to, or greater than another, it facilitates various sorting and comparison tasks in Java programming. Understanding how to use compareTo() effectively can greatly enhance your ability to manipulate and analyze strings in Java applications.
## String.charAt() Method in Java
The `String.charAt()` method in Java returns the character located at the specified index within the given string. The index value should be between 0 and `length() - 1`.
+### Parameters
+**index :** An integer representing the index of the character.
+### Return Value
+The method returns the character at the specified index within the string.
+### Exceptions
+**IndexOutOfBoundsException :** If the index argument is negative or not less than the length of the string.
#### Example π‘
```java
+public class CharAtMethodDemo {
+
+ public static void main(String[] args) {
+ String java = "JAVA";
+ char j = java.charAt(0); // 'J'
+ char exception = java.charAt(4);// IndexOutOfBoundsException, because index value (4) is not with in the range of 'String.length()-1'.
+ }
+
+}
+```
+### Usage π
+- Use this method when you need to retrieve a specific character from a string by its index.
+- It's handy when you want to iterate over each character in a string.
+### Note βοΈ
+- Remember that index starts from 0. So, the first character of the string is at index 0.
+### Conclusion π
+- The String.charAt() method in Java provides a simple and efficient way to access individual characters within a string by their index. By specifying the desired index, you can retrieve the character located at that position in the string.
+- This method is particularly useful when you need to work with individual characters within a string, such as extracting specific characters or iterating through each character in the string.
+- However, it's important to be mindful of the index values to avoid IndexOutOfBoundsException. The index should be within the range of 0 to length() - 1 for the string.
+- Overall, String.charAt() is a fundamental method for string manipulation in Java, offering versatility and ease of use in various string processing tasks.
+- Happy coding! π» π.
+## isEmpty() Method in Java
+The `isEmpty()` method in Java is used to check whether a string is empty or not. An empty string is defined as a string that has a length of zero.
+### Return Value
+- 'true' if the length of the string is 0, indicating that it is empty.
+- 'false' otherwise
+
From 9356fd23db98b8649f0013daeebfb9e413c36428 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 19:31:58 +0530
Subject: [PATCH 053/236] Update README.md
---
section6/README.md | 3 +++
1 file changed, 3 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index 3652224..30c22df 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -242,6 +242,9 @@ The `isEmpty()` method in Java is used to check whether a string is empty or not
### Return Value
- 'true' if the length of the string is 0, indicating that it is empty.
- 'false' otherwise
+#### Example
+
+
From 11947417af11cf9ab72d4bac9e9b436c7cca4576 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 Feb 2024 19:58:24 +0530
Subject: [PATCH 054/236] Update README.md
---
section6/README.md | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index 30c22df..8d9cfd3 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -243,6 +243,32 @@ The `isEmpty()` method in Java is used to check whether a string is empty or not
- 'true' if the length of the string is 0, indicating that it is empty.
- 'false' otherwise
#### Example
+```java
+public class EmptyCheckDemo {
+
+ public static void main(String[] args) {
+ String myString = "";
+ boolean isEmpty = myString.isEmpty(); //true
+ boolean isLengthZero = myString.length()==0;// true
+ boolean isEqualEmpty = "".equals(myString); //true
+
+ String nullString = null;
+ boolean isnullEmpty = "".equals(nullString); //false
+ // boolean isEmptyNull = nullString.length()==0; // NullPointerException
+ }
+
+}
+```
+### Usage π
+The isEmpty() method is commonly used in scenarios where you need to check if a string contains any meaningful content before performing further operations on it.
+### Notes βοΈ
+- The 'isEmpty()' method is a part of the java.lang.String class and can be called on any string object.
+- It's important to handle empty strings appropriately in your code to avoid unexpected behavior, especially when dealing with user input or data processing.
+### Conclusion π
+- The isEmpty() method in Java provides a convenient way to check whether a string is empty or not. By simply calling this method on a string object, you can quickly determine if it contains any meaningful content or if it's just a blank string.
+- This method is particularly useful in scenarios where you need to validate user input, process data, or control flow based on the presence of content in a string. By incorporating isEmpty() into your Java code, you can ensure that your applications handle empty strings gracefully and avoid unexpected behavior.
+- Remember to use isEmpty() judiciously in your code, especially when dealing with user input or data processing, to enhance the reliability and robustness of your Java applications.
+
From 373c0e2dbd260aac8e29c885a775c6245601a436 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 21 Feb 2024 12:04:02 +0530
Subject: [PATCH 055/236] Update README.md
---
section6/README.md | 45 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 45 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index 8d9cfd3..cdfd82f 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -268,6 +268,51 @@ The isEmpty() method is commonly used in scenarios where you need to check if a
- The isEmpty() method in Java provides a convenient way to check whether a string is empty or not. By simply calling this method on a string object, you can quickly determine if it contains any meaningful content or if it's just a blank string.
- This method is particularly useful in scenarios where you need to validate user input, process data, or control flow based on the presence of content in a string. By incorporating isEmpty() into your Java code, you can ensure that your applications handle empty strings gracefully and avoid unexpected behavior.
- Remember to use isEmpty() judiciously in your code, especially when dealing with user input or data processing, to enhance the reliability and robustness of your Java applications.
+## toUpperCase() and toLowerCase() methods in Java
+Java provides the `toUpperCase()` and `toLowerCase()` methods in the `String` class to convert the case of characters within a string. These methods are commonly used when you need to manipulate or normalize string data, such as converting text to uppercase for comparison or formatting purposes.
+## toUpperCase()
+The `toUpperCase()` method converts all the characters in a `String` to uppercase. Here's the syntax :
+```java
+String upperCaseString = originalString.toUpperCase();
+```
+#### Example
+```java
+String str = "Hello, World!";
+String upperCaseStr = str.toUpperCase();
+System.out.println(upperCaseStr); // Output: HELLO, WORLD!
+```
+## toLowerCase()
+The toLowerCase() method converts all the characters in a String to lowercase. Here's the syntax :
+```java
+String lowerCaseString = originalString.toLowerCase();
+```
+#### Example
+```java
+String str = "Hello, World!";
+String lowerCaseStr = str.toLowerCase();
+System.out.println(lowerCaseStr); // Output: hello, world!
+```
+### Usage π
+These methods are useful for case-insensitive string comparisons, normalizing user input, and formatting string data for output. They are commonly used in various applications, including text processing, data validation, and user interfaces.
+### Considerations π€
+- **Locale :** It's important to note that the behavior of these methods can vary based on the locale settings of the system. In some languages, certain characters may have different uppercase or lowercase representations.
+- **Immutability :** Both toUpperCase() and toLowerCase() methods return a new String object with the modified case. The original string remains unchanged.
+### Conclusion π
+The toUpperCase() and toLowerCase() methods provide convenient ways to convert the case of characters within a string in Java. Understanding their usage and considerations can help you effectively manipulate string data in your Java applications.
+## String.valueOf() Method in Java
+The String.valueOf() method in Java is a static method provided by the String class, which converts different types of data, including primitive types and objects, into their string representations.
+```java
+public static String valueOf(Object obj)
+```
+### Parameters
+- obj: The object whose string representation is to be returned.
+### Return Value
+- Returns the string representation of the specified object. If the specified object is 'null', it returns the string "null".
+#### Example
+
+
+
+
From c584f82764d53e1ef2f20bfba69aadbf57227a25 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 21 Feb 2024 17:22:47 +0530
Subject: [PATCH 056/236] Update README.md
---
section6/README.md | 123 +++++++++++++++++++++++++++++++++++++++++++--
1 file changed, 120 insertions(+), 3 deletions(-)
diff --git a/section6/README.md b/section6/README.md
index cdfd82f..def723a 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -242,7 +242,7 @@ The `isEmpty()` method in Java is used to check whether a string is empty or not
### Return Value
- 'true' if the length of the string is 0, indicating that it is empty.
- 'false' otherwise
-#### Example
+#### Example π‘
```java
public class EmptyCheckDemo {
@@ -275,7 +275,7 @@ The `toUpperCase()` method converts all the characters in a `String` to uppercas
```java
String upperCaseString = originalString.toUpperCase();
```
-#### Example
+#### Example π‘
```java
String str = "Hello, World!";
String upperCaseStr = str.toUpperCase();
@@ -286,7 +286,7 @@ The toLowerCase() method converts all the characters in a String to lowercase. H
```java
String lowerCaseString = originalString.toLowerCase();
```
-#### Example
+#### Example π‘
```java
String str = "Hello, World!";
String lowerCaseStr = str.toLowerCase();
@@ -308,7 +308,124 @@ public static String valueOf(Object obj)
- obj: The object whose string representation is to be returned.
### Return Value
- Returns the string representation of the specified object. If the specified object is 'null', it returns the string "null".
+#### Example π‘
+```java
+public class ConvertStringDemo {
+
+ public static void main(String[] args) {
+ int intValue = 42;
+ double doubleValue = 3.14;
+ boolean boolValue = true;
+
+ String str1 = String.valueOf(intValue);// "42"
+ String str2 = String.valueOf(doubleValue);// "3.14"
+ String str3 = String.valueOf(boolValue);// "true"
+ String str4 = String.valueOf('M');// "M"
+
+ int age = 30;
+ String message = "My age is : "+ age; //" My age is : 42"
+ String piValue = ""+ 3.14;// "3.14"
+ }
+}
+```
+### Usage π
+- Convert primitive data types to strings.
+- Convert objects to strings by invoking their toString() methods.
+- Concatenate strings with other data types easily.
+### Note βοΈ
+- This method returns "null" for 'null' inputs to prevent 'NullPointerException'.
+### Conclusion π
+The String.valueOf() method in Java is a versatile tool for converting various data types into their string representations. Its simplicity and flexibility make it a fundamental part of Java programming, allowing for easy manipulation and concatenation of strings with other data types. Whether you need to convert primitive types, objects, or handle null values gracefully, String.valueOf() provides a reliable solution. By understanding its syntax, parameters, and return value, you can leverage this method effectively in your Java projects.
+## String.indexOf() Method in java
+- The `indexOf()` method in Java is used to find the index of a specific character or substring within a given string. This method returns the index of the first occurrence of the specified character or substring within the string, or -1 if the character or substring is not found.
+- The syntax for using the `indexOf()` method is:
+```java
+int indexOf(int ch)
+int indexOf(int ch, int fromIndex)
+int indexOf(String str)
+int indexOf(String str, int fromIndex)
+```
+- 'ch' is the character to be searched.
+- 'str' is the substring to be searched.
+- 'fromIndex' is the index to start the search from.
+### Parameters
+The method returns the index of the first occurrence of the specified character or substring within the string, or -1 if the character or substring is not found.
+#### Example π‘
+```java
+String str = "Hello, World!";
+int index1 = str.indexOf('o'); // Returns 4
+int index2 = str.indexOf('o', 5); // Returns 8
+int index3 = str.indexOf("World"); // Returns 7
+int index4 = str.indexOf("World", 8); // Returns -1
+```
+#### In this example :
+- 'index1' returns 4 because the first occurrence of 'o' is at index 4.
+- 'index2' returns 8 because the search starts from index 5, and the next occurrence of 'o' is at index 8.
+- 'index3' returns 7 because the substring "World" starts at index 7.
+- 'index4' returns -1 because the substring "World" is not found when starting the search from index 8.
+### Note βοΈ
+- The 'indexOf()' method is case-sensitive.
+- If you need a case-insensitive search, consider using 'toLowerCase()' or 'toUpperCase()' before invoking indexOf().
+### Conclusion π
+- The 'indexOf()' method in Java is a powerful tool for searching for specific characters or substrings within a string. By understanding its syntax, parameters, and return value, you can efficiently locate the desired elements within your strings.
+- Remember that 'indexOf()' is case-sensitive, so ensure that your search criteria match the case of the characters or substrings within the string. If case-insensitive searching is required, consider converting the string to lowercase or uppercase before using 'indexOf()'.
+- With its versatility and ease of use, 'indexOf()' is a valuable method to have in your Java programming arsenal for string manipulation tasks.
+## String.startsWith() and String.endsWith() Methods in Java
+The 'startsWith()' and 'endsWith()' methods in Java are used to check whether a string begins or ends with a specific prefix or suffix, respectively. These methods are helpful in various scenarios where string manipulation is required.
+### startsWith()
+#### Syntax
+```java
+public boolean startsWith(String prefix)
+```
+### Parameters
+- **'prefix' :** The prefix to check against the beginning of the string.
+### Return Value
+- 'true' if the string starts with the specified prefix; otherwise, 'false'.
+#### Example
+```java
+String str = "Hello, world!";
+boolean startsWithHello = str.startsWith("Hello");
+System.out.println(startsWithHello); // Output: true
+```
+### endsWith()
+#### Syntax
+```java
+public boolean endsWith(String suffix)
+```
+### Parameters
+- **'suffix' :** The suffix to check against the end of the string.
+### Return Value
+- 'true' if the string ends with the specified suffix; otherwise, false.
+#### Example
+```java
+String str = "Hello, world!";
+boolean endsWithWorld = str.endsWith("world!");
+System.out.println(endsWithWorld); // Output: true
+```
+### Use Cases
+- **Validation :** Checking if a file name has a specific extension.
+- **Parsing :** Determining if a line of text ends with a particular punctuation mark.
+- **Filtering :** Filtering a list of strings based on prefixes or suffixes.
+### Notes
+- Both methods are case-sensitive.
+- If the length of the prefix or suffix is greater than the length of the string, 'startsWith()' and 'endsWith()' will return 'false'.
+- Both methods return true for an empty prefix or suffix, indicating that the string starts or ends with nothing.
+- If either the prefix or suffix is 'null', these methods will throw a 'NullPointerException'.
+## String.trim() Method in Java
+The 'String.trim()' method in Java is used to remove leading and trailing whitespace from a string. Whitespace refers to any character that has no visible representation, such as spaces, tabs, and newline characters.
+### Syntax
+```java
+public String trim()
+```
+### Parameters
+- This method does not take any parameters.
+### Return Value
+- A new string with leading and trailing whitespace removed.
#### Example
+```java
+
+
+
From a2ddd346331b5bd3fd02ad6993dc0c8f16144275 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 21 Feb 2024 17:26:36 +0530
Subject: [PATCH 057/236] Update README.md
---
section6/README.md | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index def723a..2fbaafe 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -423,6 +423,22 @@ public String trim()
- A new string with leading and trailing whitespace removed.
#### Example
```java
+public class StringTrimDemo {
+
+ public static void main(String[] args) {
+ String java1 = " java ".trim(); //java
+ String java2 = "java ".trim(); // java
+ String java3 = "\n \t java \n \r ".trim();// java
+ String java5 = " ja va ".trim();//ja va
+ String java6 = " ja \n va ".trim();//ja
+ // va
+ boolean isSame = "java".equals("java ".trim());//true
+ boolean isSame = "java".equals("java ");// false
+
+ }
+
+}
+```
From 3b43db6e79f9ee0338f0cb6ea017b27bf8e9a0c6 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 21 Feb 2024 17:43:27 +0530
Subject: [PATCH 058/236] Update README.md
---
section6/README.md | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index 2fbaafe..9ed061b 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -439,6 +439,28 @@ public class StringTrimDemo {
}
```
+### Conclusion
+- The 'String.trim()' method in Java provides a convenient way to remove leading and trailing whitespace from a string. It is useful for cleaning up user input, parsing data, and manipulating strings in various applications.
+- By utilizing 'trim()', developers can ensure that strings are properly formatted and free of unnecessary whitespace, improving the reliability and readability of their code.
+- Remember to handle cases where the string may be null to avoid 'NullPointerExceptions', and be aware that 'trim()' creates a new string instance rather than modifying the original string.
+- In summary, 'String.trim()' is a simple yet powerful method that contributes to the effectiveness and efficiency of string manipulation in Java programming.
+## String.substring() Method in Java
+The `String.substring()` method in Java is used to extract a substring from the given string. It returns a new string that is a substring of this string.
+### Syntax
+```java
+public String substring(int beginIndex)
+public String substring(int beginIndex, int endIndex)
+```
+### Parameters
+- **beginIndex :** The beginning index, inclusive.
+- **endIndex :** The ending index, exclusive.
+### Return Value
+A new string that is a substring of this string.
+#### Examples
+```java
+
+
+
From 3b789d48153159ba66d8ef51da0f8e2385064e33 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 21 Feb 2024 18:04:58 +0530
Subject: [PATCH 059/236] Update README.md
---
section6/README.md | 34 ++++++++++++++++++++++++++++++++--
1 file changed, 32 insertions(+), 2 deletions(-)
diff --git a/section6/README.md b/section6/README.md
index 9ed061b..37c059f 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -406,7 +406,7 @@ System.out.println(endsWithWorld); // Output: true
- **Validation :** Checking if a file name has a specific extension.
- **Parsing :** Determining if a line of text ends with a particular punctuation mark.
- **Filtering :** Filtering a list of strings based on prefixes or suffixes.
-### Notes
+### Notes βοΈ
- Both methods are case-sensitive.
- If the length of the prefix or suffix is greater than the length of the string, 'startsWith()' and 'endsWith()' will return 'false'.
- Both methods return true for an empty prefix or suffix, indicating that the string starts or ends with nothing.
@@ -439,7 +439,7 @@ public class StringTrimDemo {
}
```
-### Conclusion
+### Conclusion π
- The 'String.trim()' method in Java provides a convenient way to remove leading and trailing whitespace from a string. It is useful for cleaning up user input, parsing data, and manipulating strings in various applications.
- By utilizing 'trim()', developers can ensure that strings are properly formatted and free of unnecessary whitespace, improving the reliability and readability of their code.
- Remember to handle cases where the string may be null to avoid 'NullPointerExceptions', and be aware that 'trim()' creates a new string instance rather than modifying the original string.
@@ -458,6 +458,36 @@ public String substring(int beginIndex, int endIndex)
A new string that is a substring of this string.
#### Examples
```java
+public class SubStringDemo {
+
+ public static void main(String[] args) {
+ String originalString = "Hello, World!";
+ String subString1 = originalString.substring(7); // "World"
+ String subString2 = originalString.substring(0,5);// "Hello"
+ }
+
+}
+```
+### Notes βοΈ
+- The 'beginIndex' must be less than the 'endIndex'.
+- If 'beginIndex' is equal to 'endIndex', the returned string is empty.
+- If 'beginIndex' or 'endIndex' is negative or greater than the length of the string, it throws 'IndexOutOfBoundsException'.
+### Conclusion π
+- The 'String.substring()' method in Java provides a convenient way to extract substrings from a given string based on specified indices. Whether you need to extract a substring starting from a particular index or within a range of indices, this method allows you to do so with ease.
+
+- By understanding its syntax, parameters, and return value, you can effectively utilize this method in your Java programs. Remember to handle edge cases such as negative indices or out-of-bounds indices to ensure robustness in your code.
+
+- With the examples provided, you should now have a clear understanding of how to use 'String.substring()' method in various scenarios, enabling you to manipulate strings effectively in your Java applications.
+## String.replace(), String.replaceAll(), and String.replaceFirst() Methods in Java
+### String.replace()
+The `replace()` method in Java `String` class replaces all occurrences of a specified character or sequence of characters with another character or sequence of characters.
+### String.replaceAll()
+The replaceAll() method in Java String class replaces each substring of this string that matches the given regular expression with the given replacement.
+### String.replaceFirst()
+The replaceFirst() method in Java String class replaces the first substring of this string that matches the given regular expression with the given replacement.
+#### Example
+```java
+
From 54d620921e4ae0690f74ad7c5fcea6e84ef7d784 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 21 Feb 2024 18:20:37 +0530
Subject: [PATCH 060/236] Update README.md
---
section6/README.md | 32 ++++++++++++++++++++++++++++++--
1 file changed, 30 insertions(+), 2 deletions(-)
diff --git a/section6/README.md b/section6/README.md
index 37c059f..b69b26e 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -482,11 +482,39 @@ public class SubStringDemo {
### String.replace()
The `replace()` method in Java `String` class replaces all occurrences of a specified character or sequence of characters with another character or sequence of characters.
### String.replaceAll()
-The replaceAll() method in Java String class replaces each substring of this string that matches the given regular expression with the given replacement.
+The `replaceAll()` method in Java `String` class replaces each substring of this string that matches the given regular expression with the given replacement.
### String.replaceFirst()
-The replaceFirst() method in Java String class replaces the first substring of this string that matches the given regular expression with the given replacement.
+The `replaceFirst()` method in Java `String` class replaces the first substring of this string that matches the given regular expression with the given replacement.
#### Example
```java
+public class StringReplaceDemo {
+
+ public static void main(String[] args) {
+ String originalString = "Hello, World!";
+ String replacedString = originalString.replace('o', '*');// "Hell*, W*rld!"
+ String replacedString1 = originalString.replace("World","Universe");// "Hello, Universe!"
+ String replacedString2 = originalString.replace("world","Universe");// Hello, World!"
+
+ String originalString1 = "abababab";
+ String replacedString3 = originalString1.replace("ab","X");// "XXXX"
+
+ String originalString2 = "Java is fun!";
+ String replacedString4 = originalString2.replaceAll("a|e|i|o|u", "*");// J*v* *s f*n!"
+
+ String originalString3 = "apple orange apple banana apple";
+ String replacedString5 = originalString3.replaceFirst("apple", "grape");// "grape orange apple banana apple"
+
+ }
+
+}
+```
+### Conclusion
+- Use `replace()` when you want to replace all occurrences of a specific character or sequence.
+- Use `replaceAll()` when you want to replace all occurrences based on a regular expression.
+- Use `replaceFirst()` when you only want to replace the first occurrence based on a regular expression.
+
+ These methods provide flexibility in manipulating strings according to specific requirements.
+
From 7da4a4ca2773bde6ee707b7830306e152e2a69c3 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 21 Feb 2024 18:29:38 +0530
Subject: [PATCH 061/236] Update README.md
---
section6/README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/section6/README.md b/section6/README.md
index b69b26e..953a8a5 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -485,7 +485,7 @@ The `replace()` method in Java `String` class replaces all occurrences of a spec
The `replaceAll()` method in Java `String` class replaces each substring of this string that matches the given regular expression with the given replacement.
### String.replaceFirst()
The `replaceFirst()` method in Java `String` class replaces the first substring of this string that matches the given regular expression with the given replacement.
-#### Example
+#### Example π‘
```java
public class StringReplaceDemo {
@@ -508,7 +508,7 @@ public class StringReplaceDemo {
}
```
-### Conclusion
+### Conclusion π
- Use `replace()` when you want to replace all occurrences of a specific character or sequence.
- Use `replaceAll()` when you want to replace all occurrences based on a regular expression.
- Use `replaceFirst()` when you only want to replace the first occurrence based on a regular expression.
From c571a20462b831e18633e817c0d8042c85a06a11 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 21 Feb 2024 18:33:19 +0530
Subject: [PATCH 062/236] Update README.md
---
section6/README.md | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index 953a8a5..9d71cc8 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -514,6 +514,18 @@ public class StringReplaceDemo {
- Use `replaceFirst()` when you only want to replace the first occurrence based on a regular expression.
These methods provide flexibility in manipulating strings according to specific requirements.
+## String.split() Method in Java
+The `split()` method in Java is a function provided by the `String` class to split a string into an array of substrings based on a delimiter. It's commonly used for parsing and manipulating textual data.
+### Syntax
+```java
+public String[] split(String regex)
+```
+- **regex :** The regular expression to use as a delimiter.
+### Parameters
+**regex :** The regular expression that defines where the string should be split.
+### Return Value
+An array of strings split from the original string based on the delimiter provided.
+### Example
From 90a8ae298a73887e1c1cdd7afb79cbac60a2e554 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 21 Feb 2024 18:45:49 +0530
Subject: [PATCH 063/236] Update README.md
---
section6/README.md | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index 9d71cc8..4d68c3e 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -526,6 +526,30 @@ public String[] split(String regex)
### Return Value
An array of strings split from the original string based on the delimiter provided.
### Example
+```java
+public class StringSplitDemo {
+
+ public static void main(String[] args) {
+ String fruits = "apple,orange,banana,grape";
+ String[] fruitArray = fruits.split(",");
+ for(int i=0; i
Date: Fri, 1 Mar 2024 14:07:32 +0530
Subject: [PATCH 064/236] Update README.md
---
section6/README.md | 15 +++++++++++++++
1 file changed, 15 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index 4d68c3e..7f93863 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -549,6 +549,21 @@ In this example, the string `"apple,orange,banana,grape"` is split into parts us
- The `split()` method in Java is a versatile tool for splitting strings into substrings based on a specified delimiter. Whether you're parsing CSV files, breaking down user input, or manipulating textual data, `split()` offers a convenient way to achieve your goals.
- By understanding its syntax, parameters, and return value, along with practical examples, you can leverage this method effectively in your Java applications.Remember to consider edge cases, such as handling empty strings or using appropriate regex patterns, to ensure robustness and accuracy in your implementations.
+## String.join() Method in Java
+The `String.join()` method in Java is used to join multiple strings into a single string. It's a convenient way to concatenate strings with a specified delimiter.
+### Syntax
+```java
+public static String join(CharSequence delimiter, CharSequence... elements)
+```
+### Parameters
+- **delimiter :** The delimiter to use for joining the strings.
+- **elements :** The strings to be joined.
+### Returns
+A string consisting of the elements joined together with the specified delimiter.
+### Example
+```java
+
+
From 42a4829da680a813481fd5551f23927e29f72777 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 1 Mar 2024 14:25:38 +0530
Subject: [PATCH 065/236] Update README.md
---
section6/README.md | 33 +++++++++++++++++++++++++++++++--
1 file changed, 31 insertions(+), 2 deletions(-)
diff --git a/section6/README.md b/section6/README.md
index 7f93863..0d149bd 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -525,7 +525,7 @@ public String[] split(String regex)
**regex :** The regular expression that defines where the string should be split.
### Return Value
An array of strings split from the original string based on the delimiter provided.
-### Example
+### Example π‘
```java
public class StringSplitDemo {
@@ -560,8 +560,37 @@ public static String join(CharSequence delimiter, CharSequence... elements)
- **elements :** The strings to be joined.
### Returns
A string consisting of the elements joined together with the specified delimiter.
-### Example
+### Example π‘
+```java
+public class StringJoinDemo {
+
+ public static void main(String[] args) {
+ String result = String.join(",", "Hello", "World", "Java"); // "Hello,World,Java"
+ String result1 = String.join("", "Java is", "fun and", "powerful");// "Java isfun andpowerfull"
+ }
+
+}
+```
+### Notes βοΈ
+- If the delimiter is null, then `NullPointerException` is thrown.
+- If the elements array is null, then `NullPointerException` is thrown.
+- If any element is null, then "null" is added to the joined string.
+- The String.join() method was introduced in Java 8.
+### Conclusion π
+The `String.join()` method in Java provides a concise and efficient way to concatenate multiple strings with a specified delimiter. By using this method, you can avoid manually iterating over the elements and appending them together, which leads to cleaner and more readable code.
+
+Remember to handle cases where the delimiter or elements array is null to prevent `NullPointerExceptions`. Additionally, keep in mind that if any element in the array is null, it will be represented as "null" in the joined string.
+
+Overall, the `String.join()` method is a valuable addition to the Java language introduced in Java 8, simplifying string concatenation tasks and improving code maintainability.
+## String.format() Method in Java
+In Java, the `String.format()` method is used to format strings. It returns a formatted string using the specified format string and arguments. This method is useful for creating complex output strings with placeholders for variables.
+### Syntax
```java
+String formattedString = String.format(String format, Object... args);
+```
+**format :** A format string that specifies how the output string should be formatted. It may contain placeholders that will be replaced by the corresponding arguments.
+**args :** Optional arguments that will replace the placeholders in the format string.
+### Example
From 726a1902a7fcbf8ab0bba60ba5508a9518a56c3e Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 1 Mar 2024 14:33:14 +0530
Subject: [PATCH 066/236] Update README.md
---
section6/README.md | 28 +++++++++++++++++++++++++++-
1 file changed, 27 insertions(+), 1 deletion(-)
diff --git a/section6/README.md b/section6/README.md
index 0d149bd..a4cb901 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -590,7 +590,33 @@ String formattedString = String.format(String format, Object... args);
```
**format :** A format string that specifies how the output string should be formatted. It may contain placeholders that will be replaced by the corresponding arguments.
**args :** Optional arguments that will replace the placeholders in the format string.
-### Example
+### Example π‘
+```java
+public class StringFormatDemo {
+
+ public static void main(String[] args) {
+ String message = "Hello, %s ! You have %d messages.";
+ String msgForMadan = String.format(message, "Madan", 3); // "Hello, Madan ! You have 3 messages."
+ String msgForSaanvi = String.format(message, "Saanvi", 6);// "Hello, Saanvi ! You have 6 messages."
+
+ String message1 = "The price is $%.2f";
+ String price1 = String.format(message1, 19.99);
+ String price2 = String.format(message1, 9.99);
+
+ }
+}
+```
+In this example, we used String.format() to create a formatted string with placeholders %s, %d, and %.2f for name, messages, and price, respectively.
+### Format Specifiers
+- **%s :** String
+- **%d :** Integer
+- **%f :** Float or double
+- **%c :** Character
+- **%b :** Boolean
+- **%t :** Date/time
+### Conclusion π
+The `String.format()` method in Java provides a powerful way to create formatted strings with placeholders. By using format specifiers in the format string, you can control the formatting of different types of data in the output string.
+
From 061f4b5cb0f548466ddc73a2718cc6e3ae55bcef Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 1 Mar 2024 14:41:08 +0530
Subject: [PATCH 067/236] Update README.md
---
section6/README.md | 14 ++++++++++++++
1 file changed, 14 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index a4cb901..296fb66 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -616,6 +616,20 @@ In this example, we used String.format() to create a formatted string with place
- **%t :** Date/time
### Conclusion π
The `String.format()` method in Java provides a powerful way to create formatted strings with placeholders. By using format specifiers in the format string, you can control the formatting of different types of data in the output string.
+## System.out.printf() Method in Java
+`System.out.printf()` is a method in Java used for formatted output. It allows you to print formatted strings to the standard output stream (`System.out`).
+### Syntax
+```java
+public PrintStream printf(String format, Object... args)
+```
+### Parameters
+**format :** This is a string that specifies the formatting of the output. It can contain format specifiers, which start with % and are followed by optional flags, width, precision, and conversion characters.
+**args :** These are the arguments to be inserted into the format string. They correspond to the format specifiers in the format string.
+### Return Value
+This method returns a reference to the PrintStream object (System.out).
+### Example
+```java
+
From 87b5f95af4073cccbfdd32fc278bb785273c2608 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 1 Mar 2024 14:51:19 +0530
Subject: [PATCH 068/236] Update README.md
---
section6/README.md | 26 +++++++++++++++++++++++++-
1 file changed, 25 insertions(+), 1 deletion(-)
diff --git a/section6/README.md b/section6/README.md
index 296fb66..f90a39e 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -627,8 +627,32 @@ public PrintStream printf(String format, Object... args)
**args :** These are the arguments to be inserted into the format string. They correspond to the format specifiers in the format string.
### Return Value
This method returns a reference to the PrintStream object (System.out).
-### Example
+### Example π‘
```java
+public class PrintfDemo {
+
+ public static void main(String[] args) {
+
+ System.out.printf("Name: %s, Age: %d%n", "John", 25); // "Name: John, Age:25"
+ System.out.printf("Price: %.2f%n", 19.99); // "Price: 19.99"
+ System.out.printf("Grade: %c%n", 'A');
+ System.out.printf("Is Java fun ?: %b%n", true);
+ }
+
+}
+```
+### Notes βοΈ
+- The `printf()` method uses the same formatting conventions as the Formatter class.
+- If the number of arguments does not match the number of format specifiers, an `IllegalFormatException` will be thrown.
+### Conclusion π
+- The System.out.printf() method in Java provides a convenient way to format output strings. By using format specifiers within the format string, you can control the layout and appearance of the output. This method is particularly useful when you need to display data in a structured and visually appealing manner.
+- By leveraging System.out.printf(), you can enhance the readability and professionalism of your Java applications' output. Whether you're printing simple text or complex data structures, this method offers the flexibility and precision needed to meet your formatting requirements.
+
+
+
+
+
+
From 6f005553a9a8c66469fdc24ec4e116ebd1bbeb03 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 6 Mar 2024 11:55:39 +0530
Subject: [PATCH 069/236] Update README.md
---
section6/README.md | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index f90a39e..b6ebb7d 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -647,6 +647,16 @@ public class PrintfDemo {
### Conclusion π
- The System.out.printf() method in Java provides a convenient way to format output strings. By using format specifiers within the format string, you can control the layout and appearance of the output. This method is particularly useful when you need to display data in a structured and visually appealing manner.
- By leveraging System.out.printf(), you can enhance the readability and professionalism of your Java applications' output. Whether you're printing simple text or complex data structures, this method offers the flexibility and precision needed to meet your formatting requirements.
+## Mutable Strings in Java
+Mutable Strings in Java refer to strings that can be modified after their creation. Unlike the traditional String class, which is immutable, mutable strings offer the flexibility to change their content without creating new objects.
+### Introduction
+Mutable strings are particularly useful in scenarios where frequent modifications to the string content are required, such as in performance-critical applications or when dealing with large datasets
+In Java, the StringBuilder and StringBuffer classes provide mutable string functionality.
+### StringBuilder
+`StringBuilder` is a mutable sequence of characters. It is similar to StringBuffer, but differs in that it is not synchronized, making it faster for single-threaded operations.
+### StringBuffer
+`StringBuffer` is a thread-safe, mutable sequence of characters. It is similar to StringBuilder, but synchronized, making it safe for use in multi-threaded environments.
+
From 865b0dd7cfc7a0d916a6b578ed0f5cf81877493e Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 6 Mar 2024 12:14:17 +0530
Subject: [PATCH 070/236] Update README.md
---
section6/README.md | 44 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 44 insertions(+)
diff --git a/section6/README.md b/section6/README.md
index b6ebb7d..e180726 100644
--- a/section6/README.md
+++ b/section6/README.md
@@ -656,6 +656,50 @@ In Java, the StringBuilder and StringBuffer classes provide mutable string funct
`StringBuilder` is a mutable sequence of characters. It is similar to StringBuffer, but differs in that it is not synchronized, making it faster for single-threaded operations.
### StringBuffer
`StringBuffer` is a thread-safe, mutable sequence of characters. It is similar to StringBuilder, but synchronized, making it safe for use in multi-threaded environments.
+### Example π‘
+```java
+import java.io.CharArrayWriter;
+import java.io.IOException;
+
+public class StringMutableDemo {
+
+ public static void main(String[] args) throws IOException {
+
+ // Approach 1
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.append("World");
+ stringBuilder.insert(0,"Hello "); // "Hello World"
+ stringBuilder.deleteCharAt(4); //" Hell World"
+ stringBuilder.insert(4,'o'); // "Hello World"
+ stringBuilder.setLength(5); //"Hello"
+ stringBuilder.reverse(); //"olleh"
+ String str = stringBuilder.toString();
+
+ // Approach 2
+ StringBuffer stringBuffer = new StringBuffer();
+ stringBuffer.append("World");
+ stringBuffer.insert(0,"Hello ");
+ stringBuffer.deleteCharAt(4);
+ stringBuffer.insert(4,'o');
+ stringBuffer.setLength(5);
+ stringBuffer.reverse();
+ String str1 = stringBuffer.toString();
+
+ // Approach 3
+
+ CharArrayWriter cw = new CharArrayWriter();
+ cw.write("Hello");
+ cw.write(" World");
+ String string3 = cw.toString();
+
+ }
+
+}
+```
+### Conclusion π
+Mutable strings provided by `StringBuilder` and `StringBuffer` classes offer efficient ways to manipulate string data in Java applications. Choose `StringBuilder` for single-threaded scenarios where synchronization is not needed, and `StringBuffer` for multi-threaded environments requiring thread safety.
+
+
From 9ee80279285d9028166a8150d97be0568c627f3d Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 6 Mar 2024 12:18:54 +0530
Subject: [PATCH 071/236] Create README.md
---
section7/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section7/README.md
diff --git a/section7/README.md b/section7/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section7/README.md
@@ -0,0 +1 @@
+
From 392b592b3b3d9e2ca881d13e65a8a669db119b7c Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 6 Mar 2024 14:04:09 +0530
Subject: [PATCH 072/236] Update README.md
---
section7/README.md | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index 8b13789..cde5381 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -1 +1,27 @@
+# Operators and Operands in Java
+### Overview
+In Java programming, operators are symbols that perform operations on operands. Operands can be variables, constants, or expressions. Understanding operators and operands is crucial for writing efficient and concise code.
+## Java Expressions
+In Java, expressions are combinations of variables, operators, and method invocations that produce a single value. They can be as simple as a single variable or as complex as a mathematical formula.
+### Arithmetic Expressions
+Arithmetic expressions involve arithmetic operators (+, -, *, /, %) and operands (variables or literals) to perform mathematical calculations.
+### Relational Expressions
+Relational expressions compare two values using relational operators (==, !=, >, <, >=, <=) and evaluate to a boolean value (true or false).
+### Logical Expressions
+Logical expressions combine boolean values using logical operators (&&, ||, !) to form compound conditions.
+### Assignment Expressions
+Assignment expressions use the assignment operator (=) to assign a value to a variable.
+### Conditional Expressions
+Conditional expressions, also known as the ternary operator (?:), evaluate a boolean expression and return one of two values based on the result of the evaluation.
+
+### Assignment Operator
+The assignment operator in Java (`=`) is used to assign a value to a variable. It is one of the most commonly used operators in Java programming.
+#### Syntax
+```java
+variable = expression;
+```
+###### where :
+- variable is the name of the variable to which the value will be assigned.
+- expression is the value that will be assigned to the variable.
+
From 0dbf5795b901914043ae6b5a9b9c92353a58c003 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 6 Mar 2024 14:27:45 +0530
Subject: [PATCH 073/236] Update README.md
---
section7/README.md | 72 ++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 72 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index cde5381..d15b843 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -23,5 +23,77 @@ variable = expression;
###### where :
- variable is the name of the variable to which the value will be assigned.
- expression is the value that will be assigned to the variable.
+#### Example
+```java
+public class AssignmentOperatorDemo {
+
+ public static void main(String[] args) {
+ int num1, num2, num3, num4, num5;
+ num1 = num2 = num3 = num4 = num5 = 98;
+
+ double dNum1 = 3.14;
+ double dNum2 = 4.48;
+ dNum1 = dNum2;
+ System.out.println(dNum1); //4.48
+ dNum2 = 6.58;
+ System.out.println(dNum1); //4.48
+ }
+
+}
+```
+### Usage
+- Assigning a value to a variable.
+- Updating the value of a variable.
+### Notes
+- The assignment operator is a binary operator, meaning it requires two operands: the variable and the value to be assigned.
+- It evaluates the expression on the right-hand side and assigns the result to the variable on the left-hand side.
+- The data type of the variable must be compatible with the data type of the expression.
+## Arithmetic Operators in Java
+Arithmetic operators are used to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. Java provides several arithmetic operators that allow you to perform these operations on numeric operands.
+### Addition Operator (+)
+The addition operator (+) is used to add two operands together.
+```java
+int a = 5;
+int b = 3;
+int result = a + b;
+```
+### Subtraction Operator (-)
+The subtraction operator (-) is used to subtract the right operand from the left operand.
+```java
+int a = 10;
+int b = 4;
+int result = a - b; // result will be 6
+```
+### Multiplication Operator (*)
+The multiplication operato
+r (*) is used to multiply two operands.
+```java
+int a = 3;
+int b = 4;
+int result = a * b; // result will be 12
+```
+### Division Operator (/)
+The division operator (/) is used to divide the left operand by the right operand.
+```java
+int a = 10;
+int b = 2;
+int result = a / b; // result will be 5
+```
+### Modulus Operator (%)
+The modulus operator (%) is used to find the remainder of dividing the left operand by the right operand.
+```java
+int a = 10;
+int b = 3;
+int result = a % b; // result will be 1
+```
+### Increment (++) and Decrement (--) Operators
+The increment (++) operator is used to increment the value of an operand by 1. The decrement (--) operator is used to decrement the value of an operand by 1.
+```java
+int a = 5;
+a++; // Increment a by 1, now a is 6
+int b = 10;
+b--; // Decrement b by 1, now b is 9
+```
+
From 701d54ecec35dda68f927849e0ff41c1b0d96ee8 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 6 Mar 2024 15:08:19 +0530
Subject: [PATCH 074/236] Update README.md
---
section7/README.md | 49 ++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 49 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index d15b843..0bf3af6 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -94,6 +94,55 @@ a++; // Increment a by 1, now a is 6
int b = 10;
b--; // Decrement b by 1, now b is 9
```
+### Unary Plus Operator in Java
+The unary plus operator (+) in Java is used to indicate a positive value. It is primarily used to explicitly specify the sign of a numeric expression, although it does not change the value itself.
+#### Example
+```java
+int number = 10;
+int positiveNumber = +number; // positiveNumber will be 10
+```
+In the above example, the unary plus operator is used to explicitly indicate that the value of number is positive. However, since number is already positive, the unary plus operator does not affect its value.
+
+### Unary Minus Operator in Java
+The unary minus operator (-) in Java is used to negate the value of its operand. It is a unary operator because it operates on only one operand.
+#### Example
+```java
+public class Main {
+ public static void main(String[] args) {
+ int number = 10;
+ int result = -number;
+
+ System.out.println("Original Number: " + number); //10
+ System.out.println("Negated Number: " + result);// -10
+ }
+}
+```
+### Usage
+The unary minus operator is commonly used when you need to change the sign of a numeric value, for example, to convert a positive number to a negative one or vice versa.
+### Notes
+- The operand of the unary minus operator must be a numeric type (byte, short, int, long, float, or double).
+- If the operand is an integer type (byte, short, int, long), the result will be the negation of that integer.
+- If the operand is a floating-point type (float or double), the result will be the negation of that floating-point number.
+## Compound Arithmetic Assignment Operators in Java
+### Overview
+Compound arithmetic assignment operators in Java are shorthand notation for performing arithmetic operations and assignment in a single step. They combine an arithmetic operator with the assignment operator (`=`) to modify the value of a variable. These operators are useful for simplifying and streamlining code, especially when incrementing or decrementing variables by a fixed amount.
+### List of Compound Arithmetic Assignment Operators
+Java supports the following compound arithmetic assignment operators :
+- `+=`: Addition assignment operator
+- `-=`: Subtraction assignment operator
+- `*=`: Multiplication assignment operator
+- `/=`: Division assignment operator
+- `%=`: Modulus assignment operator
+### Syntax
+```java
+variable operator= expression;
+```
+Where:
+
+
+
+
+
From bc3bb572b00dbcc66830821fc858a2f6c3828aba Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 7 Mar 2024 12:00:04 +0530
Subject: [PATCH 075/236] Update README.md
---
section7/README.md | 56 +++++++++++++++++++++++++++++++++++++++-------
1 file changed, 48 insertions(+), 8 deletions(-)
diff --git a/section7/README.md b/section7/README.md
index 0bf3af6..6ed0688 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -23,7 +23,7 @@ variable = expression;
###### where :
- variable is the name of the variable to which the value will be assigned.
- expression is the value that will be assigned to the variable.
-#### Example
+#### Example π‘
```java
public class AssignmentOperatorDemo {
@@ -96,7 +96,7 @@ b--; // Decrement b by 1, now b is 9
```
### Unary Plus Operator in Java
The unary plus operator (+) in Java is used to indicate a positive value. It is primarily used to explicitly specify the sign of a numeric expression, although it does not change the value itself.
-#### Example
+#### Example π‘
```java
int number = 10;
int positiveNumber = +number; // positiveNumber will be 10
@@ -105,7 +105,7 @@ In the above example, the unary plus operator is used to explicitly indicate tha
### Unary Minus Operator in Java
The unary minus operator (-) in Java is used to negate the value of its operand. It is a unary operator because it operates on only one operand.
-#### Example
+#### Example π‘
```java
public class Main {
public static void main(String[] args) {
@@ -117,9 +117,9 @@ public class Main {
}
}
```
-### Usage
+### Usage π
The unary minus operator is commonly used when you need to change the sign of a numeric value, for example, to convert a positive number to a negative one or vice versa.
-### Notes
+### Notes βοΈ
- The operand of the unary minus operator must be a numeric type (byte, short, int, long, float, or double).
- If the operand is an integer type (byte, short, int, long), the result will be the negation of that integer.
- If the operand is a floating-point type (float or double), the result will be the negation of that floating-point number.
@@ -133,11 +133,51 @@ Java supports the following compound arithmetic assignment operators :
- `*=`: Multiplication assignment operator
- `/=`: Division assignment operator
- `%=`: Modulus assignment operator
-### Syntax
+### Addition Assignment `(+=)`
+The `+=` operator adds the value of the right operand to the value of the left operand and assigns the result to the left operand.
+#### Example π‘
+```java
+int x = 5;
+x += 3; // Equivalent to: x = x + 3;
+System.out.println(x); // Output: 8
+```
+### Subtraction Assignment `(-=)`
+The `-=` operator subtracts the value of the right operand from the value of the left operand and assigns the result to the left operand.
+#### Example π‘
```java
-variable operator= expression;
+int x = 10;
+x -= 4; // Equivalent to: x = x - 4;
+System.out.println(x); // Output: 6
```
-Where:
+### Multiplication Assignment `(*=)`
+The `*=` operator multiplies the value of the left operand by the value of the right operand and assigns the result to the left operand.
+#### Example π‘
+```java
+int x = 3;
+x *= 2; // Equivalent to: x = x * 2;
+System.out.println(x); // Output: 6
+```
+### Division Assignment `(/=)`
+The `/=` operator divides the value of the left operand by the value of the right operand and assigns the result to the left operand.
+#### Example π‘
+```java
+int x = 8;
+x /= 2; // Equivalent to: x = x / 2;
+System.out.println(x); // Output: 4
+```
+### Modulus Assignment `(%=)`
+The `%=` operator divides the value of the left operand by the value of the right operand and assigns the remainder to the left operand.
+#### Example π‘
+```java
+int x = 10;
+x %= 3; // Equivalent to: x = x % 3;
+System.out.println(x); // Output: 1
+```
+### Conclusion π
+Compound arithmetic assignment operators in Java are useful for performing arithmetic operations and assignment in a single step, making code concise and readable. They offer a convenient way to update variables based on their current values.
+
+
+
From 94ce079ed2a46e828b0036c2530699f85c6bb4be Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 7 Mar 2024 12:14:59 +0530
Subject: [PATCH 076/236] Update README.md
---
section7/README.md | 29 +++++++++++++++++++++++++++++
1 file changed, 29 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index 6ed0688..6c5ef0a 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -176,6 +176,35 @@ System.out.println(x); // Output: 1
### Conclusion π
Compound arithmetic assignment operators in Java are useful for performing arithmetic operations and assignment in a single step, making code concise and readable. They offer a convenient way to update variables based on their current values.
+## Realational Operators
+### Equality Operator in Java
+The Equality Operator `(==)` in Java is used to compare two operands to determine if they are equal. It's important to understand how it works and its nuances to avoid unexpected behavior in your Java programs.
+#### Basic Usage
+The Equality Operator compares the values of two operands. If the values are equal, it returns `true`; otherwise, it returns `false`. It's commonly used in conditional statements and expressions.
+#### Example
+```java
+int a = 5;
+int b = 5;
+
+boolean resul t= a==b;
+System.out.println(result); //true
+
+String str1=new String("hello");
+String str2=new String("hello");
+
+boolean isSame = str1==str2;
+
+System.out.println(isSame);// false
+```
+- When comparing reference types (objects), the Equality Operator checks if the references point to the same object in memory, not if the objects have the same values.
+- In the above example, `str1` and `str2` are different objects in memory, even though they have the same value. Therefore, the result of the comparison will be `false`.
+#### Equality vs. Identity
+- **Equality :** Compares the values of two operands.
+- **Identity :** Compares the memory addresses of two operands.
+#### Conclusion
+Understanding how the Equality Operator works in Java is crucial for writing reliable and bug-free code. Always consider the types of operands you are comparing and whether you need to check for equality or identity.
+
+
From 1fc92be12aafe5d774726796aa50b911ab27a7ab Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 7 Mar 2024 12:25:18 +0530
Subject: [PATCH 077/236] Update README.md
---
section7/README.md | 24 ++++++++++++++++++++----
1 file changed, 20 insertions(+), 4 deletions(-)
diff --git a/section7/README.md b/section7/README.md
index 6c5ef0a..4b1dc36 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -177,9 +177,9 @@ System.out.println(x); // Output: 1
Compound arithmetic assignment operators in Java are useful for performing arithmetic operations and assignment in a single step, making code concise and readable. They offer a convenient way to update variables based on their current values.
## Realational Operators
-### Equality Operator in Java
+## Equality Operator in Java
The Equality Operator `(==)` in Java is used to compare two operands to determine if they are equal. It's important to understand how it works and its nuances to avoid unexpected behavior in your Java programs.
-#### Basic Usage
+### Basic Usage
The Equality Operator compares the values of two operands. If the values are equal, it returns `true`; otherwise, it returns `false`. It's commonly used in conditional statements and expressions.
#### Example
```java
@@ -198,11 +198,27 @@ System.out.println(isSame);// false
```
- When comparing reference types (objects), the Equality Operator checks if the references point to the same object in memory, not if the objects have the same values.
- In the above example, `str1` and `str2` are different objects in memory, even though they have the same value. Therefore, the result of the comparison will be `false`.
-#### Equality vs. Identity
+### Equality vs. Identity
- **Equality :** Compares the values of two operands.
- **Identity :** Compares the memory addresses of two operands.
-#### Conclusion
+### Conclusion
Understanding how the Equality Operator works in Java is crucial for writing reliable and bug-free code. Always consider the types of operands you are comparing and whether you need to check for equality or identity.
+## Inequality Operator in Java
+In Java, the inequality operator `!=` is used to compare two values and check if they are not equal. It returns `true` if the two values are different, and `false` if they are equal.
+#### Example
+```java
+int a = 5;
+int b = 10;
+
+boolean result= a!=b;
+
+System.out.println(result);// true
+
+```
+### Notes
+- The inequality operator can be used with all primitive data types in Java (e.g., int, float, double, char, boolean, etc.).
+- It can also be used to compare objects in Java, where it checks if the references point to different objects.
+- When comparing objects, it's important to understand the difference between reference equality and object equality. For object comparison, you might need to override the `equals()` method.
From afe872282a58b416b46945965e6668bbf21a246c Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 7 Mar 2024 14:42:42 +0530
Subject: [PATCH 078/236] Update README.md
---
section7/README.md | 51 ++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 51 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index 4b1dc36..c3c90ff 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -220,6 +220,57 @@ System.out.println(result);// true
- It can also be used to compare objects in Java, where it checks if the references point to different objects.
- When comparing objects, it's important to understand the difference between reference equality and object equality. For object comparison, you might need to override the `equals()` method.
+## Comparison Operators in Java
+In Java, comparison operators are used to compare two values. These operators return a boolean value (`true` or `false`) based on the comparison result. Here, we'll discuss the greater than (`>`), greater than or equal to (`>=`), less than (`<`), and less than or equal to (`<=`) operators.
+
+### Greater Than (`>`) Operator
+The greater than operator (`>`) is used to check if the value on the left side of the operator is greater than the value on the right side.
+
+#### Example
+```java
+int a = 5;
+int b = 3;
+
+Systsem.out.println(a > b); // true
+```
+### Greater Than or Equal To (>=) Operator
+The greater than or equal to operator (`>=`) is used to check if the value on the left side of the operator is greater than or equal to the value on the right side.
+#### Example
+```java
+int a = 5;
+int b = 5;
+
+System.out.println(a >= b); // Output: true
+```
+### Less Than (<) Operator
+The less than operator (`<`) is used to check if the value on the left side of the operator is less than the value on the right side.
+#### Example
+```java
+int a = 3;
+int b = 5;
+
+System.out.println(a < b); // Output: true
+```
+### Less Than or Equal To (<=) Operator
+The less than or equal to operator (<=) is used to check if the value on the left side of the operator is less than or equal to the value on the right side.
+#### Example
+```java
+int a = 5;
+int b = 5;
+
+System.out.println(a <= b); // Output: true
+```
+
+
+
+
+
+
+
+
+
+
+
From 437f9efee30ead1feb23af53fd9ef83e796e7c79 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 7 Mar 2024 14:54:20 +0530
Subject: [PATCH 079/236] Update README.md
---
section7/README.md | 13 +++++++++----
1 file changed, 9 insertions(+), 4 deletions(-)
diff --git a/section7/README.md b/section7/README.md
index c3c90ff..08bd608 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -233,7 +233,7 @@ int b = 3;
Systsem.out.println(a > b); // true
```
-### Greater Than or Equal To (>=) Operator
+### Greater Than or Equal To (`>=`) Operator
The greater than or equal to operator (`>=`) is used to check if the value on the left side of the operator is greater than or equal to the value on the right side.
#### Example
```java
@@ -242,7 +242,7 @@ int b = 5;
System.out.println(a >= b); // Output: true
```
-### Less Than (<) Operator
+### Less Than (`<`) Operator
The less than operator (`<`) is used to check if the value on the left side of the operator is less than the value on the right side.
#### Example
```java
@@ -251,8 +251,8 @@ int b = 5;
System.out.println(a < b); // Output: true
```
-### Less Than or Equal To (<=) Operator
-The less than or equal to operator (<=) is used to check if the value on the left side of the operator is less than or equal to the value on the right side.
+### Less Than or Equal To (`<=`) Operator
+The less than or equal to operator (`<=`) is used to check if the value on the left side of the operator is less than or equal to the value on the right side.
#### Example
```java
int a = 5;
@@ -260,6 +260,11 @@ int b = 5;
System.out.println(a <= b); // Output: true
```
+## Logical Operators
+
+### Logical NOT Operator
+The logical NOT operator (`!`) is used to invert the value of a boolean expression. It returns `true` if the operand is `false`, and false if the operand is true. Here's an example :
+#### Example
From dec5735399658ecf672c0b1ba9bf70ce51df8133 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 7 Mar 2024 15:08:38 +0530
Subject: [PATCH 080/236] Update README.md
---
section7/README.md | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index 08bd608..a081647 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -265,6 +265,25 @@ System.out.println(a <= b); // Output: true
### Logical NOT Operator
The logical NOT operator (`!`) is used to invert the value of a boolean expression. It returns `true` if the operand is `false`, and false if the operand is true. Here's an example :
#### Example
+```java
+public class LogicalOperatorsDemo {
+
+ public static void main(String[] args) {
+
+ boolean isValid;
+ isValid = !true; //false
+ isValid = !false; // true
+ int num1 = 9;
+ int num2 = 6;
+ isValid = ! (num1>num2); // false
+ }
+}
+```
+## Logical AND (`&&`) Operator
+The logical AND (`&&`) operator returns `true` if both operands are `true`, otherwise it returns `false`. However, if the first operand evaluates to `false`, the second operand is not evaluated because the result will always be `false` regardless of its value.
+#### Example
+```java
+
From 0bd59bb750269ae93eedcef08d7b12f896963356 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 7 Mar 2024 15:27:36 +0530
Subject: [PATCH 081/236] Update README.md
---
section7/README.md | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index a081647..5386218 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -283,6 +283,28 @@ public class LogicalOperatorsDemo {
The logical AND (`&&`) operator returns `true` if both operands are `true`, otherwise it returns `false`. However, if the first operand evaluates to `false`, the second operand is not evaluated because the result will always be `false` regardless of its value.
#### Example
```java
+public class LogicalOperatorsDemo {
+
+ public static void main(String[] args) {
+
+ boolean isValid;
+ isValid = !true;
+ isValid = !false;
+ int num1 = 9;
+ int num2 = 6;
+ isValid = ! (num1>num2);
+
+ boolean a = (num1>5) && ((num2=16)>15);
+ System.out.println(a); // true
+ System.out.println(num2); // 16
+ }
+
+}
+```
+### Logical OR (`||`) Operator
+The logical OR (`||`) operator returns true if at least one of the operands is true. Similar to the logical AND operator, the logical OR operator also short-circuits the evaluation of an expression. If the first operand evaluates to true, the second operand is not evaluated because the result will always be true regardless of its value.
+#### Example
+
From 2a6ea6078299c4dec481b02f2596303919e407f4 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 7 Mar 2024 15:38:15 +0530
Subject: [PATCH 082/236] Update README.md
---
section7/README.md | 28 ++++++++++++++++++++++++++++
1 file changed, 28 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index 5386218..3a69a82 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -304,6 +304,34 @@ public class LogicalOperatorsDemo {
### Logical OR (`||`) Operator
The logical OR (`||`) operator returns true if at least one of the operands is true. Similar to the logical AND operator, the logical OR operator also short-circuits the evaluation of an expression. If the first operand evaluates to true, the second operand is not evaluated because the result will always be true regardless of its value.
#### Example
+```java
+public class LogicalOperatorsDemo {
+
+ public static void main(String[] args) {
+
+ boolean isValid;
+ isValid = !true;
+ isValid = !false;
+ int num1 = 9;
+ int num2 = 6;
+ isValid = ! (num1>num2);
+
+ boolean a = (num1>10) && ((num2=16)>15);
+ System.out.println(a);
+ System.out.println(num2);
+
+ boolean b = (num1 < 10) || ((num2=18)>15);
+ System.out.println(b); //true
+ System.out.println(num2);// 6
+
+ }
+
+}
+```
+## Logical XOR Operator
+The `XOR` operator, denoted by the caret symbol `^`, is a binary operator that returns true if and only if the operands differ. It returns false if both operands are the same.
+#### Example
+
From 2ceeaac85822e4c07a6dbfd3f79c68c69400e762 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 7 Mar 2024 15:42:50 +0530
Subject: [PATCH 083/236] Update README.md
---
section7/README.md | 27 +++++++++++++++++++++++++++
1 file changed, 27 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index 3a69a82..0d6399d 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -331,6 +331,33 @@ public class LogicalOperatorsDemo {
## Logical XOR Operator
The `XOR` operator, denoted by the caret symbol `^`, is a binary operator that returns true if and only if the operands differ. It returns false if both operands are the same.
#### Example
+```java
+public class LogicalOperatorsDemo {
+
+ public static void main(String[] args) {
+
+ boolean isValid;
+ isValid = !true;
+ isValid = !false;
+ int num1 = 9;
+ int num2 = 6;
+ isValid = ! (num1>num2);
+
+ boolean a = (num1>10) && ((num2=16)>15);
+ System.out.println(a);
+ System.out.println(num2);
+
+ boolean b = (num1 < 10) || ((num2=18)>15);
+ System.out.println(b);
+ System.out.println(num2);
+
+ boolean c = (num1>5) ^ (num2<10);
+ System.out.println(c);// false
+
+ boolean d = (num1>5) ^ (num2>10); true
+ }
+}
+```
From 5237b977584c3e426d10332e1a5feeef023a34da Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 8 Mar 2024 11:48:03 +0530
Subject: [PATCH 084/236] Update README.md
---
section7/README.md | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index 0d6399d..4108963 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -358,6 +358,12 @@ public class LogicalOperatorsDemo {
}
}
```
+## Compound Logical Assignment operator in Java
+#### Example
+```java
+
+```
+
From 327583a76a47a6a70d391be5ea0ba3b58af75e39 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 8 Mar 2024 19:33:18 +0530
Subject: [PATCH 085/236] Update README.md
---
section7/README.md | 29 +++++++++++++++++++++++++++++
1 file changed, 29 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index 4108963..4dac7e9 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -359,10 +359,39 @@ public class LogicalOperatorsDemo {
}
```
## Compound Logical Assignment operator in Java
+Compound logical assignment operators in Java are shorthand operators used to combine an arithmetic or bitwise operation with an assignment. These operators perform the operation and then assign the result to the variable in a single step. They are convenient for modifying variables based on certain conditions efficiently.
#### Example
```java
+public class LogicalOperatorsDemo {
+
+ public static void main(String[] args) {
+
+ boolean b1 = true;
+ b1 &= true;
+ System.out.println(b1);// true
+
+ boolean b2 = true;
+ b2 |= false;
+ System.out.println(b2); //true
+
+ boolean b3 = true;
+ b3 ^= false;
+ System.out.println(b3); // true
+ }
+
+}
```
+## Biwise Operators in Java
+Bitwise operators in Java are used to perform operations on individual bits of integer operands. These operators work on the binary representation of numbers. Java provides six bitwise operators :
+### Bitwise NOT Operator in Java
+The bitwise `NOT` operator in Java, denoted by `~`, is a unary operator that flips the bits of its operand. It's used to perform bitwise negation on individual bits of an integer operand.
+### Usage
+The bitwise NOT operator flips each bit of its operand. If a bit is 1, it becomes 0, and if it's 0, it becomes 1.
+#### Example
+Let's say a is 5, represented in binary as 101. Applying the bitwise NOT operator to a will flip each bit :
+
+
From afcf2365ed8b7610189d7396584aa03476c3feb4 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 8 Mar 2024 22:12:16 +0530
Subject: [PATCH 086/236] Update README.md
---
section7/README.md | 97 +++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 96 insertions(+), 1 deletion(-)
diff --git a/section7/README.md b/section7/README.md
index 4dac7e9..74bab21 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -389,7 +389,102 @@ The bitwise `NOT` operator in Java, denoted by `~`, is a unary operator that fli
### Usage
The bitwise NOT operator flips each bit of its operand. If a bit is 1, it becomes 0, and if it's 0, it becomes 1.
#### Example
-Let's say a is 5, represented in binary as 101. Applying the bitwise NOT operator to a will flip each bit :
+```java
+public class BitwiseOperatorsDemo {
+
+ public static void main(String[] args) {
+
+ int x = 9;
+ int y = ~x;
+ System.out.println(y); // -10
+ }
+
+}
+```
+## Bitwise AND Operator
+The BITWISE AND operator (`&`) in Java is a binary operator that performs a bitwise AND operation between two integer operands. It evaluates to 1 if both corresponding bits in the operands are 1; otherwise, it evaluates to 0.
+#### Example
+```java
+public class BitwiseAndExample {
+ public static void main(String[] args) {
+ int num1 = 10; // Binary: 1010
+ int num2 = 6; // Binary: 0110
+ int result = num1 & num2; // Binary result: 0010 (2 in decimal)
+ System.out.println("Result of BITWISE AND operation: " + result); // 2
+ }
+}
+```
+## Bitwise OR Operator
+In Java, the bitwise OR operator (`|`) is a binary operator that performs a bitwise OR operation between two integer operands. It evaluates to 1 if either or both of the corresponding bits in the operands are 1 else 0.
+#### Example
+```java
+int a = 5; // 101 in binary
+int b = 3; // 011 in binary
+int result = a | b; // result = 7 (111 in binary)
+```
+In this example, the bitwise OR operation is performed between a and b, resulting in 7 which is 111 in binary.
+### Usage
+- Combining Flags: Bitwise OR is commonly used to combine or set specific flags or options in programming.
+- Masking: It's used in bitmasking techniques to manipulate individual bits or groups of bits within an integer.
+### Notes
+- The bitwise OR operator evaluates each bit position independently.
+- It sets the corresponding bit in the result to 1 if either of the bits in the operands is 1.
+### Alternatives
+**Logical OR (`||`) Operator :** This is a conditional OR operator used for boolean expressions. It evaluates to true if either operand is true.
+### Conclusion
+The bitwise OR operator in Java provides a powerful tool for manipulating individual bits within integers. It's commonly used in low-level programming and for various bitwise operations.
+## Bitwise XOR Operator
+In Java, the bitwise XOR operator (`^`) is used to perform a bitwise exclusive OR operation between two integers.It compares each bit two operands, and if the bits are diffrent then the resulting bit is 1, otherwise resulting bit is 0.
+#### Example
+```java
+int a = 5; // 101 in binary
+int b = 3; // 011 in binary
+
+int result = a ^ b; // result = 110 in binary, which is 6 in decimal
+
+System.out.println("5 ^ 3 = " + result); // Output: 6
+```
+### Usage
+The bitwise XOR operator is commonly used for various purposes such as :
+- Flipping bits: XORing a value with a bit pattern of all 1s flips all of its bits.
+- Encrypting and decrypting data.
+- Checking for differences between two bit patterns.
+- Swapping values without using a temporary variable.
+### Important Notes
+- The operands for the XOR operator must be of integer types (byte, short, int, long, char).
+- The XOR operation sets a bit to 1 if it is different in the operands, otherwise sets it to 0.
+### Conclusion
+The bitwise XOR operator (^) in Java is a fundamental tool for performing bitwise exclusive OR operations between integers. Understanding its behavior and applications is essential for working with binary data and performing bitwise manipulations efficiently.
+## Left Shift Operator
+In Java, the left shift operator (`<<`) is a bitwise operator used to shift the bits of a number to the left. It is used to perform multiplication by powers of two.
+
+Where:
+- `operand` is the value to be shifted.
+- `numBits` is the number of positions to shift the bits to the left.
+
+## Example
+
+```java
+int num = 5; // Binary representation: 00000101
+
+// Left shifting by 2 bits
+int result = num << 2; // Binary representation: 00010100
+
+System.out.println(result); // Output: 20
+```
+In this example, the binary representation of 5 is 00000101. When we left shift this number by 2 bits (num << 2), the result is 00010100, which is equivalent to 20 in decimal.
+
+### Usage
+- The left shift operator is commonly used for performing quick multiplication or division by powers of two.
+- It can also be used for bit manipulation and optimizing certain algorithms.
+### Notes
+- Left shifting a number by n bits is equivalent to multiplying the number by 2^n.
+- The leftmost bits that are shifted out of the number are discarded, and zero bits are shifted in from the right.
+
+
+
+
+
From 781be5d7f8ddf41643b7db668580b1f20ef1fbbc Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 8 Mar 2024 23:29:26 +0530
Subject: [PATCH 087/236] Update README.md
---
section7/README.md | 97 ++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 97 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index 74bab21..940be6e 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -480,6 +480,103 @@ In this example, the binary representation of 5 is 00000101. When we left shift
### Notes
- Left shifting a number by n bits is equivalent to multiplying the number by 2^n.
- The leftmost bits that are shifted out of the number are discarded, and zero bits are shifted in from the right.
+## Signed Right Shift Operator
+In Java, the signed right shift operator (>>) is used to shift the bits of a number to the right. It preserves the sign of the number, meaning it fills the shifted positions with the sign bit (the leftmost bit) of the original number.
+### Syntax
+The syntax for the signed right shift operator is as follows:
+```java
+result = number >> shiftAmount;
+```
+Where :
+- number is the integer value whose bits are to be shifted.
+- shiftAmount is the number of positions to shift the bits.
+### Example
+```java
+int x = 10; // Binary: 0000 1010
+int shifted = x >> 2; // Shift right by 2 positions // Binary: 0000 0010
+System.out.println(shifted); // 2
+
+```
+After the shift operation, shifted will have the value 2, because the rightmost two bits are discarded.
+### Behavior
+- The signed right shift operator preserves the sign of the number.
+- If the number is positive, it fills the vacant positions on the left with 0.
+- If the number is negative, it fills the vacant positions on the left with 1.
+### Applications
+- It is commonly used in optimizing division by powers of 2.
+- It can be used for efficient multiplication or division by 2^n, where n is the shift amount.
+### Note
+- When shifting right by n positions, the number effectively gets divided by 2^n.
+- Care should be taken when using the signed right shift operator with negative numbers to avoid unexpected results.
+### Conclusion
+The signed right shift operator (>>) in Java is a useful tool for shifting the bits of a number to the right while preserving its sign. Understanding its behavior and applications can help in writing efficient and concise code.
+## Unsigned Right Shift Operator (>>>)
+In Java, the Unsigned Right Shift operator (`>>>`) is used to shift the bits of a number to the right by a specified number of positions. Unlike the Right Shift operator (`>>`), the Unsigned Right Shift operator always fills the leftmost bits with zeros, irrespective of the sign bit.
+### Syntax
+The syntax for the Unsigned Right Shift operator is :
+- result = value >>> numPositions;
+- Here, `value` is the number whose bits are to be shifted, `numPositions` is the number of positions to shift the bits to the right, and `result` is the variable that will hold the result of the operation.
+#### Example
+
+```java
+int number = 10; // binary representation: 0000 0101
+int result = number >>> 1; // Shift right by 1 position // binary representation : 0000 0010
+System.out.println(result) //2
+```
+### Use Cases
+- Dividing by powers of 2: Unsigned Right Shift is often used for dividing by powers of 2 because it's a fast operation.
+- Working with binary data: When dealing with binary data and you need to shift bits to the right while maintaining the unsigned nature of the data, the Unsigned Right Shift operator comes in handy.
+### Notes
+- The Unsigned Right Shift operator (>>>) does not preserve the sign bit, which means it treats the number as if it were positive, shifting all bits to the right and filling the leftmost bits with zeros.
+- This operator is useful when working with binary data or when you want to perform logical right shifts without considering the sign of the number.
+## Compound Assignment Bitwise Operators
+Compound assignment bitwise operators combine a bitwise operation with assignment, allowing you to perform an operation and assign the result to the same variable in a single statement.
+### Compound Assignment Bitwise And Operator
+#### Example
+```
+int x = 10; //binary representation :1010
+int y = 6; // binary representation :0110
+ x &= y
+System.out.println(x) //2 // binary representation :0010
+```
+Please practice remaing `Compound Assignment Bitwise And Operator`
+
+## Ternary Conditional Operator
+The Ternary Conditional Operator, often referred to as the "conditional operator" or "ternary operator", is a concise way to express conditional statements in Java. It provides a shorthand for the if-else statement.
+### Syntax
+```
+condition ? expression1 : expression2
+```
+- If the condition evaluates to true, the expression1 is executed.
+- If the condition evaluates to false, the expression2 is executed.
+#### Example
+```java
+int x = 10;
+int y = 5;
+int max = (x > y) ? x : y;
+System.out.println("The maximum value is: " + max);// 10
+```
+In this example :
+- If `x` is greater than `y`, `x` is assigned to max.
+- If `y` is greater than or equal to `x`, `y` is assigned to max.
+### Advantages
+- **Conciseness :** The ternary operator reduces the amount of code required for simple conditional statements.
+- **Readability :** It can make the code more readable, especially for simple conditions.
+### Limitations
+- Complexity: Overuse of nested ternary operators can lead to decreased readability and maintainability.
+- Not Suitable for Complex Logic: For complex conditions, using if-else statements is often more appropriate.
+### Conclusion
+The Ternary Conditional Operator is a powerful tool for writing concise conditional statements in Java. It can improve code readability and reduce verbosity for simple conditions. However, it should be used judiciously and avoided for complex logic to maintain code clarity and understandability.
+
+
+
+
+
+
+
+
+
+
From 5617abd4c8fada0b7fe128457ad9c2baa011ede2 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 19:08:54 +0530
Subject: [PATCH 088/236] Create README.md
---
section8/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section8/README.md
diff --git a/section8/README.md b/section8/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section8/README.md
@@ -0,0 +1 @@
+
From 603f50ebf4ddc99d0f9c8fe8127a854703424e53 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 19:11:49 +0530
Subject: [PATCH 089/236] Update README.md
---
section8/README.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/section8/README.md b/section8/README.md
index 8b13789..1344a19 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -1 +1,2 @@
-
+# Control Flow Statements in Java
+Control flow statements in Java are used to control the execution flow of a program. They allow you to make decisions, execute code repeatedly, and branch execution based on conditions. Java provides several types of control flow statements, including:
From 3cc5f90f437b28630c49ac5659e095e845373bbf Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 19:21:44 +0530
Subject: [PATCH 090/236] Update README.md
---
section8/README.md | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
diff --git a/section8/README.md b/section8/README.md
index 1344a19..c0738e0 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -1,2 +1,23 @@
# Control Flow Statements in Java
Control flow statements in Java are used to control the execution flow of a program. They allow you to make decisions, execute code repeatedly, and branch execution based on conditions. Java provides several types of control flow statements, including:
+## If-else Statements
+If-else statements are fundamental to programming as they allow you to make decisions based on certain conditions.
+### Example
+```java
+public class FindNumber {
+ public static void main(String[] args) {
+ int num = 10;
+
+ if (num > 0) {
+ System.out.println("Number is positive");
+ } else {
+ System.out.println("Number is non-positive");
+ }
+ }
+}
+```
+## Nested If-else
+### Example
+```java
+
+
From 120d2ae5bfe6d41a67b17f111585a822cc3705ce Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 19:32:54 +0530
Subject: [PATCH 091/236] Update README.md
---
section8/README.md | 43 ++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 42 insertions(+), 1 deletion(-)
diff --git a/section8/README.md b/section8/README.md
index c0738e0..bae67f7 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -16,8 +16,49 @@ public class FindNumber {
}
}
```
-## Nested If-else
+## if, else-if, else
### Example
```java
+public class FindTheDay {
+
+ public static void main(String[] args) {
+ String whatIsToday = "Monday";
+ // Approach 1
+
+ if(whatIsToday.equals("Monday")) {
+ System.out.println("It is weekday");
+ } else if (whatIsToday.equals("Tuesday")) {
+ System.out.println("It is weekday");
+ } else if (whatIsToday.equals("Wednesday")) {
+ System.out.println("It is weekday");
+ } else if (whatIsToday.equals("Thursday")) {
+ System.out.println("It is weekday");
+ } else if (whatIsToday.equals("Friday")) {
+ System.out.println("It is weekday");
+ } else if (whatIsToday.equals("Saturday")) {
+ System.out.println("It is weekend");
+ } else if (whatIsToday.equals("Sunday")) {
+ System.out.println("It is weekend");
+ } else {
+ System.out.println("Invalid input. Please check the same");
+ }
+
+ //Approach 2
+
+ if(whatIsToday.equals("Monday") || whatIsToday.equals("Tuesday")
+ || whatIsToday.equals("Wednesday") || whatIsToday.equals("Thursday")
+ || whatIsToday.equals("Friday")) {
+ System.out.println("It is weekday");
+ } else if (whatIsToday.equals("Saturday") || whatIsToday.equals("Sunday")) {
+ System.out.println("It is weekend");
+ } else {
+ System.out.println("Invalid input. Please check the same");
+ }
+
+ }
+
+}
+```
+## Nested If-else
From 4fc769c668d5616df93477f2b021296880deb89e Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 19:48:42 +0530
Subject: [PATCH 092/236] Update README.md
---
section8/README.md | 30 ++++++++++++++++++++++++++++++
1 file changed, 30 insertions(+)
diff --git a/section8/README.md b/section8/README.md
index bae67f7..68eb10f 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -60,5 +60,35 @@ public class FindTheDay {
}
```
## Nested If-else
+```java
+public class MessageForDay {
+
+ public static void main(String[] args) {
+
+ String dayOfWeek = "Wednesday";
+
+ if (dayOfWeek.equals("Saturday") || dayOfWeek.equals("Sunday")) {
+ System.out.println("Hooray, it's the weekend!");
+ if (dayOfWeek.equals("Saturday")) {
+ System.out.println("Time for a relaxing day or maybe some outdoor activities!");
+ } else {
+ System.out.println("Lazy Sunday vibes perfect for a cozy day indoors.");
+ }
+ } else {
+ System.out.println("It's a weekday. Time to work or attend classes.");
+ if (dayOfWeek.equals("Wednesday") || dayOfWeek.equals("Thursday")
+ || dayOfWeek.equals("Friday")) {
+ System.out.println("Midweek hustle! Keep going, the weekend is approaching.");
+ } else {
+ System.out.println("Monday blues? Grab some coffee and power through the day!");
+ }
+ }
+
+ }
+
+}
+```
+## Ternary Operator
+The ternary operator is a concise way of writing if-else statements in Java. It's also known as the conditional operator. It's a one-liner syntax that evaluates a condition and returns one of two values, depending on whether the condition is true or false.
From 2216487a683ee564d86a051c82bccee3c9405c7c Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 19:55:11 +0530
Subject: [PATCH 093/236] Update README.md
---
section8/README.md | 28 ++++++++++++++++++++++++++++
1 file changed, 28 insertions(+)
diff --git a/section8/README.md b/section8/README.md
index 68eb10f..eb18039 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -90,5 +90,33 @@ public class MessageForDay {
```
## Ternary Operator
The ternary operator is a concise way of writing if-else statements in Java. It's also known as the conditional operator. It's a one-liner syntax that evaluates a condition and returns one of two values, depending on whether the condition is true or false.
+### Example
+```java
+public class TernaryOperator {
+
+ public static void main(String[] args) {
+ int x = 10;
+ int y;
+
+ y = x > 5 ? 20 : 30;
+ System.out.println(y);
+ sum(x, x > 5 ? 20 : 30 );
+ }
+
+ public static void sum (int x, int y) {
+ System.out.println(x+y);
+ }
+}
+```
+### Advantages
+- **Concise syntax :** It reduces code length compared to if-else statements, making code more readable and easier to maintain.
+- **Functional programming :** It allows for functional programming-style expressions, especially when used with lambda expressions.
+### Limitations
+- **Readability :** Overuse or complex nesting of ternary operators can reduce code readability.
+- **Limited to simple conditions :** Ternary operators are best suited for simple conditions. Complex conditions may be difficult to read or understand when expressed using the ternary operator.
+### Conclusion
+The ternary operator in Java provides a concise and elegant way to express conditional statements. When used appropriately, it can improve code readability and maintainability. However, it's essential to use it judiciously and avoid overcomplicating expressions.
+
+
From 9b4480f1adbdef40d9173b6c417647feff15009e Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 20:01:02 +0530
Subject: [PATCH 094/236] Update README.md
---
section8/README.md | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/section8/README.md b/section8/README.md
index eb18039..5057e29 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -116,6 +116,11 @@ public class TernaryOperator {
- **Limited to simple conditions :** Ternary operators are best suited for simple conditions. Complex conditions may be difficult to read or understand when expressed using the ternary operator.
### Conclusion
The ternary operator in Java provides a concise and elegant way to express conditional statements. When used appropriately, it can improve code readability and maintainability. However, it's essential to use it judiciously and avoid overcomplicating expressions.
+## Switch-Case Statements
+Switch-case statements in Java provide a convenient way to execute different blocks of code based on the value of a variable or expression. They offer a cleaner alternative to multiple `if-else` statements when dealing with multiple possible conditions.
+### Example
+
+
From 9da131f04bc6ce7f096bf58b1665b23f9720e37c Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 20:20:55 +0530
Subject: [PATCH 095/236] Update README.md
---
section8/README.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 46 insertions(+)
diff --git a/section8/README.md b/section8/README.md
index 5057e29..73e1778 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -119,6 +119,52 @@ The ternary operator in Java provides a concise and elegant way to express condi
## Switch-Case Statements
Switch-case statements in Java provide a convenient way to execute different blocks of code based on the value of a variable or expression. They offer a cleaner alternative to multiple `if-else` statements when dealing with multiple possible conditions.
### Example
+```java
+public class SwitchCaseDemo {
+
+ public static void main(String[] args) {
+
+ String fruitName = "Banana";
+
+ switch (fruitName) {
+
+ case "Banana":
+ case "Apple":
+ System.out.println("$ 1.0 charged");
+ break;
+ case "Grapes":
+ System.out.println("$ 2.0 charged");
+ break;
+ case "Pineapple":
+ System.out.println("$ 2.5 charged");
+ break;
+ case "Mango":
+ System.out.println("$ 3.0 charged");
+ break;
+ default:
+ System.out.println("Pick a valid fruit");
+ break;
+ // Output : $ 1.0 charged
+ }
+
+ }
+
+}
+```
+- **switch :** Begins the switch statement and evaluates the expression.
+- **case value :** Specifies a value to compare the expression against.
+- **break :** Terminates the switch block. Without a break statement, execution will continue to the next case.
+- **default :** Executes if the expression doesn't match any of the cases. It's optional but recommended for handling unexpected values.
+### Key Points
+- **Expression :** The variable or expression whose value is being compared against different cases. It must evaluate to a primitive type (such as int, char, or enum) or String (Java 7 and later).
+- **Values :** Each case specifies a value to compare the expression against. These values must be constant expressions.
+- **Execution Flow :** When a match is found, the corresponding code block executes. If there's no break, execution will continue to the next case. The default case, if present, is executed if no matches are found.
+- **Break Statement :** Each case block should end with a break statement to prevent fall-through to subsequent cases.
+- **Default Case :** It's good practice to include a default case to handle unexpected values gracefully.
+## Switch Expression
+A switch expression is a control flow statement that evaluates an expression and selects one of several code blocks to execute, depending on the value of the expression. It's an enhanced version of the traditional switch statement found in many programming languages.
+#### Example
+
From b0df112da2e5a9c0ecb6f3213fd9c7a583cc90db Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 20:34:28 +0530
Subject: [PATCH 096/236] Update README.md
---
section8/README.md | 84 +++++++++++++++++++++++++++++++++++++++++-----
1 file changed, 76 insertions(+), 8 deletions(-)
diff --git a/section8/README.md b/section8/README.md
index 73e1778..c9e36b5 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -2,7 +2,7 @@
Control flow statements in Java are used to control the execution flow of a program. They allow you to make decisions, execute code repeatedly, and branch execution based on conditions. Java provides several types of control flow statements, including:
## If-else Statements
If-else statements are fundamental to programming as they allow you to make decisions based on certain conditions.
-### Example
+### Example π‘
```java
public class FindNumber {
public static void main(String[] args) {
@@ -17,7 +17,7 @@ public class FindNumber {
}
```
## if, else-if, else
-### Example
+### Example π‘
```java
public class FindTheDay {
@@ -90,7 +90,7 @@ public class MessageForDay {
```
## Ternary Operator
The ternary operator is a concise way of writing if-else statements in Java. It's also known as the conditional operator. It's a one-liner syntax that evaluates a condition and returns one of two values, depending on whether the condition is true or false.
-### Example
+### Example π‘
```java
public class TernaryOperator {
@@ -108,17 +108,17 @@ public class TernaryOperator {
}
}
```
-### Advantages
+### Advantages π
- **Concise syntax :** It reduces code length compared to if-else statements, making code more readable and easier to maintain.
- **Functional programming :** It allows for functional programming-style expressions, especially when used with lambda expressions.
-### Limitations
+### Limitations π«
- **Readability :** Overuse or complex nesting of ternary operators can reduce code readability.
- **Limited to simple conditions :** Ternary operators are best suited for simple conditions. Complex conditions may be difficult to read or understand when expressed using the ternary operator.
-### Conclusion
+### Conclusion π
The ternary operator in Java provides a concise and elegant way to express conditional statements. When used appropriately, it can improve code readability and maintainability. However, it's essential to use it judiciously and avoid overcomplicating expressions.
## Switch-Case Statements
Switch-case statements in Java provide a convenient way to execute different blocks of code based on the value of a variable or expression. They offer a cleaner alternative to multiple `if-else` statements when dealing with multiple possible conditions.
-### Example
+### Example π‘
```java
public class SwitchCaseDemo {
@@ -163,7 +163,75 @@ public class SwitchCaseDemo {
- **Default Case :** It's good practice to include a default case to handle unexpected values gracefully.
## Switch Expression
A switch expression is a control flow statement that evaluates an expression and selects one of several code blocks to execute, depending on the value of the expression. It's an enhanced version of the traditional switch statement found in many programming languages.
-#### Example
+#### Example π‘
+```java
+public class SwitchExpressionDemo {
+
+ public static void main(String[] args) {
+ String fruitName = "Banana";
+ switch (fruitName) {
+ case "Banana", "Apple" -> System.out.println("$ 1.0 charged");
+ case "Grapes" -> System.out.println("$ 2.0 charged");
+ case "Pineapple" -> System.out.println("$ 2.5 charged");
+ case "Mango" -> System.out.println("$ 3.0 charged");
+ default -> System.out.println("Pick a valid fruit");
+ }
+
+ String output = switch (fruitName) {
+ case "Banana", "Apple" -> "$ 1.0 charged";
+ case "Grapes" -> "$ 2.0 charged";
+ case "Pineapple" -> "$ 2.5 charged";
+ case "Mango" -> "$ 3.0 charged";
+ default -> "Pick a valid fruit";
+ };
+
+ String day = "FRIDAY";
+
+ int numLetters = switch (day) {
+
+ case "MONDAY", "FRIDAY", "SUNDAY" -> {
+ System.out.println(6);
+ yield 6;
+ }
+ case "TUESDAY" -> {
+ System.out.println(7);
+ yield 7;
+ }
+ case "THURSDAY", "SATURDAY" -> {
+ System.out.println(8);
+ yield 8;
+ }
+ case "WEDNESDAY" -> {
+ System.out.println(9);
+ yield 9;
+ }
+ default -> {
+ System.out.println("Invalid Day");
+ yield 0;
+ }
+
+ };
+
+ }
+
+}
+```
+## While Statement
+In Java, the `while` statement is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. It is used when the number of iterations is not known beforehand and depends on the condition being evaluated.
+### Syntax
+```java
+```java
+while (condition) {
+ // Code block to be executed
+}
+```
+- The condition is a boolean expression. If it evaluates to true, the code block inside the loop will be executed. If it evaluates to false, the loop terminates, and the program continues with the next statement after the loop.
+- The code block within the curly braces {} contains the statements to be executed repeatedly.
+### Example
+```java
+
+
+
From 1ab543fac6b5204cd8e0ec0aee908ea0b5027065 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 20:39:50 +0530
Subject: [PATCH 097/236] Update README.md
---
section8/README.md | 35 +++++++++++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
diff --git a/section8/README.md b/section8/README.md
index c9e36b5..c987880 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -229,6 +229,41 @@ while (condition) {
- The code block within the curly braces {} contains the statements to be executed repeatedly.
### Example
```java
+public class WhileStatementDemo {
+
+ public static void main(String[] args) {
+
+ int i = 1;
+
+ while (i<=10 ) {
+ System.out.println(i);
+ i++;
+ }
+
+ while (true) {
+ System.out.println("I can print infinitely");
+ }
+ }
+}
+```
+### Key Points
+- Use the `while` loop when the number of iterations is not known beforehand.
+- Ensure that the condition eventually becomes false to avoid infinite loops.
+- The code block inside the while loop must contain statements that alter the variables involved in the condition to avoid an infinite loop.
+## Do-While Statement
+In Java, a do-while statement is used to execute a block of code repeatedly until a specified condition evaluates to false. Unlike the while loop, the do-while loop ensures that the block of code is executed at least once, even if the condition is initially false.
+### Syntax
+```java
+```java
+do {
+ // code block to be executed
+} while (condition);
+```
+- The code block within the do statement is executed first.
+- Then, the condition is evaluated.
+- If the condition is true, the code block will be executed again.
+- This process continues until the condition becomes false
+### Example
From fbb29c34d4c931f0e859f8f15bd120d858a7ddca Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 20:44:58 +0530
Subject: [PATCH 098/236] Update README.md
---
section8/README.md | 31 +++++++++++++++++++++++++++++++
1 file changed, 31 insertions(+)
diff --git a/section8/README.md b/section8/README.md
index c987880..700e3f1 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -264,6 +264,37 @@ do {
- If the condition is true, the code block will be executed again.
- This process continues until the condition becomes false
### Example
+```java
+public class DoWhileStatementDemo {
+
+ public static void main(String[] args) {
+
+ int n = 6;
+
+ do {
+ System.out.println(n);
+ n++;
+ } while ( n < 10);
+
+ }
+
+}
+```
+### Conclusion
+The do-while loop in Java is useful when you need to execute a block of code at least once, regardless of whether the condition is initially true or false. It's commonly used in situations where the exact number of iterations is not known beforehand.
+## for Loop
+In Java, the for loop provides a concise way to iterate over a range of values or elements in an array or collection. It consists of three parts: initialization, condition, and iteration expression.
+### Syntax
+```java
+for (initialization; condition; iteration) {
+ // code block to be executed
+}
+```
+- **Initialization :** Initializes the loop control variable.
+- **Condition :** Evaluates to true or false. If true, the code block is executed; if false, the loop terminates.
+- **Iteration :** Updates the loop control variable after each iteration.
+### Example
+
From f39fa3fc2d860f7b9ec1e9dd3049200ac57270ed Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 20:51:16 +0530
Subject: [PATCH 099/236] Update README.md
---
section8/README.md | 32 ++++++++++++++++++++++++++++++++
1 file changed, 32 insertions(+)
diff --git a/section8/README.md b/section8/README.md
index 700e3f1..ed18514 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -294,6 +294,38 @@ for (initialization; condition; iteration) {
- **Condition :** Evaluates to true or false. If true, the code block is executed; if false, the loop terminates.
- **Iteration :** Updates the loop control variable after each iteration.
### Example
+```java
+public class ForLoopDemo {
+
+ public static void main(String[] args) {
+ int result ;
+ for (int i = 1; i <= 10; i++) {
+ result = i * 9;
+ System.out.println("9 * " + i + " = "+ result);
+ }
+ }
+}
+```
+### Notes
+- The initialization step is executed only once at the beginning of the loop.
+- The condition is evaluated before each iteration. If it evaluates to false, the loop terminates.
+- The iteration expression is executed after each iteration.
+## Nested For Loops
+Nested for loops in Java are used when you need to iterate over a collection of items that contain another collection. This is commonly seen when dealing with multi-dimensional arrays or when you need to perform a task on each combination of elements from two or more collections.
+### Syntax
+```java
+for (initialization; condition; increment/decrement) {
+ // Outer loop
+ for (initialization; condition; increment/decrement) {
+ // Inner loop
+ // Code to be executed
+ }
+}
+```
+The outer loop controls the execution of the inner loop. It runs once for each iteration of the outer loop.
+### Example
+```java
+
From c408ff44db64f58ac0af219e07f86592b522c09f Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 20:56:41 +0530
Subject: [PATCH 100/236] Update README.md
---
section8/README.md | 38 ++++++++++++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
diff --git a/section8/README.md b/section8/README.md
index ed18514..a885adc 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -325,6 +325,44 @@ for (initialization; condition; increment/decrement) {
The outer loop controls the execution of the inner loop. It runs once for each iteration of the outer loop.
### Example
```java
+public class NestedForLoopDemo {
+
+ public static void main(String[] args) {
+
+ int number = 10;
+
+ for(int i = 1; i <= number; i++) {
+ for(int j =1; j<=number;j++) {
+ System.out.println(i + " x " + j + " = " + i*j);
+ }
+ }
+
+ int rows = 10;
+ for (int i =1; i <=rows; i ++ ) {
+ for (int j =1; j <=i; j++) {
+ System.out.print("*");
+ }
+ System.out.println();
+ }
+
+ }
+
+}
+```
+### Nested Loop Behavior
+When using nested loops, keep in mind that the inner loop runs to completion for each iteration of the outer loop. This means that the inner loop will run its entire course before the outer loop moves to its next iteration.
+### Advantages
+- Nested loops provide a way to handle complex iterations over multi-dimensional data structures.
+- They allow you to perform operations on combinations of elements from multiple collections.
+### Tips
+- Ensure that you are incrementing/decrementing loop variables properly to avoid infinite loops.
+- Be cautious of performance implications, especially with deeply nested loops and large datasets.
+### Conclusion
+Nested for loops in Java are a powerful tool for iterating over multi-dimensional data structures and handling combinations of elements. Understanding how to use them effectively can greatly enhance your ability to work with complex data.
+## Break Statement
+The `break` statement in Java is used to terminate the execution of a loop prematurely. When the `break` statement is encountered inside a loop, the loop is immediately terminated, and the program control resumes at the next statement following the loop.
+### Example
+
From 71513bc77dd758825d55d475845bc97f994da583 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 21:03:25 +0530
Subject: [PATCH 101/236] Update README.md
---
section8/README.md | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)
diff --git a/section8/README.md b/section8/README.md
index a885adc..8d07c44 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -362,6 +362,26 @@ Nested for loops in Java are a powerful tool for iterating over multi-dimensiona
## Break Statement
The `break` statement in Java is used to terminate the execution of a loop prematurely. When the `break` statement is encountered inside a loop, the loop is immediately terminated, and the program control resumes at the next statement following the loop.
### Example
+```java
+public class BreakExample {
+ public static void main(String[] args) {
+ for (int i = 0; i < 10; i++) {
+ if (i == 5) {
+ System.out.println("Reached the break statement, terminating loop.");
+ break;
+ }
+ System.out.println("Iteration: " + i); //5
+ }
+ }
+}
+
+```
+In this example, the loop terminates when the value of i becomes equal to 5, and the program control resumes at the statement following the loop.
+
+### Notes
+- The `break` statement can be used with for, while, and do-while loops.
+- When `break` is used inside nested loops, it only terminates the innermost loop.
+### continue Statement
From a0d74c54421a3f481cd21b825d6bdfc3a2ef9465 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 14 Mar 2024 21:19:33 +0530
Subject: [PATCH 102/236] Update README.md
---
section8/README.md | 93 +++++++++++++++++++++++++++++++++++++++-------
1 file changed, 80 insertions(+), 13 deletions(-)
diff --git a/section8/README.md b/section8/README.md
index 8d07c44..21e33a7 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -1,4 +1,4 @@
-# Control Flow Statements in Java
+# Control Flow Statements in Java
Control flow statements in Java are used to control the execution flow of a program. They allow you to make decisions, execute code repeatedly, and branch execution based on conditions. Java provides several types of control flow statements, including:
## If-else Statements
If-else statements are fundamental to programming as they allow you to make decisions based on certain conditions.
@@ -155,7 +155,7 @@ public class SwitchCaseDemo {
- **case value :** Specifies a value to compare the expression against.
- **break :** Terminates the switch block. Without a break statement, execution will continue to the next case.
- **default :** Executes if the expression doesn't match any of the cases. It's optional but recommended for handling unexpected values.
-### Key Points
+### Key Points π
- **Expression :** The variable or expression whose value is being compared against different cases. It must evaluate to a primitive type (such as int, char, or enum) or String (Java 7 and later).
- **Values :** Each case specifies a value to compare the expression against. These values must be constant expressions.
- **Execution Flow :** When a match is found, the corresponding code block executes. If there's no break, execution will continue to the next case. The default case, if present, is executed if no matches are found.
@@ -227,7 +227,7 @@ while (condition) {
```
- The condition is a boolean expression. If it evaluates to true, the code block inside the loop will be executed. If it evaluates to false, the loop terminates, and the program continues with the next statement after the loop.
- The code block within the curly braces {} contains the statements to be executed repeatedly.
-### Example
+### Example π‘
```java
public class WhileStatementDemo {
@@ -246,7 +246,7 @@ public class WhileStatementDemo {
}
}
```
-### Key Points
+### Key Points π
- Use the `while` loop when the number of iterations is not known beforehand.
- Ensure that the condition eventually becomes false to avoid infinite loops.
- The code block inside the while loop must contain statements that alter the variables involved in the condition to avoid an infinite loop.
@@ -263,7 +263,7 @@ do {
- Then, the condition is evaluated.
- If the condition is true, the code block will be executed again.
- This process continues until the condition becomes false
-### Example
+### Example π‘
```java
public class DoWhileStatementDemo {
@@ -280,7 +280,7 @@ public class DoWhileStatementDemo {
}
```
-### Conclusion
+### Conclusion π
The do-while loop in Java is useful when you need to execute a block of code at least once, regardless of whether the condition is initially true or false. It's commonly used in situations where the exact number of iterations is not known beforehand.
## for Loop
In Java, the for loop provides a concise way to iterate over a range of values or elements in an array or collection. It consists of three parts: initialization, condition, and iteration expression.
@@ -293,7 +293,7 @@ for (initialization; condition; iteration) {
- **Initialization :** Initializes the loop control variable.
- **Condition :** Evaluates to true or false. If true, the code block is executed; if false, the loop terminates.
- **Iteration :** Updates the loop control variable after each iteration.
-### Example
+### Example π‘
```java
public class ForLoopDemo {
@@ -306,7 +306,7 @@ public class ForLoopDemo {
}
}
```
-### Notes
+### Notes π
- The initialization step is executed only once at the beginning of the loop.
- The condition is evaluated before each iteration. If it evaluates to false, the loop terminates.
- The iteration expression is executed after each iteration.
@@ -323,7 +323,7 @@ for (initialization; condition; increment/decrement) {
}
```
The outer loop controls the execution of the inner loop. It runs once for each iteration of the outer loop.
-### Example
+### Example π‘
```java
public class NestedForLoopDemo {
@@ -351,17 +351,17 @@ public class NestedForLoopDemo {
```
### Nested Loop Behavior
When using nested loops, keep in mind that the inner loop runs to completion for each iteration of the outer loop. This means that the inner loop will run its entire course before the outer loop moves to its next iteration.
-### Advantages
+### Advantages π
- Nested loops provide a way to handle complex iterations over multi-dimensional data structures.
- They allow you to perform operations on combinations of elements from multiple collections.
### Tips
- Ensure that you are incrementing/decrementing loop variables properly to avoid infinite loops.
- Be cautious of performance implications, especially with deeply nested loops and large datasets.
-### Conclusion
+### Conclusion π
Nested for loops in Java are a powerful tool for iterating over multi-dimensional data structures and handling combinations of elements. Understanding how to use them effectively can greatly enhance your ability to work with complex data.
## Break Statement
The `break` statement in Java is used to terminate the execution of a loop prematurely. When the `break` statement is encountered inside a loop, the loop is immediately terminated, and the program control resumes at the next statement following the loop.
-### Example
+### Example π‘
```java
public class BreakExample {
public static void main(String[] args) {
@@ -378,10 +378,77 @@ public class BreakExample {
```
In this example, the loop terminates when the value of i becomes equal to 5, and the program control resumes at the statement following the loop.
-### Notes
+### Notes π
- The `break` statement can be used with for, while, and do-while loops.
- When `break` is used inside nested loops, it only terminates the innermost loop.
### continue Statement
+The `continu`e statement is used in Java to skip the rest of the code inside a loop for the current iteration and proceed to the next iteration. It is mainly used within loops to control the flow of execution based on certain conditions.
+### How it Works
+When the `continue` statement is encountered inside a loop, the control immediately jumps to the next iteration of the loop, skipping any remaining code within the current iteration.
+### Example π‘
+```java
+for (int i = 0; i < 5; i++) {
+ if (i == 2) {
+ continue;
+ }
+ System.out.print(i+" ");
+}
+```
+In this example, when i is equal to 2, the `continue` statement is executed, causing the loop to skip the current iteration. As a result, the output will be:0 1 3 4
+### Use Cases
+- **Skipping Certain Iterations :** It can be used to skip certain iterations of a loop based on specific conditions, improving the efficiency of the code.
+- **Avoiding Nested if Statements :** It can help avoid deeply nested if statements by allowing you to skip iterations directly within the loop.
+### Notes π
+- The `continue` statement can only be used within loops (for, while, do-while).
+- If the `continue` statement is encountered in a nested loop, it only affects the innermost loop.
+### Conclusion π
+The `continue` statement in Java provides a way to control the flow of execution within loops, allowing you to skip certain iterations based on conditions. It is a useful tool for improving the efficiency and readability of your code.
+## Local Variables
+Local variables in Java are variables that are declared within a method, constructor, or block of code. These variables are only accessible within the scope in which they are declared.
+### Declaration and Initialization
+Local variables must be declared and initialized before they can be used. Here's how you can declare and initialize a local variable in Java:
+```java
+public class LocalVariablesExample {
+ public void exampleMethod() {
+ // Declaration and initialization of a local variable
+ int localVar = 10;
+ System.out.println("The value of localVar is: " + localVar);
+ }
+}
+```
+In this example, localVar is a local variable of type int declared within the exampleMethod() method.
+### Scope
+The scope of a local variable is limited to the block of code in which it is declared. Once the block of code is exited, the variable goes out of scope and cannot be accessed anymore. Here's an example illustrating the scope of local variables:
+```java
+public class LocalVariablesScopeExample {
+ public void exampleMethod() {
+ int localVar = 10;
+ System.out.println("Inside exampleMethod, localVar is: " + localVar); // 10
+
+ // localVar is accessible only within exampleMethod
+ }
+
+ public void anotherMethod() {
+ // Uncommenting the line below will cause a compilation error
+ // System.out.println("Inside anotherMethod, localVar is: " + localVar);
+
+ // localVar is not accessible here
+ }
+}
+```
+In this example, localVar is accessible only within the `exampleMethod()` method and cannot be accessed from `anotherMethod()`.
+### Final Thoughts
+Local variables are crucial in Java programming as they provide a way to store and manipulate data within a specific context or scope. Understanding their scope and usage is essential for writing efficient and bug-free code.
+
+## Conclusion π
+Understanding control flow statements is essential for writing efficient and structured Java code. By mastering if-else statements, switch statements, for loops, while loops, and do-while loops, you gain the ability to control the flow of your program, making it more dynamic and responsive to different conditions.
+
+As you continue to develop your Java programming skills, remember to choose the appropriate control flow statement for each scenario to ensure readability, maintainability, and performance of your code. Experiment with different control flow constructs and explore their nuances to become proficient in using them effectively.
+
+By referring to the examples provided in this documentation and experimenting with your own code, you'll build a solid foundation in control flow statements, empowering you to write more robust and efficient Java applications.
+
+Happy coding! π
+
From 5dbfb4bd4c8127f10ffc0f29090588912c332a99 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 15 Mar 2024 12:25:49 +0530
Subject: [PATCH 103/236] Create README.md
---
section9/src/com/eazybytes/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section9/src/com/eazybytes/README.md
diff --git a/section9/src/com/eazybytes/README.md b/section9/src/com/eazybytes/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section9/src/com/eazybytes/README.md
@@ -0,0 +1 @@
+
From d9bfbc512714729c328a9fc816c98dabca2f6778 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 15 Mar 2024 20:36:14 +0530
Subject: [PATCH 104/236] Update README.md
---
section8/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section8/README.md b/section8/README.md
index 21e33a7..c5c81aa 100644
--- a/section8/README.md
+++ b/section8/README.md
@@ -1,4 +1,4 @@
-# Control Flow Statements in Java
+# Control Flow Statements in Java
Control flow statements in Java are used to control the execution flow of a program. They allow you to make decisions, execute code repeatedly, and branch execution based on conditions. Java provides several types of control flow statements, including:
## If-else Statements
If-else statements are fundamental to programming as they allow you to make decisions based on certain conditions.
From e96cc658f7f222d9cbd17dad7c41737841e7cb69 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 15 Mar 2024 20:47:05 +0530
Subject: [PATCH 105/236] Update README.md
---
section9/src/com/eazybytes/README.md | 88 ++++++++++++++++++++++++++++
1 file changed, 88 insertions(+)
diff --git a/section9/src/com/eazybytes/README.md b/section9/src/com/eazybytes/README.md
index 8b13789..a73d0a1 100644
--- a/section9/src/com/eazybytes/README.md
+++ b/section9/src/com/eazybytes/README.md
@@ -1 +1,89 @@
+# Java Packages
+Java packages are a way of organizing classes into namespaces, providing modularity and encapsulation. This README explores the benefits of using packages in Java and how they contribute to better code organization and maintenance.
+## Benefits of Java Packages
+1. **Modularity**
+- Packages allow you to partition code into logical units, making it easier to manage and understand.
+- Modules can be developed, tested, and maintained independently, enhancing scalability and collaboration among developers.
+
+### 2. **Encapsulation**
+ - Packages enable access control through modifiers like `public`, `protected`, and `private`, ensuring that classes and members are only accessible where necessary.
+ - Encapsulation helps in hiding implementation details, reducing dependencies and making the code more maintainable.
+
+### 3. **Name Collision Avoidance**
+ - Packages prevent naming conflicts by providing a hierarchical namespace. Classes within different packages can have the same name without conflicts.
+ - This helps in avoiding clashes, especially in large projects or when integrating third-party libraries.
+
+### 4. **Code Reusability**
+ - Packages facilitate code reuse by allowing classes to be organized into reusable components.
+ - Libraries packaged as JAR files can be shared across projects, promoting code reuse and reducing redundancy.
+
+### 5. **Versioning and Dependency Management**
+ - Packages provide a mechanism for versioning, allowing different versions of libraries to coexist.
+ - Dependency management tools like Maven and Gradle leverage package management systems to resolve and download dependencies automatically.
+## Usage
+To utilize packages in Java, follow these steps:
+
+1. **Package Declaration**: At the beginning of your Java source files, declare the package using the `package` keyword followed by the package name.
+ ```java
+ package com.example.myproject;
+ ```
+**2. Class Organization:** Organize your classes within packages according to their functionality or domain.
+```java
+package com.example.myproject;
+
+public class MyClass {
+ // Class members and methods
+}
+```
+**3. Import Statements:** To use classes from other packages, import them using the import statement.
+
+```java
+import com.example.otherpackage.OtherClass;
+```
+**4. Access Modifiers:** Use access modifiers (public, protected, private) to control access to classes and members within packages.
+
+```java
+package com.example.myproject;
+
+public class MyClass {
+ private int myPrivateField;
+ // Other members...
+}
+```
+### Conclusion
+Java packages offer several benefits including modularity, encapsulation, name collision avoidance, code reusability, and dependency management. By organizing classes into packages, developers can create more maintainable, scalable, and reusable software components.
+## Using Package Members with Import Statement in Java
+This guide explains how to effectively use package members in your Java code by utilizing the `import` statement. Importing packages allows you to access classes, interfaces, and other members defined in external packages, making your code modular and organized.
+### Introduction
+In Java, a package is a namespace that organizes a set of related classes and interfaces. By grouping related items together, packages help in avoiding naming conflicts and provide a structured way to manage code.
+
+When working with packages, you can use the import statement to make classes and other members from external packages available in your code.
+
+### Importing Packages
+To import an entire package into your Java source file, you can use the import statement followed by the package name. For example:
+
+```java
+import java.util.*; // Importing the entire java.util package
+```
+This allows you to use any class or interface from the java.util package without specifying the package name each time.
+
+### Importing Specific Members
+If you only need certain classes or interfaces from a package, you can import them individually. For example:
+
+```java
+import java.util.ArrayList; // Importing only the ArrayList class from java.util package
+import java.util.List; // Importing only the List interface from java.util package
+```
+This approach keeps your code clean and avoids unnecessary imports.
+
+### Static Imports
+Java also supports static imports, which allow you to access static members of a class directly without qualifying them with the class name. For example:
+
+```java
+import static java.lang.Math.*; // Importing all static members of Math class
+```
+This lets you use static methods like sqrt() and pow() directly without prefixing them with Math..
+
+### Conclusion
+Using the import statement in Java is essential for managing packages and accessing their members efficiently. By importing packages and specific members, you can keep your code concise and readable, while static imports provide convenience when working with static members.
From be1aa6c1e1271a661d0f63f45ada784c7553c3e1 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 15 Mar 2024 20:57:45 +0530
Subject: [PATCH 106/236] Update README.md
---
section9/src/com/eazybytes/README.md | 73 ++++++++++++++++++++++++++++
1 file changed, 73 insertions(+)
diff --git a/section9/src/com/eazybytes/README.md b/section9/src/com/eazybytes/README.md
index a73d0a1..bb7e91c 100644
--- a/section9/src/com/eazybytes/README.md
+++ b/section9/src/com/eazybytes/README.md
@@ -86,4 +86,77 @@ This lets you use static methods like sqrt() and pow() directly without prefixin
### Conclusion
Using the import statement in Java is essential for managing packages and accessing their members efficiently. By importing packages and specific members, you can keep your code concise and readable, while static imports provide convenience when working with static members.
+## Java Access Modifiers for Methods and Fields
+Access modifiers in Java are keywords used to specify the accessibility of classes, methods, and fields. They control the level of visibility and accessibility to other classes and packages. Understanding access modifiers is crucial for encapsulation and maintaining the integrity of your codebase.
+
+### Access Modifiers for Fields
+** public :** Fields declared as public are accessible from any other class.
+
+```java
+public class MyClass {
+ public int publicField;
+}
+```
+**private :** Fields declared as private are accessible only within the same class.
+
+```java
+public class MyClass {
+ private int privateField;
+}
+```
+**protected :** Fields declared as protected are accessible within the same package and subclasses.
+```java
+public class MyClass {
+ protected int protectedField;
+}
+```
+** default (no modifier) :** Fields with no explicit modifier are accessible within the same package.
+
+```java
+public class MyClass {
+ int defaultField;
+}
+```
+### Access Modifiers for Methods
+**public :** Methods declared as public are accessible from any other class.
+
+```java
+public class MyClass {
+ public void publicMethod() {
+ // Method implementation
+ }
+}
+```
+**private :** Methods declared as private are accessible only within the same class.
+
+```java
+public class MyClass {
+ private void privateMethod() {
+ // Method implementation
+ }
+}
+```
+**protected :** Methods declared as protected are accessible within the same package and subclasses.
+```java
+public class MyClass {
+ protected void protectedMethod() {
+ // Method implementation
+ }
+}
+```
+**default (no modifier) :** Methods with no explicit modifier are accessible within the same package.
+
+```java
+public class MyClass {
+ void defaultMethod() {
+ // Method implementation
+ }
+}
+```
+### Summary
+- **public :** Accessible from anywhere.
+- **private :** Accessible only within the same class.
+- **protected :** Accessible within the same package and subclasses.
+- **default (no modifier) :** Accessible within the same package.
+- Understanding these access modifiers will help you design more robust and secure Java applications.
From 198a3f73c0645c1e539b5c544472180f7712019f Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 18 Mar 2024 12:30:29 +0530
Subject: [PATCH 107/236] Create README.md
---
section_10/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_10/README.md
diff --git a/section_10/README.md b/section_10/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_10/README.md
@@ -0,0 +1 @@
+
From fe43635e495aef1a516340081081c23704afb72d Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 18 Mar 2024 14:26:02 +0530
Subject: [PATCH 108/236] Update README.md
---
section_10/README.md | 55 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 55 insertions(+)
diff --git a/section_10/README.md b/section_10/README.md
index 8b13789..7c311a1 100644
--- a/section_10/README.md
+++ b/section_10/README.md
@@ -1 +1,56 @@
+# Inheritance in Java
+Inheritance is a fundamental concept in object-oriented programming (OOP) languages like Java. It allows a class (subclass/derived class) to inherit properties and behaviors from another class (superclass/base class). This promotes code reusability and establishes a hierarchical relationship between classes.
+```java
+# Inheritance in Java
+
+Inheritance is a fundamental concept in object-oriented programming (OOP) languages like Java. It allows a class (subclass/derived class) to inherit properties and behaviors from another class (superclass/base class). This promotes code reusability and establishes a hierarchical relationship between classes.
+
+## How Inheritance Works
+
+In Java, inheritance is achieved using the `extends` keyword. Here's a simple example:
+
+```java
+// Superclass
+class Vehicle {
+ void move() {
+ System.out.println("Vehicle is moving...");
+ }
+}
+
+// Subclass inheriting from Vehicle
+class Car extends Vehicle {
+ void accelerate() {
+ System.out.println("Car is accelerating...");
+ }
+}
+
+// Main class
+public class Main {
+ public static void main(String[] args) {
+ Car myCar = new Car();
+ myCar.move(); // Output: Vehicle is moving...
+ myCar.accelerate(); // Output: Car is accelerating...
+ }
+}
+```
+### In this example:
+- `Vehicle` is the superclass, and Car is the subclass.
+- `Car` inherits the `move()` method from Vehicle.
+-` Car` also has its own method `accelerate()`.
+## Types of Inheritance
+**1.Single Inheritance :** A subclass extends only one superclass.
+**2.Multilevel Inheritance :** A subclass extends another subclass.
+**3.Hierarchical Inheritance :** Multiple subclasses extend the same superclass.
+**4.Multiple Inheritance (achieved through interfaces):** A class implements multiple interfaces.
+## Rules and Considerations
+When working with inheritance in Java, keep these points in mind:
+- Java does not support multiple inheritance for classes (i.e., a class cannot extend more than one class). However, it supports multiple inheritance through interfaces.
+- The access level of the inherited members depends on their access modifiers. Inherited members with private access are not visible in the subclass.
+- Constructors are not inherited but can be invoked using the super() keyword.
+- Overriding allows a subclass to provide a specific implementation for a method defined in the superclass.
+## When to Use Inheritance
+- You want to model an "is-a" relationship between classes (e.g., a Car is-a Vehicle).
+- You need to reuse code from existing classes.
+- You want to establish a hierarchical structure to organize classes.
+
From 5fa4e79b9cf3e76f0a1e21a5fce240fa24e190da Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 18 Mar 2024 18:08:09 +0530
Subject: [PATCH 109/236] Update README.md
---
section_10/README.md | 192 +++++++++++++++++++++++++++++++++++++++++--
1 file changed, 187 insertions(+), 5 deletions(-)
diff --git a/section_10/README.md b/section_10/README.md
index 7c311a1..4b7ec48 100644
--- a/section_10/README.md
+++ b/section_10/README.md
@@ -33,24 +33,206 @@ public class Main {
}
}
```
-### In this example:
-- `Vehicle` is the superclass, and Car is the subclass.
+#### In this example:
+- `Vehicle` is the superclass, and `Car` is the subclass.
- `Car` inherits the `move()` method from Vehicle.
-` Car` also has its own method `accelerate()`.
-## Types of Inheritance
+### Types of Inheritance
**1.Single Inheritance :** A subclass extends only one superclass.
**2.Multilevel Inheritance :** A subclass extends another subclass.
**3.Hierarchical Inheritance :** Multiple subclasses extend the same superclass.
**4.Multiple Inheritance (achieved through interfaces):** A class implements multiple interfaces.
-## Rules and Considerations
+### Rules and Considerations
When working with inheritance in Java, keep these points in mind:
- Java does not support multiple inheritance for classes (i.e., a class cannot extend more than one class). However, it supports multiple inheritance through interfaces.
- The access level of the inherited members depends on their access modifiers. Inherited members with private access are not visible in the subclass.
- Constructors are not inherited but can be invoked using the super() keyword.
- Overriding allows a subclass to provide a specific implementation for a method defined in the superclass.
-## When to Use Inheritance
+### When to Use Inheritance
- You want to model an "is-a" relationship between classes (e.g., a Car is-a Vehicle).
- You need to reuse code from existing classes.
- You want to establish a hierarchical structure to organize classes.
+### Conclusion
+Inheritance is a powerful feature in Java that allows classes to inherit properties and behaviors from other classes. By understanding and leveraging inheritance, you can write more efficient and maintainable code.
+## Object Class in Java
+## Methods
+### public boolean equals(Object obj)
+The equals method is used to compare the current object with another object for equality. By default, this method compares the memory addresses of the objects. However, it is often overridden by subclasses to provide custom equality comparison.
+
+### public int hashCode()
+The hashCode method returns a hash code value for the object. This method is used in conjunction with hash-based data structures such as HashMap and HashSet.
+
+### public String toString()
+The toString method returns a string representation of the object. By default, this method returns a string consisting of the class name followed by the "@" symbol and the object's hash code.
+
+### protected Object clone() throws CloneNotSupportedException
+The clone method creates and returns a copy of the object. It is declared protected and must be overridden in subclasses to support cloning.
+
+### public final Class> getClass()
+The getClass method returns the runtime class of the object. It returns an instance of the Class class that provides information about the class.
+
+### public final void notify()
+The notify method wakes up a single thread that is waiting on the object's monitor.
+
+### public final void notifyAll()
+The notifyAll method wakes up all threads that are waiting on the object's monitor.
+
+### public final void wait() throws InterruptedException
+The wait method causes the current thread to wait until another thread calls the notify() or notifyAll() method on the object.
+
+### public final void wait(long timeout) throws InterruptedException
+The wait method causes the current thread to wait until another thread calls the notify() or notifyAll() method on the object, or until the specified timeout expires.
+
+### public final void wait(long timeout, int nanos) throws InterruptedException
+Similar to the previous wait method, but allows specifying a timeout in nanoseconds.
+#### Example
+```java
+public class ObjectExample {
+ public static void main(String[] args) {
+ Object obj1 = new Object();
+ Object obj2 = new Object();
+
+ // Using equals method
+ if (obj1.equals(obj2)) {
+ System.out.println("Objects are equal");
+ } else {
+ System.out.println("Objects are not equal");
+ }
+
+ // Using hashCode method
+ System.out.println("Hash code of obj1: " + obj1.hashCode());
+ System.out.println("Hash code of obj2: " + obj2.hashCode());
+
+ // Using toString method
+ System.out.println("String representation of obj1: " + obj1.toString());
+
+ // Using getClass method
+ System.out.println("Class of obj1: " + obj1.getClass().getName());
+ }
+}
+```
+### Notes
+- The `Object` class provides default implementations for many of its methods, which can be overridden by subclasses to customize behavior.
+- When overriding the `equals` method, it is recommended to also override the `hashCode` method to maintain the general contract between the two methods.
+- The `wait`, `notify`, and `notifyAll` methods are used for inter-thread communication and synchronization.
+## is-a Realationship
+In Java, the "is-a" relationship is a fundamental principle of object-oriented programming (OOP) that is implemented through inheritance. It signifies a relationship between classes where one class is considered to be a specialized version of another class.
+#### Example
+```java
+// Superclass
+class Animal {
+ void makeSound() {
+ System.out.println("Animal makes a sound.");
+ }
+}
+
+// Subclass
+class Dog extends Animal { // Dog is a Animal
+ void wagTail() {
+ System.out.println("Dog wags its tail.");
+ }
+}
+
+// Subclass
+class Cat extends Animal { // Cat is a Animal
+ void purr() {
+ System.out.println("Cat purrs.");
+ }
+}
+```
+## "has-a" Relationship
+In the "has-a" relationship, one class (usually referred to as the container or composite class) contains an instance of another class (referred to as the contained or component class) as one of its members. This implies that the container class "has" an object of the component class.
+#### Example
+```java
+public class Car {
+ private Engine engine;
+
+ public Car(Engine engine) {
+ this.engine = engine;
+ }
+
+ // Other methods and attributes of the Car class...
+}
+
+public class Engine {
+ // Properties and methods of the Engine class...
+}
+```
+### In this example:
+The `Car` class has an instance of the Engine class as one of its attributes.
+The `Engine` class represents the component that the Car class possesses.
+### Benefits of "has-a" Relationship:
+**1.Modularity :**
+- Allows for modular design by encapsulating related functionality within separate classes.
+#### 2.Code Reusability :
+- Promotes code reusability as the same component class can be used across multiple container classes.
+#### 3.Flexibility :
+- Provides flexibility in designing complex systems by composing smaller, reusable components.
+### How to Use:
+When designing classes in Java, consider whether one class needs to contain an instance of another class to represent a "has-a" relationship. If so, define the appropriate attributes and methods to interact with the contained class.
+
+### Conclusion:
+Understanding the "has-a" relationship is crucial for designing modular and maintainable Java applications. By utilizing this relationship effectively, you can create flexible and reusable code that accurately models real-world scenarios.
+## Up-casting
+Up-casting refers to the process of converting an object of a subclass to a reference of its superclass. It is implicit and does not require any explicit casting operator. Up-casting is always safe because a subclass object inherently possesses all the attributes and behaviors of its superclass.
+#### Example:
+```java
+class Animal {
+ public void sound() {
+ System.out.println("Animal makes a sound"); //
+ }
+}
+
+class Dog extends Animal {
+ @Override
+ public void sound() {
+ System.out.println("Dog barks");
+ }
+}
+
+public class Main {
+ public static void main(String[] args) {
+ Animal animal = new Dog(); // Up-casting
+ animal.sound(); // Output: Dog barks
+ }
+}
+```
+### Down-casting
+Down-casting is the opposite of up-casting. It refers to the process of converting a reference of a superclass type to its subclass type. Down-casting is explicit and requires the use of the casting operator. It can potentially lead to a `ClassCastException` at runtime if the object being casted is not actually an instance of the target subclass.
+#### Example:
+```java
+class Animal {
+ public void sound() {
+ System.out.println("Animal makes a sound");
+ }
+}
+
+class Dog extends Animal {
+ @Override
+ public void sound() {
+ System.out.println("Dog barks");
+ }
+}
+
+public class Main {
+ public static void main(String[] args) {
+ Animal animal = new Dog(); // Up-casting
+ animal.sound(); // Output: Dog barks
+ }
+}
+public class Main {
+ public static void main(String[] args) {
+ Animal animal = new Dog(); // Up-casting
+ Dog dog = (Dog) animal; // Down-casting
+ dog.sound(); // Output: Dog barks
+ }
+}
+In the above example, we first up-cast a Dog object to an Animal reference. Then, we down-cast the Animal reference back to a Dog reference. Since the original object was indeed a Dog, down-casting is safe in this scenario.
+### Conclusion
+Up-casting and down-casting are important concepts in Java that allow for flexibility and polymorphism in object-oriented programming. While up-casting is implicit and safe, down-casting requires explicit type casting and should be used carefully to avoid runtime errors.
+
+
+
+
From e6dc03a95f17563b89ba8c66e65e8b3fef87325b Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 18 Mar 2024 19:40:18 +0530
Subject: [PATCH 110/236] Update README.md
---
section_10/README.md | 35 +++++++++++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
diff --git a/section_10/README.md b/section_10/README.md
index 4b7ec48..8e54e7f 100644
--- a/section_10/README.md
+++ b/section_10/README.md
@@ -227,9 +227,44 @@ public class Main {
dog.sound(); // Output: Dog barks
}
}
+```
In the above example, we first up-cast a Dog object to an Animal reference. Then, we down-cast the Animal reference back to a Dog reference. Since the original object was indeed a Dog, down-casting is safe in this scenario.
### Conclusion
Up-casting and down-casting are important concepts in Java that allow for flexibility and polymorphism in object-oriented programming. While up-casting is implicit and safe, down-casting requires explicit type casting and should be used carefully to avoid runtime errors.
+### instanceof Operator
+The `instanceof` operator in Java is used to test whether an object is an instance of a particular class or interface. It returns either `true` or `false` based on whether the object is an instance of the specified type.
+#### Example
+```java
+public class Main {
+ public static void main(String[] args) {
+ String str = "Hello";
+
+ // Using instanceof to check if str is an instance of String class
+ boolean isString = str instanceof String;
+ System.out.println("Is str an instance of String? " + isString); // Output: true
+
+ // Using instanceof to check if str is an instance of Object class
+ boolean isObject = str instanceof Object;
+ System.out.println("Is str an instance of Object? " + isObject); // Output: true // Object class is super class of all the classes
+
+
+ // Using instanceof to check if str is an instance of Integer class
+ boolean isInteger = str instanceof Integer;
+ System.out.println("Is str an instance of Integer? " + isInteger); // Output: false
+ }
+}
+```
+In this example:
+- We create a String object str.
+- We use the instanceof operator to check if str is an instance of the `String` class, which returns `true`.
+- Similarly, we check if `str` is an instance of the `Object` class, which also returns `true`.
+- Finally, we check if str is an instance of the `Integer` class, which returns `false`.
+### Key Points
+- The `instanceof` operator is used for type checking at runtime.
+- It returns true if the object is an instance of the specified type or any of its subtypes, otherwise false.
+- It's commonly used when working with polymorphic code to determine the actual type of an object before performing certain operations.
+
+
From 98933a79aa7f098275724e7ae4630c8c2f2d2ad8 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 18 Mar 2024 20:41:34 +0530
Subject: [PATCH 111/236] Update README.md
---
section_10/README.md | 47 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 47 insertions(+)
diff --git a/section_10/README.md b/section_10/README.md
index 8e54e7f..b73f170 100644
--- a/section_10/README.md
+++ b/section_10/README.md
@@ -263,6 +263,53 @@ In this example:
- The `instanceof` operator is used for type checking at runtime.
- It returns true if the object is an instance of the specified type or any of its subtypes, otherwise false.
- It's commonly used when working with polymorphic code to determine the actual type of an object before performing certain operations.
+## Static Binding and Dynamic Binding
+In Java, binding refers to the process of associating a method call with the method body. There are two types of binding in Java: static binding and dynamic binding.
+## Static Binding
+Static binding, also known as early binding, occurs during compile time. In static binding, the method call is resolved by the compiler based on the reference type. This means that the compiler determines which method to call based on the reference type of the object at compile time.
+### Dynamic Binding
+Dynamic binding, also known as late binding, occurs during runtime. In dynamic binding, the method call is resolved by the JVM (Java Virtual Machine) based on the actual object type. This means that the JVM determines which method to call based on the actual object type at runtime.
+#### Example:
+```java
+class Animal {
+ void sound() {
+ System.out.println("Animal makes a sound");
+ }
+}
+
+class Dog extends Animal {
+ void sound() {
+ System.out.println("Dog barks");
+ }
+}
+
+class Cat extends Animal {
+ void sound() {
+ System.out.println("Cat meows");
+ }
+}
+
+public class Main {
+ public static void main(String[] args) {
+ Animal animal1 = new Animal();
+ Animal animal2 = new Dog();
+ Animal animal3 = new Cat();
+
+ animal1.sound(); // Output: Animal makes a sound (static binding)
+ animal2.sound(); // Output: Dog barks (dynamic binding)
+ animal3.sound(); // Output: Cat meows (dynamic binding)
+ }
+}
+
+```
+In this example:
+
+- animal1 is of type Animal, and the sound() method call is resolved at compile time because the reference type is known.
+- animal2 is of type Animal, but it refers to a Dog object. The method call is resolved at runtime, and the sound() method of Dog class is invoked (dynamic binding).
+- animal3 is also of type Animal, but it refers to a Cat object. Again, the method call is resolved at runtime, and the sound() method of Cat class is invoked (dynamic binding).
+- This demonstrates the difference between static binding, where the method is determined at compile time based on the reference type, and dynamic binding, where the method is determined at runtime based on the actual object type.
+
+
From fe6971d820f587f35ddf35406fd662e6662b003d Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 19 Mar 2024 16:08:51 +0530
Subject: [PATCH 112/236] Update README.md
---
section_10/README.md | 81 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 81 insertions(+)
diff --git a/section_10/README.md b/section_10/README.md
index b73f170..829e9d3 100644
--- a/section_10/README.md
+++ b/section_10/README.md
@@ -308,6 +308,87 @@ In this example:
- animal2 is of type Animal, but it refers to a Dog object. The method call is resolved at runtime, and the sound() method of Dog class is invoked (dynamic binding).
- animal3 is also of type Animal, but it refers to a Cat object. Again, the method call is resolved at runtime, and the sound() method of Cat class is invoked (dynamic binding).
- This demonstrates the difference between static binding, where the method is determined at compile time based on the reference type, and dynamic binding, where the method is determined at runtime based on the actual object type.
+## Polymorphism in Java
+Polymorphism is one of the fundamental concepts in object-oriented programming (OOP) languages like Java. It allows objects of different classes to be treated as objects of a common superclass. This enables a single interface to be used for entities of different types.
+### Types of Polymorphism
+### 1. Compile-time Polymorphism (Method Overloading)
+Method overloading allows a class to have multiple methods with the same name but with different parameters. The appropriate method is called based on the number and type of parameters during compile-time.
+#### Example:
+```java
+public class Calculator {
+ public int add(int a, int b) {
+ return a + b;
+ }
+
+ public double add(double a, double b) {
+ return a + b;
+ }
+}
+```
+### Runtime Polymorphism (Method Overriding)
+Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. It allows the subclass to provide its own implementation of the method.
+#### Example:
+```java
+class Animal {
+ public void makeSound() {
+ System.out.println("Some generic sound");
+ }
+}
+
+class Dog extends Animal {
+ @Override
+ public void makeSound() {
+ System.out.println("Woof");
+ }
+}
+```
+### Benefits of Polymorphism
+**Code Reusability :** Polymorphism allows methods to be written that can work with objects of any subclass of a common superclass, promoting code reuse.
+**Flexibility and Extensibility :** New classes can be added without modifying existing code, as long as they inherit from the common superclass.
+#### Conclusion
+Polymorphism is a powerful feature of Java that enhances code flexibility, reusability, and extensibility. By treating objects of different classes uniformly through a common interface, it simplifies code maintenance and promotes good design practices.
+## Using the super Keyword
+In Java, the `super` keyword is used to refer to the superclass (parent class) of the current object. One common use of `super` is to invoke superclass methods or constructors from a subclass.
+### Invoking Superclass Methods
+When a subclass overrides a method defined in its superclass, you can use `super` to invoke the overridden method of the superclass. This is particularly useful when you want to extend the behavior of the superclass method rather than replace it entirely.
+### Syntax
+```java
+super.methodName();
+```
+#### Example
+```java
+class Vehicle {
+ void start() {
+ System.out.println("Vehicle started");
+ }
+}
+
+class Car extends Vehicle {
+ @Override
+ void start() {
+ super.start(); // invoking superclass method
+ System.out.println("Car started");
+ }
+}
+
+public class Main {
+ public static void main(String[] args) {
+ Car car = new Car();
+ car.start();
+ }
+}
+```
+#### Output:
+```java
+Vehicle started
+Car started
+```
+In this example, the `start()` method of the Car class invokes the `start()` method of the superclass Vehicle using `super.start()`, and then it adds its own behavior.
+#### Conclusion
+The `super` keyword in Java provides a way to access superclass members (methods, fields, and constructors) from within a subclass. It's particularly handy when you want to customize or extend the behavior of superclass methods in your subclass implementations.
+
+
+
From e431043b2de0edef708042c6bf5611953b2ad6ad Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 19 Mar 2024 16:11:57 +0530
Subject: [PATCH 113/236] Update README.md
---
section_10/README.md | 18 +++++++++---------
1 file changed, 9 insertions(+), 9 deletions(-)
diff --git a/section_10/README.md b/section_10/README.md
index 829e9d3..4a7e77e 100644
--- a/section_10/README.md
+++ b/section_10/README.md
@@ -117,7 +117,7 @@ public class ObjectExample {
- The `wait`, `notify`, and `notifyAll` methods are used for inter-thread communication and synchronization.
## is-a Realationship
In Java, the "is-a" relationship is a fundamental principle of object-oriented programming (OOP) that is implemented through inheritance. It signifies a relationship between classes where one class is considered to be a specialized version of another class.
-#### Example
+#### Example π‘
```java
// Superclass
class Animal {
@@ -142,7 +142,7 @@ class Cat extends Animal { // Cat is a Animal
```
## "has-a" Relationship
In the "has-a" relationship, one class (usually referred to as the container or composite class) contains an instance of another class (referred to as the contained or component class) as one of its members. This implies that the container class "has" an object of the component class.
-#### Example
+#### Example π‘
```java
public class Car {
private Engine engine;
@@ -175,7 +175,7 @@ When designing classes in Java, consider whether one class needs to contain an i
Understanding the "has-a" relationship is crucial for designing modular and maintainable Java applications. By utilizing this relationship effectively, you can create flexible and reusable code that accurately models real-world scenarios.
## Up-casting
Up-casting refers to the process of converting an object of a subclass to a reference of its superclass. It is implicit and does not require any explicit casting operator. Up-casting is always safe because a subclass object inherently possesses all the attributes and behaviors of its superclass.
-#### Example:
+#### Example π‘
```java
class Animal {
public void sound() {
@@ -199,7 +199,7 @@ public class Main {
```
### Down-casting
Down-casting is the opposite of up-casting. It refers to the process of converting a reference of a superclass type to its subclass type. Down-casting is explicit and requires the use of the casting operator. It can potentially lead to a `ClassCastException` at runtime if the object being casted is not actually an instance of the target subclass.
-#### Example:
+#### Example π‘
```java
class Animal {
public void sound() {
@@ -233,7 +233,7 @@ In the above example, we first up-cast a Dog object to an Animal reference. Then
Up-casting and down-casting are important concepts in Java that allow for flexibility and polymorphism in object-oriented programming. While up-casting is implicit and safe, down-casting requires explicit type casting and should be used carefully to avoid runtime errors.
### instanceof Operator
The `instanceof` operator in Java is used to test whether an object is an instance of a particular class or interface. It returns either `true` or `false` based on whether the object is an instance of the specified type.
-#### Example
+#### Example π‘
```java
public class Main {
public static void main(String[] args) {
@@ -269,7 +269,7 @@ In Java, binding refers to the process of associating a method call with the met
Static binding, also known as early binding, occurs during compile time. In static binding, the method call is resolved by the compiler based on the reference type. This means that the compiler determines which method to call based on the reference type of the object at compile time.
### Dynamic Binding
Dynamic binding, also known as late binding, occurs during runtime. In dynamic binding, the method call is resolved by the JVM (Java Virtual Machine) based on the actual object type. This means that the JVM determines which method to call based on the actual object type at runtime.
-#### Example:
+#### Example π‘
```java
class Animal {
void sound() {
@@ -313,7 +313,7 @@ Polymorphism is one of the fundamental concepts in object-oriented programming (
### Types of Polymorphism
### 1. Compile-time Polymorphism (Method Overloading)
Method overloading allows a class to have multiple methods with the same name but with different parameters. The appropriate method is called based on the number and type of parameters during compile-time.
-#### Example:
+#### Example π‘
```java
public class Calculator {
public int add(int a, int b) {
@@ -327,7 +327,7 @@ public class Calculator {
```
### Runtime Polymorphism (Method Overriding)
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. It allows the subclass to provide its own implementation of the method.
-#### Example:
+#### Example π‘
```java
class Animal {
public void makeSound() {
@@ -355,7 +355,7 @@ When a subclass overrides a method defined in its superclass, you can use `super
```java
super.methodName();
```
-#### Example
+#### Example π‘
```java
class Vehicle {
void start() {
From 83cdd58869d325fe98750e8a4eadb3631b32fcc6 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 19 Mar 2024 16:13:13 +0530
Subject: [PATCH 114/236] Update README.md
---
section_10/README.md | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/section_10/README.md b/section_10/README.md
index 4a7e77e..10f44f3 100644
--- a/section_10/README.md
+++ b/section_10/README.md
@@ -171,7 +171,7 @@ The `Engine` class represents the component that the Car class possesses.
### How to Use:
When designing classes in Java, consider whether one class needs to contain an instance of another class to represent a "has-a" relationship. If so, define the appropriate attributes and methods to interact with the contained class.
-### Conclusion:
+### Conclusion π
Understanding the "has-a" relationship is crucial for designing modular and maintainable Java applications. By utilizing this relationship effectively, you can create flexible and reusable code that accurately models real-world scenarios.
## Up-casting
Up-casting refers to the process of converting an object of a subclass to a reference of its superclass. It is implicit and does not require any explicit casting operator. Up-casting is always safe because a subclass object inherently possesses all the attributes and behaviors of its superclass.
@@ -229,7 +229,7 @@ public class Main {
}
```
In the above example, we first up-cast a Dog object to an Animal reference. Then, we down-cast the Animal reference back to a Dog reference. Since the original object was indeed a Dog, down-casting is safe in this scenario.
-### Conclusion
+### Conclusion π
Up-casting and down-casting are important concepts in Java that allow for flexibility and polymorphism in object-oriented programming. While up-casting is implicit and safe, down-casting requires explicit type casting and should be used carefully to avoid runtime errors.
### instanceof Operator
The `instanceof` operator in Java is used to test whether an object is an instance of a particular class or interface. It returns either `true` or `false` based on whether the object is an instance of the specified type.
@@ -345,7 +345,7 @@ class Dog extends Animal {
### Benefits of Polymorphism
**Code Reusability :** Polymorphism allows methods to be written that can work with objects of any subclass of a common superclass, promoting code reuse.
**Flexibility and Extensibility :** New classes can be added without modifying existing code, as long as they inherit from the common superclass.
-#### Conclusion
+#### Conclusion π
Polymorphism is a powerful feature of Java that enhances code flexibility, reusability, and extensibility. By treating objects of different classes uniformly through a common interface, it simplifies code maintenance and promotes good design practices.
## Using the super Keyword
In Java, the `super` keyword is used to refer to the superclass (parent class) of the current object. One common use of `super` is to invoke superclass methods or constructors from a subclass.
@@ -384,7 +384,7 @@ Vehicle started
Car started
```
In this example, the `start()` method of the Car class invokes the `start()` method of the superclass Vehicle using `super.start()`, and then it adds its own behavior.
-#### Conclusion
+#### Conclusion π
The `super` keyword in Java provides a way to access superclass members (methods, fields, and constructors) from within a subclass. It's particularly handy when you want to customize or extend the behavior of superclass methods in your subclass implementations.
From ad98e1bb746e4ac4b9554b2accebfcb39fa45217 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 19 Mar 2024 16:15:41 +0530
Subject: [PATCH 115/236] Update README.md
---
section_10/README.md | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/section_10/README.md b/section_10/README.md
index 10f44f3..057ed41 100644
--- a/section_10/README.md
+++ b/section_10/README.md
@@ -52,7 +52,7 @@ When working with inheritance in Java, keep these points in mind:
- You want to model an "is-a" relationship between classes (e.g., a Car is-a Vehicle).
- You need to reuse code from existing classes.
- You want to establish a hierarchical structure to organize classes.
-### Conclusion
+### Conclusion π
Inheritance is a powerful feature in Java that allows classes to inherit properties and behaviors from other classes. By understanding and leveraging inheritance, you can write more efficient and maintainable code.
## Object Class in Java
## Methods
@@ -85,7 +85,7 @@ The wait method causes the current thread to wait until another thread calls the
### public final void wait(long timeout, int nanos) throws InterruptedException
Similar to the previous wait method, but allows specifying a timeout in nanoseconds.
-#### Example
+#### Example π‘
```java
public class ObjectExample {
public static void main(String[] args) {
@@ -111,7 +111,7 @@ public class ObjectExample {
}
}
```
-### Notes
+### Notes π
- The `Object` class provides default implementations for many of its methods, which can be overridden by subclasses to customize behavior.
- When overriding the `equals` method, it is recommended to also override the `hashCode` method to maintain the general contract between the two methods.
- The `wait`, `notify`, and `notifyAll` methods are used for inter-thread communication and synchronization.
@@ -259,7 +259,7 @@ In this example:
- We use the instanceof operator to check if str is an instance of the `String` class, which returns `true`.
- Similarly, we check if `str` is an instance of the `Object` class, which also returns `true`.
- Finally, we check if str is an instance of the `Integer` class, which returns `false`.
-### Key Points
+### Key Points π
- The `instanceof` operator is used for type checking at runtime.
- It returns true if the object is an instance of the specified type or any of its subtypes, otherwise false.
- It's commonly used when working with polymorphic code to determine the actual type of an object before performing certain operations.
From 5d6c98945b17a536e166075bbb13ee3f315b7950 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 19 Mar 2024 17:33:27 +0530
Subject: [PATCH 116/236] Update README.md
---
section_10/README.md | 65 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 65 insertions(+)
diff --git a/section_10/README.md b/section_10/README.md
index 057ed41..55e2a04 100644
--- a/section_10/README.md
+++ b/section_10/README.md
@@ -386,6 +386,71 @@ Car started
In this example, the `start()` method of the Car class invokes the `start()` method of the superclass Vehicle using `super.start()`, and then it adds its own behavior.
#### Conclusion π
The `super` keyword in Java provides a way to access superclass members (methods, fields, and constructors) from within a subclass. It's particularly handy when you want to customize or extend the behavior of superclass methods in your subclass implementations.
+## Method Hiding in Java
+Method hiding is a concept in Java where a subclass can define a static method with the same signature as a static method in its superclass. This hides the superclass method from the subclass, effectively replacing it with the subclass method. This behavior is different from method overriding, where the subclass provides a specific implementation of a non-static method from its superclass.
+## Usage
+To understand method hiding, consider the following example:
+```java
+class Superclass {
+ static void myStaticMethod() {
+ System.out.println("Static method in Superclass");
+ }
+}
+
+class Subclass extends Superclass {
+ static void myStaticMethod() {
+ System.out.println("Static method in Subclass");
+ }
+}
+
+public class Main {
+ public static void main(String[] args) {
+ Superclass.myStaticMethod(); // Output: Static method in Superclass
+ Subclass.myStaticMethod(); // Output: Static method in Subclass
+ }
+}
+```
+In this example, both Superclass and Subclass have a static method named `myStaticMethod()`. When called from the Main class, the output demonstrates that the method from the subclass is invoked, even though the reference is of the superclass type.
+### Key Points
+- Method hiding occurs when a subclass defines a static method with the same signature as a static method in its superclass.
+- Method hiding is resolved at compile time based on the reference type, not the object type.
+- It is recommended to use method hiding judiciously, as it can lead to confusion and make the code harder to understand.
+- Unlike method overriding, method hiding does not involve polymorphism because it is based on the reference type, not the object type.
+#### Conclusion
+Method hiding in Java provides a mechanism for subclasses to hide static methods of their superclass and provide their own implementations. While it can be useful in certain situations, it should be used carefully to avoid confusion and maintain code clarity.
+## Feild Hiding
+To achieve field hiding in Java, you can use inheritance along with declaring fields with the same name in the superclass and subclass. Here's a simple example to demonstrate field hiding :
+```java
+// Superclass
+class Parent {
+ int x = 10; // Field in the superclass
+
+ void display() {
+ System.out.println("Value of x in Parent: " + x);
+ }
+}
+
+// Subclass
+class Child extends Parent {
+ int x = 20; // Field in the subclass, hiding the field in the superclass
+
+ void display() {
+ System.out.println("Value of x in Child: " + x);
+ System.out.println("Value of x in Parent: " + super.x); // Accessing superclass field
+ }
+}
+
+public class Main {
+ public static void main(String[] args) {
+ Child obj = new Child();
+ obj.display(); // This will print the value of x in Child and Parent
+ }
+}
+```
+In this example, the Child class extends the Parent class, and both classes have a field named `x`. However, the field in the subclass hides the field in the superclass. When you access x inside the Child class, it refers to the field in the subclass. If you want to access the field in the superclass, you can use the `super` keyword.
+
+
+
From 904b3dff10a76f82842cda7a128adf11e555641f Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 19 Mar 2024 19:57:07 +0530
Subject: [PATCH 117/236] Update README.md
---
section_10/README.md | 242 ++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 241 insertions(+), 1 deletion(-)
diff --git a/section_10/README.md b/section_10/README.md
index 55e2a04..71db3ca 100644
--- a/section_10/README.md
+++ b/section_10/README.md
@@ -416,7 +416,7 @@ In this example, both Superclass and Subclass have a static method named `myStat
- Method hiding is resolved at compile time based on the reference type, not the object type.
- It is recommended to use method hiding judiciously, as it can lead to confusion and make the code harder to understand.
- Unlike method overriding, method hiding does not involve polymorphism because it is based on the reference type, not the object type.
-#### Conclusion
+#### Conclusion π
Method hiding in Java provides a mechanism for subclasses to hide static methods of their superclass and provide their own implementations. While it can be useful in certain situations, it should be used carefully to avoid confusion and maintain code clarity.
## Feild Hiding
To achieve field hiding in Java, you can use inheritance along with declaring fields with the same name in the superclass and subclass. Here's a simple example to demonstrate field hiding :
@@ -448,6 +448,246 @@ public class Main {
}
```
In this example, the Child class extends the Parent class, and both classes have a field named `x`. However, the field in the subclass hides the field in the superclass. When you access x inside the Child class, it refers to the field in the subclass. If you want to access the field in the superclass, you can use the `super` keyword.
+## Types of Inheritance
+### Single Inheritance
+Single inheritance refers to the inheritance of properties and behaviors from a single parent class. In Java, a class can extend only one other class.
+```java
+class Parent {
+ // Parent class members
+}
+
+class Child extends Parent {
+ // Child class members
+}
+```
+### Multilevel Inheritance
+Multilevel inheritance involves a chain of inheritance where a subclass becomes the superclass for another subclass. This creates a hierarchical relationship between classes.
+
+```java
+class Grandparent {
+ // Grandparent class members
+}
+
+class Parent extends Grandparent {
+ // Parent class members
+}
+
+class Child extends Parent {
+ // Child class members
+}
+```
+### Hierarchical Inheritance
+Hierarchical inheritance involves multiple subclasses inheriting from a single superclass. Each subclass inherits the properties and behaviors of the superclass.
+
+```java
+class Animal {
+ // Animal class members
+}
+
+class Dog extends Animal {
+ // Dog class members
+}
+
+class Cat extends Animal {
+ // Cat class members
+}
+```
+### Multiple Inheritance (with Interfaces)
+Java does not support multiple inheritance of classes due to the "diamond problem" (ambiguous references). However, it supports multiple inheritance of interfaces. A class can implement multiple interfaces, inheriting abstract methods from each.
+
+```java
+interface Interface1 {
+ // Interface1 methods
+}
+
+interface Interface2 {
+ // Interface2 methods
+}
+
+class MyClass implements Interface1, Interface2 {
+ // MyClass members
+}
+```
+Using Inheritance
+To use inheritance in Java, you simply need to extend a class using the extends keyword or implement interfaces using the implements keyword.
+
+```java
+class Vehicle {
+ void drive() {
+ System.out.println("Driving...");
+ }
+}
+
+class Car extends Vehicle {
+ void park() {
+ System.out.println("Parking...");
+ }
+}
+
+public class Main {
+ public static void main(String[] args) {
+ Car myCar = new Car();
+ myCar.drive(); // Output: Driving...
+ myCar.park(); // Output: Parking...
+ }
+}
+```
+### Conclusion π
+Inheritance is a fundamental concept in Java programming, allowing classes to inherit properties and behaviors from other classes. Understanding the types of inheritance and how to use them is essential for building maintainable and efficient Java applications.
+## Abstract Classes and Methods
+In Java, abstract classes and methods are fundamental concepts in object-oriented programming. They allow you to define a blueprint for classes and methods that must be implemented by subclasses.
+### Abstract Classes
+An abstract class in Java is a class that cannot be instantiated on its own and may contain one or more abstract methods. Abstract classes are typically used to define a common interface for subclasses. They can also include concrete methods.
+#### Example π‘
+To create an abstract class in Java, use the `abstract` keyword in the class declaration. Abstract classes can have abstract methods (methods without a body) and concrete methods (methods with a body).
+```java
+public abstract class Shape {
+ // Abstract method
+ public abstract double area();
+
+ // Concrete method
+ public void display() {
+ System.out.println("Displaying shape...");
+ }
+}
+```
+### Abstract Methods
+An abstract method in Java is a method declared without implementation. It must be overridden by concrete subclasses. Abstract methods serve as placeholders for functionality that must be implemented by subclasses.
+### Usage
+To declare an abstract method, use the abstract keyword in the method declaration. Abstract methods must be implemented by non-abstract subclasses.
+```java
+
+public abstract double area();
+```
+#### Example π‘
+```java
+public abstract class Shape {
+ // Abstract method
+ public abstract double area();
+
+ // Concrete method
+ public void display() {
+ System.out.println("Displaying shape...");
+ }
+}
+
+public class Rectangle extends Shape {
+ private double length;
+ private double width;
+
+ public Rectangle(double length, double width) {
+ this.length = length;
+ this.width = width;
+ }
+
+ // Implementing abstract method
+ @Override
+ public double area() {
+ return length * width;
+ }
+}
+
+public class Main {
+ public static void main(String[] args) {
+ Rectangle rectangle = new Rectangle(5, 3);
+ System.out.println("Area of rectangle: " + rectangle.area());
+ rectangle.display();
+ }
+}
+
+```
+#### Conclusion π
+Abstract classes and methods provide a powerful mechanism for defining common interfaces and behaviors in Java. They promote code reusability and help in achieving abstraction and encapsulation.
+## final Keyword
+In Java, the `final` keyword is used to restrict the user. It can be applied to variables, methods, and classes, each with its own implications. Here's a breakdown of its usage
+### Final Variables
+When a variable is declared as `final`, its value cannot be changed once initialized.
+```java
+final int x = 10;
+x = 20; // This will result in a compilation error
+```
+### Final Methods
+When a method is declared as final in a class, it means that the method cannot be overridden by subclasses.
+```java
+class Parent {
+ final void display() {
+ System.out.println("Parent class method");
+ }
+}
+
+
+class Child extends Parent {
+ void display() { // This will result in a compilation error
+ System.out.println("Child class method");
+ }
+}
+```
+### Final Classes
+When a class is declared as `final`, it means that it cannot be subclassed.
+```java
+final class FinalClass {
+ // Class implementation
+}
+
+// This will result in a compilation error
+class SubClass extends FinalClass {
+ // Class implementation
+}
+```
+### Benefits of Using final
+- **Security :** It prevents modifications to sensitive data or methods.
+- **Performance :** The JVM can optimize final variables, methods, and classes more aggressively.
+- **Design Clarity :** It communicates intent to other developers, making the code easier to understand and maintain.
+#### Conclusion π
+The `final` keyword in Java provides a way to create constants, enforce immutability, and define methods or classes that cannot be overridden or subclassed. Proper use of final can enhance code clarity, security, and performance.
+## Sealed Classes and Interfaces
+Sealed classes and interfaces were introduced in Java 15 as a preview feature and became a permanent feature starting from Java 17. They provide a mechanism to restrict which classes can extend or implement a particular class or interface. This enhances encapsulation and improves maintainability by controlling the inheritance hierarchy.
+### Key Concepts
+### Sealed Classes
+A sealed class is a class that restricts which other classes can extend it. It explicitly specifies the permitted subclasses. To declare a sealed class, you use the `sealed` modifier followed by the permitted subclasses. The permitted subclasses can be either `final` classes or non-sealed classes.
+#### Example:
+```java
+public sealed class Shape permits Circle, Square, Triangle {
+ // Class implementation
+}
+```
+## Sealed Interfaces
+Similarly, a sealed interface restricts which classes can implement it. It specifies the permitted implementing classes using the `permits` keyword.
+```java
+public sealed interface Vehicle permits Car, Truck, Motorcycle {
+ // Interface methods
+}
+```
+### Permitting Classes
+Permitted subclasses or implementing classes can be either final or non-sealed. If a subclass is final, it cannot have further subclasses. If it's non-sealed, it can have subclasses that are not explicitly listed in the permits clause.
+
+### Non-sealed Classes and Interfaces
+Non-sealed classes and interfaces can be extended or implemented by any class in the same package. They provide flexibility while designing the class hierarchy.
+#### Example
+```java
+public non-sealed class Animal {
+ // Class implementation
+}
+
+public non-sealed interface Printable {
+ void print();
+}
+
+```
+### Benefits
+**Enhanced Encapsulation :** Sealed classes and interfaces explicitly specify the allowed subclasses or implementing classes, thus preventing unexpected extensions or implementations.
+**Improved Maintainability :** By controlling the inheritance hierarchy, sealed classes and interfaces make the codebase more maintainable and easier to understand.
+**Stronger Contracts :** They provide clearer contracts for subclasses or implementing classes, reducing the likelihood of unintentional misuse.
+### Usage Guidelines
+- Use sealed classes and interfaces when you want to tightly control the inheritance hierarchy and provide clear boundaries for extensions or implementations.
+- Prefer sealed classes/interfaces over final classes/interfaces when you need to allow limited extension or implementation.
+### Compatibility
+- Sealed classes and interfaces were introduced as a preview feature in Java 15 and became permanent in Java 17. Ensure that you're using a compatible JDK version to leverage this feature.
+### Conclusion
+Sealed classes and interfaces are a powerful addition to Java's type system, providing fine-grained control over class hierarchies. By explicitly specifying permitted subclasses or implementing classes, they enhance encapsulation and maintainability of the codebase.
+
+
+
From f073006bd7916243c11aa61da2aa5318806767b5 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 20 Mar 2024 14:00:34 +0530
Subject: [PATCH 118/236] Create README.md
---
section_11/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_11/README.md
diff --git a/section_11/README.md b/section_11/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_11/README.md
@@ -0,0 +1 @@
+
From c86a6c81bbb83b1fea529ca22db456dd2d98b572 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 20 Mar 2024 17:51:11 +0530
Subject: [PATCH 119/236] Update README.md
---
section_11/README.md | 88 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 88 insertions(+)
diff --git a/section_11/README.md b/section_11/README.md
index 8b13789..8204319 100644
--- a/section_11/README.md
+++ b/section_11/README.md
@@ -1 +1,89 @@
+# Interfaces in Java
+## Creating Interfaces in java
+In Java, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields. The methods in interfaces are abstract by default, meaning they are declared with the abstract keyword and do not have a body. Any class that implements an interface must implement all the methods declared in the interface.
+## Steps to Create an Interface in Java
+### 1. Define the Interface
+Create a new Java file with a .java extension. Define your interface using the interface keyword followed by the interface name. Declare method signatures within the interface. Example:
+
+```java
+public interface MyInterface {
+ // Method signatures
+ void method1();
+ int method2();
+ String method3(String input);
+}
+```
+### 2. Implement the Interface
+Create a class that implements the interface. Use the implements keyword followed by the interface name after the class declaration. Implement all the methods declared in the interface. Example:
+```java
+public class MyClass implements MyInterface {
+ @Override
+ public void method1() {
+ // Implementation for method1
+ }
+
+ @Override
+ public int method2() {
+ // Implementation for method2
+ return 0;
+ }
+
+ @Override
+ public String method3(String input) {
+ // Implementation for method3
+ return "Result: " + input;
+ }
+}
+```
+### 3. Utilize the Interface
+Create objects of the class that implements the interface and use them to invoke the interface methods. Example:
+
+```java
+public class Main {
+ public static void main(String[] args) {
+ MyInterface obj = new MyClass();
+ obj.method1();
+ int result = obj.method2();
+ String output = obj.method3("Hello");
+ System.out.println(output);
+ }
+}
+```
+### Additional Notes
+- Interfaces can extend other interfaces using the extends keyword.
+- Classes can implement multiple interfaces by separating interface names with commas.
+- Interfaces are used to achieve abstraction and multiple inheritance in Java.
+### Advantages
+**1. Abstraction :** Interfaces allow you to define a set of methods that must be implemented by classes that use the interface. This helps in hiding the implementation details from the user, promoting a higher level of abstraction.
+
+**2. Multiple Inheritance :** Java does not support multiple inheritance for classes, but a class can implement multiple interfaces. This allows a class to inherit behaviors from multiple sources, promoting code reusability.
+
+**3. Polymorphism :** Interfaces support polymorphism, allowing objects of different classes to be treated interchangeably if they implement the same interface. This promotes flexibility and code modularity.
+
+**4. Loose Coupling :** Interfaces promote loose coupling between components in a system. Classes that use interfaces only depend on the methods declared in the interface, rather than specific implementations. This makes the code more maintainable and easier to refactor.
+## Constant Field Declarations in Interfaces
+In Java, interfaces can contain constant fields, which are implicitly public, static, and final. These fields represent constants that are shared across all classes that implement the interface. Utilizing constant fields in interfaces is a common practice for defining and enforcing a set of constants related to a particular domain or functionality.
+### Constant Field Declaration Syntax
+Constant fields in interfaces are declared similarly to variables but with additional modifiers to enforce immutability and accessibility.
+
+```java
+public interface MyInterface {
+ // Constant field declaration
+ public static final int MY_CONSTANT = 42;
+}
+```
+### Usage Examples
+Once constants are declared in an interface, they can be accessed by implementing classes without the need for instantiation.
+
+```java
+public class MyClass implements MyInterface {
+ public void printConstant() {
+ System.out.println(MyInterface.MY_CONSTANT); // Outputs: 42
+ }
+}
+```
+### Best Practices
+**Use Descriptive Names :** Choose meaningful names for constant fields to improve code readability and maintainability.
+**Group Related Constants :** Group related constants together within the same interface to maintain cohesion and organization.
+**Avoid Redundancy :** Avoid redeclaring constants in implementing classes; instead, access them directly through the interface.
From f12929c5fb6ca10db1cfcd7af2d25f78a64d31ba Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 20 Mar 2024 18:15:39 +0530
Subject: [PATCH 120/236] Update README.md
---
section_11/README.md | 144 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 144 insertions(+)
diff --git a/section_11/README.md b/section_11/README.md
index 8204319..d32d8f2 100644
--- a/section_11/README.md
+++ b/section_11/README.md
@@ -87,3 +87,147 @@ public class MyClass implements MyInterface {
**Use Descriptive Names :** Choose meaningful names for constant fields to improve code readability and maintainability.
**Group Related Constants :** Group related constants together within the same interface to maintain cohesion and organization.
**Avoid Redundancy :** Avoid redeclaring constants in implementing classes; instead, access them directly through the interface.
+
+
+## Interface Methods in Java
+
+In Java, interfaces provide a way to define a contract for classes to implement. They can contain method declarations without implementations, which are later implemented by classes that implement the interface. In this README, we'll discuss different types of methods allowed in Java interfaces.
+
+### Abstract Methods
+
+Abstract methods are methods declared in an interface without providing an implementation. Any class that implements the interface must provide an implementation for these methods.
+
+```java
+public interface MyInterface {
+ void abstractMethod();
+}
+```
+### Default Methods
+Default methods were introduced in Java 8. They allow interfaces to provide a default implementation for a method. Classes that implement the interface can use this default implementation or override it with their own implementation.
+
+```java
+public interface MyInterface {
+ default void defaultMethod() {
+ System.out.println("Default implementation of defaultMethod");
+ }
+}
+```
+### Static Methods
+Static methods in interfaces were introduced in Java 8. These methods are defined in the interface and can be called using the interface name. They cannot be overridden by implementing classes.
+
+```java
+public interface MyInterface {
+ static void staticMethod() {
+ System.out.println("Static method in interface");
+ }
+}
+```
+### Private Methods
+Private methods in interfaces were also introduced in Java 9. These methods are used to break down default methods into smaller, reusable units. They cannot be accessed outside the interface and are not inherited by implementing classes.
+
+```java
+public interface MyInterface {
+ default void defaultMethod() {
+ helperMethod();
+ }
+
+ private void helperMethod() {
+ System.out.println("Private helper method");
+ }
+}
+```
+### Summary
+**Abstract Methods :** Must be implemented by classes that implement the interface.
+**Default Methods :** Provide a default implementation that can be overridden.
+**Static Methods :** Defined in the interface and cannot be overridden.
+**Private Methods :** Used within the interface to break down default methods.
+Interfaces in Java provide a powerful mechanism for defining contracts and providing default behavior, making them a key component of the language's design.
+
+## Building Default Methods in Interfaces
+In Java, interfaces traditionally only allowed method declarations but not method implementations. However, with the introduction of Java 8, default methods were introduced, which allow interfaces to have methods with a default implementation. This feature was added to facilitate the evolution of interfaces without breaking existing implementations.
+### Example
+```java
+// Example interface with a default method
+interface MyInterface {
+ // Abstract method
+ void abstractMethod();
+
+ // Default method
+ default void defaultMethod() {
+ System.out.println("This is a default method.");
+ }
+}
+
+// Example class implementing MyInterface
+class MyClass implements MyInterface {
+ @Override
+ public void abstractMethod() {
+ System.out.println("Abstract method implementation.");
+ }
+}
+```
+### Creating Default Methods
+- Declare the method within the interface as you would for any other method.
+- Implement the method using the default keyword followed by the method body.
+```java
+class MyClass implements MyInterface {
+ // Optional: Override the default method
+ @Override
+ public void defaultMethod() {
+ // Custom implementation
+ }
+
+}
+```
+### Benefits of Default Methods
+**Backward Compatibility :** Allows adding new methods to interfaces without breaking existing implementations.
+**Code Reusability :** Provides a default implementation that can be reused across multiple classes.
+### Conclusion
+Default methods in interfaces provide a way to extend interfaces in Java without breaking the classes that implement them. They offer flexibility and backward compatibility, making it easier to evolve interfaces over time.
+## Building Static Methods in Interfaces
+In Java 8 and later versions, interfaces can have static methods. This feature enables interface types to have utility methods that can be called without creating an instance of the interface
+### Definition Syntax
+To declare a static method in an interface, use the static keyword followed by the method signature and body. Here's the syntax:
+```java
+public interface MyInterface {
+ static void myStaticMethod() {
+ // Method body
+ }
+}
+```
+### Accessing Static Methods
+Static methods in interfaces can be accessed using the interface name, followed by the `.` operator and the method name. Here's how you can access a static method:
+```java
+MyInterface.myStaticMethod();
+```
+### Example
+
+Let's create an interface named MathUtils with a static method multiply that multiplies two numbers:
+
+```java
+public interface MathUtils {
+ static int multiply(int a, int b) {
+ return a * b;
+ }
+}
+```
+Now, let's use this static method in a Java class:
+
+```java
+public class Main {
+ public static void main(String[] args) {
+ int result = MathUtils.multiply(5, 3);
+ System.out.println("Result: " + result); // Output: Result: 15
+ }
+}
+```
+### Considerations
+- Static methods in interfaces cannot be overridden by implementing classes or interfaces.
+- Static methods can only access other static members of the interface and cannot access instance members.
+- Static methods cannot be abstract.
+### Conclusion
+Static methods in interfaces provide a way to define utility methods associated with the interface type itself. They enhance code reusability and readability by encapsulating common functionality within the interface definition.
+
+
+## Multiple Inheritance Using Interfaces
+
From 72580167af92155eadb721dfac16b41faf16ddef Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 20 Mar 2024 18:18:31 +0530
Subject: [PATCH 121/236] Update README.md
---
section_11/README.md | 14 ++++++++------
1 file changed, 8 insertions(+), 6 deletions(-)
diff --git a/section_11/README.md b/section_11/README.md
index d32d8f2..8872156 100644
--- a/section_11/README.md
+++ b/section_11/README.md
@@ -4,8 +4,8 @@ In Java, an interface is a reference type, similar to a class, that can contain
## Steps to Create an Interface in Java
### 1. Define the Interface
-Create a new Java file with a .java extension. Define your interface using the interface keyword followed by the interface name. Declare method signatures within the interface. Example:
-
+Create a new Java file with a .java extension. Define your interface using the interface keyword followed by the interface name. Declare method signatures within the interface.
+#### Example
```java
public interface MyInterface {
// Method signatures
@@ -15,7 +15,8 @@ public interface MyInterface {
}
```
### 2. Implement the Interface
-Create a class that implements the interface. Use the implements keyword followed by the interface name after the class declaration. Implement all the methods declared in the interface. Example:
+Create a class that implements the interface. Use the implements keyword followed by the interface name after the class declaration. Implement all the methods declared in the interface.
+#### Example:
```java
public class MyClass implements MyInterface {
@Override
@@ -37,7 +38,8 @@ public class MyClass implements MyInterface {
}
```
### 3. Utilize the Interface
-Create objects of the class that implements the interface and use them to invoke the interface methods. Example:
+Create objects of the class that implements the interface and use them to invoke the interface methods.
+#### Example
```java
public class Main {
@@ -182,7 +184,7 @@ class MyClass implements MyInterface {
### Benefits of Default Methods
**Backward Compatibility :** Allows adding new methods to interfaces without breaking existing implementations.
**Code Reusability :** Provides a default implementation that can be reused across multiple classes.
-### Conclusion
+### Conclusion π
Default methods in interfaces provide a way to extend interfaces in Java without breaking the classes that implement them. They offer flexibility and backward compatibility, making it easier to evolve interfaces over time.
## Building Static Methods in Interfaces
In Java 8 and later versions, interfaces can have static methods. This feature enables interface types to have utility methods that can be called without creating an instance of the interface
@@ -225,7 +227,7 @@ public class Main {
- Static methods in interfaces cannot be overridden by implementing classes or interfaces.
- Static methods can only access other static members of the interface and cannot access instance members.
- Static methods cannot be abstract.
-### Conclusion
+### Conclusion π
Static methods in interfaces provide a way to define utility methods associated with the interface type itself. They enhance code reusability and readability by encapsulating common functionality within the interface definition.
From 0ef16988160c40712c1fc45532462fc57a127a65 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 20 Mar 2024 18:19:49 +0530
Subject: [PATCH 122/236] Update README.md
---
section_11/README.md | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/section_11/README.md b/section_11/README.md
index 8872156..24201db 100644
--- a/section_11/README.md
+++ b/section_11/README.md
@@ -5,7 +5,7 @@ In Java, an interface is a reference type, similar to a class, that can contain
## Steps to Create an Interface in Java
### 1. Define the Interface
Create a new Java file with a .java extension. Define your interface using the interface keyword followed by the interface name. Declare method signatures within the interface.
-#### Example
+#### Example π‘
```java
public interface MyInterface {
// Method signatures
@@ -16,7 +16,7 @@ public interface MyInterface {
```
### 2. Implement the Interface
Create a class that implements the interface. Use the implements keyword followed by the interface name after the class declaration. Implement all the methods declared in the interface.
-#### Example:
+#### Example π‘
```java
public class MyClass implements MyInterface {
@Override
@@ -39,7 +39,7 @@ public class MyClass implements MyInterface {
```
### 3. Utilize the Interface
Create objects of the class that implements the interface and use them to invoke the interface methods.
-#### Example
+#### Example π‘
```java
public class Main {
@@ -75,7 +75,7 @@ public interface MyInterface {
public static final int MY_CONSTANT = 42;
}
```
-### Usage Examples
+### Usage Examples π‘
Once constants are declared in an interface, they can be accessed by implementing classes without the need for instantiation.
```java
@@ -147,7 +147,7 @@ Interfaces in Java provide a powerful mechanism for defining contracts and provi
## Building Default Methods in Interfaces
In Java, interfaces traditionally only allowed method declarations but not method implementations. However, with the introduction of Java 8, default methods were introduced, which allow interfaces to have methods with a default implementation. This feature was added to facilitate the evolution of interfaces without breaking existing implementations.
-### Example
+### Example π‘
```java
// Example interface with a default method
interface MyInterface {
@@ -202,7 +202,7 @@ Static methods in interfaces can be accessed using the interface name, followed
```java
MyInterface.myStaticMethod();
```
-### Example
+### Example π‘
Let's create an interface named MathUtils with a static method multiply that multiplies two numbers:
From 36b0adfa4947ff49c0e5d3b103f889f8a334ae2e Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 20 Mar 2024 19:04:29 +0530
Subject: [PATCH 123/236] Update README.md
---
section_11/README.md | 120 ++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 118 insertions(+), 2 deletions(-)
diff --git a/section_11/README.md b/section_11/README.md
index 24201db..e72e77a 100644
--- a/section_11/README.md
+++ b/section_11/README.md
@@ -52,11 +52,11 @@ public class Main {
}
}
```
-### Additional Notes
+### Additional Notes π
- Interfaces can extend other interfaces using the extends keyword.
- Classes can implement multiple interfaces by separating interface names with commas.
- Interfaces are used to achieve abstraction and multiple inheritance in Java.
-### Advantages
+### Advantages π
**1. Abstraction :** Interfaces allow you to define a set of methods that must be implemented by classes that use the interface. This helps in hiding the implementation details from the user, promoting a higher level of abstraction.
**2. Multiple Inheritance :** Java does not support multiple inheritance for classes, but a class can implement multiple interfaces. This allows a class to inherit behaviors from multiple sources, promoting code reusability.
@@ -232,4 +232,120 @@ Static methods in interfaces provide a way to define utility methods associated
## Multiple Inheritance Using Interfaces
+In Java, a class can implement multiple interfaces, allowing it to inherit behavior from multiple sources. This is a form of multiple inheritance, albeit not in the traditional sense where a class directly inherits from multiple classes.
+### Example π‘
+Suppose we have two interfaces: `InterfaceA` and `InterfaceB`, each containing a method :
+
+```java
+public interface InterfaceA {
+ void methodA();
+}
+
+public interface InterfaceB {
+ void methodB();
+}
+```
+And a class `ExampleClass` that implements both interfaces:
+```java
+public class ExampleClass implements InterfaceA, InterfaceB {
+ @Override
+ public void methodA() {
+ System.out.println("Method A");
+ }
+
+ @Override
+ public void methodB() {
+ System.out.println("Method B");
+ }
+}
+```
+We can then create an instance of `ExampleClass` and call both methods:
+```java
+public class Main {
+ public static void main(String[] args) {
+ ExampleClass example = new ExampleClass();
+ example.methodA();
+ example.methodB();
+ }
+}
+```
+output
+```java
+Method A
+Method B
+```
+### Explanation
+In the example above, `ExampleClass` implements both `InterfaceA` and `InterfaceB`. By doing so, it inherits the abstract methods `methodA()` and `methodB()` from both interfaces. This allows `ExampleClass` to exhibit behavior from both `InterfaceA` and `InterfaceB`, achieving multiple inheritance through interfaces.
+### Conclusion π
+Using interfaces in Java, we can achieve a form of multiple inheritance by allowing classes to implement multiple interfaces. This provides a flexible way to inherit behavior from multiple sources while avoiding some of the complexities and issues associated with traditional multiple inheritance in other languages.
+## Marker Interface
+In Java, a Marker Interface is an interface that doesn't declare any methods. It serves as a tag for classes, indicating to the compiler or runtime environment that instances of those classes have some special behavior or characteristics associated with them.
+### Usage π
+Marker interfaces are typically used for:
+
+_ **Metadata :** They provide metadata to the compiler or runtime environment about the classes that implement them. For example, the `Serializable` interface in Java indicates that objects of the implementing class can be serialized.
+
+- **Marker for Frameworks :** They are often used in frameworks and libraries to enable conditional processing or to identify specific types. For instance, in the Java Collections Framework, the `Serializable` and `Cloneable` interfaces serve as markers to indicate that a class supports serialization and cloning, respectively.
+#### Example π‘
+```java
+// Define the Marker Interface
+public interface MyMarkerInterface {
+ // No methods declared
+}
+
+// Implement the Marker Interface
+public class MyClass implements MyMarkerInterface {
+ // Class implementation
+}
+
+// Usage
+public class Main {
+ public static void main(String[] args) {
+ MyClass obj = new MyClass();
+
+ // Check if the object implements the Marker Interface
+ if (obj instanceof MyMarkerInterface) {
+ System.out.println("Object is an instance of MyMarkerInterface");
+ // Additional actions specific to objects implementing the Marker Interface
+ } else {
+ System.out.println("Object does not implement MyMarkerInterface");
+ }
+ }
+}
+```
+### Notes π
+- Marker interfaces are a design pattern in Java and are often used when there's a need to provide metadata about classes at compile time or runtime.
+- While marker interfaces serve their purpose, they have limitations, such as not being able to provide any additional functionality or behavior through methods.
+## Functional Interface
+- A functional interface in Java is an interface that contains only one abstract method. It can have any number of default or static methods, but only one abstract method. Functional interfaces are used extensively in Java 8's lambda expressions and method references.
+- Functional interfaces provide a way to implement functional programming concepts in Java. They enable the use of lambda expressions, which provide a concise way to express instances of single-method interfaces (functional interfaces).
+#### Example π‘
+```java
+```java
+@FunctionalInterface
+interface MyFunctionalInterface {
+ void myMethod();
+}
+```
+### Predefined Functional Interfaces
+Java provides several predefined functional interfaces in the java.util.function package, such as `Function`,` Predicate`, `Consumer`,` Supplier` etc. For example:
+```java
+import java.util.function.Consumer;
+
+public class Main {
+ public static void main(String[] args) {
+ Consumer consumer = (str) -> System.out.println(str);
+ consumer.accept("Hello, world!");
+ }
+}
+
+```
+### Restrictions
+- Functional interfaces can contain only one abstract method. If you try to add more than one abstract method, it will result in a compilation error.
+- They can have any number of default or static methods without affecting their functional nature.
+- You can use the `@FunctionalInterface` annotation to ensure that an interface is a functional interface, although it's not strictly required.
+### Conclusion π
+Functional interfaces are a powerful feature introduced in Java 8, enabling functional programming paradigms within Java. They facilitate the use of lambda expressions, making code more concise and readable.
+
+
From 9d7333fa177010d30a9bec3b378293324bb15bbd Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 21 Mar 2024 12:21:08 +0530
Subject: [PATCH 124/236] Create README.md
---
section_12/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_12/README.md
diff --git a/section_12/README.md b/section_12/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_12/README.md
@@ -0,0 +1 @@
+
From 464179034b31e3c7443dc5d10142fd2dfe64d9b5 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 21 Mar 2024 13:46:26 +0530
Subject: [PATCH 125/236] Update README.md
---
section_12/README.md | 127 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 127 insertions(+)
diff --git a/section_12/README.md b/section_12/README.md
index 8b13789..367b443 100644
--- a/section_12/README.md
+++ b/section_12/README.md
@@ -1 +1,128 @@
+# Arrays in Java
+Arrays in Java are a fundamental data structure used to store a fixed-size sequential collection of elements of the same type. They provide a convenient way to group multiple variables of the same type under a single name.
+## Declaration and Initialization
+```java
+public class Numbers
+{
+ public static void main(String[] args) {
+// Declaration and Initialization
+ int num[]={1,2,3,4};
+}
+```
+Using the `new` Keyword
+```java
+public class Numbers
+{
+ public static void main(String[] args) {
+
+ int size=5;
+ //Declaration
+ int num[] = new int[size];
+
+ int numbers=1;
+ for(int i=0;i
Date: Thu, 21 Mar 2024 14:12:32 +0530
Subject: [PATCH 126/236] Update README.md
---
section_12/README.md | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/section_12/README.md b/section_12/README.md
index 367b443..0909d55 100644
--- a/section_12/README.md
+++ b/section_12/README.md
@@ -121,6 +121,12 @@ public class ArrayIteration {
```
### Conclusion
The for-each loop provides a convenient and concise way to iterate over arrays and collections in Java. It simplifies the syntax and improves code readability, making it a preferred choice for looping through elements.
+## Copying Arrays Using Loops
+Copying arrays in Java is a common operation in programming. It allows you to create a new array with the same elements as an existing array, which is useful for various tasks such as data manipulation, sorting, and more. By this we can create a new array with required size.
+
+
+
+
From db1ce779af8750badc3aa38516ae3e758df573a8 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 21 Mar 2024 14:18:29 +0530
Subject: [PATCH 127/236] Update README.md
---
section_12/README.md | 43 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 43 insertions(+)
diff --git a/section_12/README.md b/section_12/README.md
index 0909d55..31487dc 100644
--- a/section_12/README.md
+++ b/section_12/README.md
@@ -123,6 +123,49 @@ public class ArrayIteration {
The for-each loop provides a convenient and concise way to iterate over arrays and collections in Java. It simplifies the syntax and improves code readability, making it a preferred choice for looping through elements.
## Copying Arrays Using Loops
Copying arrays in Java is a common operation in programming. It allows you to create a new array with the same elements as an existing array, which is useful for various tasks such as data manipulation, sorting, and more. By this we can create a new array with required size.
+```java
+package com.eazybytes.main;
+
+import java.util.Arrays;
+
+public class ArrayCopyDemo {
+
+ public static void main(String[] args) {
+
+ int[] oldArray = {1,2,3,4,5};
+ int[] newArray = new int[oldArray.length+5];
+ newArray = copyArrayUsingLoop(oldArray, newArray);
+
+ for(int num:targetArray1) {
+ System.out.println(num);
+ }
+
+ }
+
+ private static int[] copyArrayUsingLoop(int[] oldArray, int[] newArray) {
+ for(int i = 0; i
Date: Thu, 21 Mar 2024 14:33:52 +0530
Subject: [PATCH 128/236] Update README.md
---
section_12/README.md | 27 +++++++++++++++++++++++++++
1 file changed, 27 insertions(+)
diff --git a/section_12/README.md b/section_12/README.md
index 31487dc..86e03ee 100644
--- a/section_12/README.md
+++ b/section_12/README.md
@@ -164,6 +164,33 @@ int[] sourceArray = {1, 2, 3, 4, 5};
int[] destinationArray = Arrays.copyOf(sourceArray, sourceArray.length);
```
#### Example
+```java
+package com.eazybytes.main;
+
+import java.util.Arrays;
+
+public class ArrayCopyDemo {
+
+ public static void main(String[] args) {
+
+ int[] oldArray = {1,2,3,4,5};
+ int[] newArray = new int[oldArray.length+5];
+
+ System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
+ int[] targetArray = Arrays.copyOf(oldArray,3);
+
+ for(int num:targetArray1) {
+ System.out.println(num);
+ }
+
+ }
+}
+```
+## Coverting Arrays
+The `Arrays` class in Java provides a convenient method `toString()` to convert an array to a string representation. This method can handle arrays of primitive types and objects.
+#### Example
+
+
From a6a326756e4e88dabffefc93dda33f0ff0cd08a8 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 21 Mar 2024 22:15:30 +0530
Subject: [PATCH 129/236] Update README.md
---
section_12/README.md | 33 +++++++++++++++++++++++++++++++++
1 file changed, 33 insertions(+)
diff --git a/section_12/README.md b/section_12/README.md
index 86e03ee..8452f5c 100644
--- a/section_12/README.md
+++ b/section_12/README.md
@@ -189,6 +189,39 @@ public class ArrayCopyDemo {
## Coverting Arrays
The `Arrays` class in Java provides a convenient method `toString()` to convert an array to a string representation. This method can handle arrays of primitive types and objects.
#### Example
+```java
+package com.eazybytes.main;
+
+import java.util.Arrays;
+
+public class ToStringDemo {
+
+ public static void main(String[] args) {
+ int[] numbers = {1,2,3,4,5};
+ System.out.println(Arrays.toString(numbers));
+ System.out.println(numbers);// Output : [1,2,3,4,5]
+ }
+
+}
+```
+## Sorting Arrays
+`Arrays.sort()` is a method provided by the `java.util.Arrays` class in Java, used for sorting arrays of primitive data types and objects. It sorts the specified array into ascending numerical or lexicographical order. This method uses the dual-pivot quicksort algorithm for sorting primitive types and the merge sort algorithm for sorting objects.
+#### Example
+```java
+import java.util.Arrays;
+
+public class Main {
+ public static void main(String[] args) {
+ int[] numbers = {5, 2, 8, 4, 1};
+
+ // Sort the entire array
+ Arrays.sort(numbers);
+ System.out.println("Sorted array: " + Arrays.toString(numbers));// [1,2,4,5,8]
+ }
+}
+
+```
+
From 02f9a9e22e1e174544193fdea4f77362bf35128b Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 21 Mar 2024 22:30:02 +0530
Subject: [PATCH 130/236] Update README.md
---
section_12/README.md | 3 +++
1 file changed, 3 insertions(+)
diff --git a/section_12/README.md b/section_12/README.md
index 8452f5c..67febc4 100644
--- a/section_12/README.md
+++ b/section_12/README.md
@@ -221,6 +221,9 @@ public class Main {
}
```
+## Arrays.fill()
+The `Arrays.fill()` method from the `java.util` package fills the specified array with the specified value.
+
From bbdff43595cab1d1926f61171fccb891a2fecb75 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 21 Mar 2024 22:45:32 +0530
Subject: [PATCH 131/236] Update README.md
---
section_12/README.md | 89 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 89 insertions(+)
diff --git a/section_12/README.md b/section_12/README.md
index 67febc4..901f502 100644
--- a/section_12/README.md
+++ b/section_12/README.md
@@ -223,6 +223,95 @@ public class Main {
```
## Arrays.fill()
The `Arrays.fill()` method from the `java.util` package fills the specified array with the specified value.
+#### Example
+```java
+package com.eazybytes.main;
+
+import java.util.Arrays;
+
+public class FillDemo {
+
+ public static void main(String[] args) {
+
+ int[] scores = new int[10];
+ Arrays.fill(scores, 100);
+ System.out.println(Arrays.toString(scores));
+
+ int[] indices = new int[5];
+ Arrays.setAll(indices, i -> i*2);
+ System.out.println(Arrays.toString(indices));
+
+ }
+
+}
+```
+## Arrays.setAll()
+In Java, the `Arrays.setAll()` method is used to set each element of an array to the result of applying a specified generator function to its index.
+### Syntax
+```java
+public static void setAll(T[] array, IntFunction extends T> generator)
+```
+- **array :** the array whose elements are to be set.
+- **generator :** a function that accepts an integer index and produces a value to be stored at that index in the array.
+#### Example
+Suppose we have an array of integers and we want to initialize it with consecutive even numbers starting from 0.
+```java
+import java.util.Arrays;
+import java.util.function.IntFunction;
+
+public class Main {
+ public static void main(String[] args) {
+ int size = 5;
+ int[] arr = new int[size];
+
+ Arrays.setAll(arr, index -> index * 2);
+
+ // Output the array
+ System.out.println(Arrays.toString(arr)); // Output: [0, 2, 4, 6, 8]
+ }
+}
+```
+In this example:
+- We create an array of size 5.
+- We use `Arrays.setAll()` to set each element of the array to `index * 2`, effectively assigning consecutive even numbers starting from 0.
+- Finally, we print out the contents of the array.
+### Notes
+- The generator function is called for each index of the array in ascending order.
+- It's important to ensure that the generator function does not throw any exceptions when called.
+- The method throws `NullPointerException` if the specified array or generator is null.
+## 2D Arrays
+A 2D array, also known as a matrix, is a grid of elements where each element is identified by two indices - row and column. In Java, 2D arrays are used to represent matrices, tables, grids, or other 2-dimensional structures.
+```java
+// Declare and initialize a 2D array with specified dimensions
+int[][] matrix = new int[rows][columns];
+
+// Initialize a 2D array with predefined values
+int[][] matrix = {{1, 2, 3},{4, 5, 6},{7, 8, 9}};
+```
+### Accessing Elements
+Accessing elements in a 2D array involves specifying both row and column indices
+```java
+// Accessing an element at row i and column j
+int element = matrix[i][j];
+```
+### Traversing a 2D Array
+Traversing a 2D array requires nested loops to iterate through each row and column.
+```java
+for (int i = 0; i < matrix.length; i++) {
+ for (int j = 0; j < matrix[i].length; j++) {
+ // Accessing and performing operations on matrix[i][j]
+ }
+}
+```
+### Common Operations
+- Transpose: Switching rows with columns in a 2D array.
+- Matrix Addition: Adding two matrices of the same dimensions.
+- Matrix Multiplication: Multiplying two matrices following specific rules.
+## Matrix Addition
+This Java program demonstrates how to add two matrices of the same dimensions.
+
+
+
From 240beee0df0aac58634b7c27c54343b60cc6654e Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 21 Mar 2024 22:56:16 +0530
Subject: [PATCH 132/236] Update README.md
---
section_12/README.md | 70 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 70 insertions(+)
diff --git a/section_12/README.md b/section_12/README.md
index 901f502..925c655 100644
--- a/section_12/README.md
+++ b/section_12/README.md
@@ -309,6 +309,76 @@ for (int i = 0; i < matrix.length; i++) {
- Matrix Multiplication: Multiplying two matrices following specific rules.
## Matrix Addition
This Java program demonstrates how to add two matrices of the same dimensions.
+```java
+package com.eazybytes.main;
+
+public class AddMatricesDemo {
+
+ public static void main(String[] args) {
+
+ int[][] array1 = {
+ {4,7,9}, {5,7,0}
+ };
+ int[][] array2 = {
+ {3,8,2}, {2,6,1}
+ };
+
+ int[][] sumArray = new int[2][3];
+
+ for (int i = 0;i
Date: Thu, 21 Mar 2024 22:57:30 +0530
Subject: [PATCH 133/236] Update README.md
---
section_12/README.md | 44 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 44 insertions(+)
diff --git a/section_12/README.md b/section_12/README.md
index 925c655..47706d4 100644
--- a/section_12/README.md
+++ b/section_12/README.md
@@ -377,6 +377,50 @@ To create a 3D array in Java, you need to specify the dimensions of each dimensi
```java
dataType[][][] arrayName = new dataType[xSize][ySize][zSize];
```
+#### Example
+```java
+package com.eazybytes.main;
+
+import java.util.Arrays;
+
+public class ThreeDArrayDemo {
+
+ public static void main(String[] args) {
+
+ int noOfStudents = 2;
+ int subjects = 4;
+ int totalSemesters = 5;
+
+ int[][][] studentArray = new int[noOfStudents][subjects][totalSemesters];
+
+ // Student 1 data
+ int[][] student1 = {
+ { 88, 76, 90, 82, 98 },
+ { 82, 96, 92, 72, 99 },
+ { 86, 66, 94, 93, 100 },
+ { 85, 86, 97, 92, 97 },
+ };
+ // Student 2 data
+ int[][] student2 = {
+ { 78, 85, 70, 72, 88 },
+ { 62, 92, 82, 91, 91 },
+ { 76, 72, 93, 87, 82 },
+ { 55, 83, 87, 71, 100 },
+ };
+
+ studentArray[0] = student1;
+ studentArray[1] = student2;
+
+ System.out.println(Arrays.deepToString(studentArray));
+
+
+
+ }
+
+}
+```
+### Conclusion
+Working with 3D arrays in Java allows you to manipulate data in a three-dimensional space efficiently. By understanding how to create, access, and manipulate 3D arrays, you can develop applications that deal with volumetric data, simulations, and more.
From 4e7262cb68022948f2d1dc9962036cf9c571f51b Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 09:51:59 +0530
Subject: [PATCH 134/236] Create README.md
---
section_13/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_13/README.md
diff --git a/section_13/README.md b/section_13/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_13/README.md
@@ -0,0 +1 @@
+
From 065f9dcd6b4451c4fd68931c9666682636f5ee97 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 09:58:59 +0530
Subject: [PATCH 135/236] Update README.md
---
section_13/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section_13/README.md b/section_13/README.md
index 8b13789..dd69592 100644
--- a/section_13/README.md
+++ b/section_13/README.md
@@ -1 +1 @@
-
+# Accept input using
From fc4959bc7d57c26739ff6928d8e415c1f43572ee Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 10:23:19 +0530
Subject: [PATCH 136/236] Update README.md
---
section_13/README.md | 52 +++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 51 insertions(+), 1 deletion(-)
diff --git a/section_13/README.md b/section_13/README.md
index dd69592..1f9c93f 100644
--- a/section_13/README.md
+++ b/section_13/README.md
@@ -1 +1,51 @@
-# Accept input using
+# Accept input using BufferedReader and Scanner
+## Understanding System.out.println()
+In Java, `System.out.println()` is a method used to print data to the standard output stream, typically the console. It belongs to the `java.io.PrintStream` class and is widely used for debugging, logging, and displaying information to the user.
+### Syntax
+The syntax of `System.out.println()` is as follows
+```java
+System.out.println(data);
+```
+Here, data can be of any primitive `data` type or an object. Multiple parameters can also be passed, which are automatically converted to strings and then printed.
+#### Example
+```java
+public class HelloWorld {
+ public static void main(String[] args) {
+ int number = 10;
+ String message = "Hello, world!";
+
+ // Printing integer variable
+ System.out.println("The number is: " + number);
+
+ // Printing string variable
+ System.out.println(message);
+
+ // Printing multiple variables
+ System.out.println("Number: " + number + ", Message: " + message);
+ }
+}
+```
+```java
+The number is: 10
+Hello, world!
+Number: 10, Message: Hello, world!
+```
+#### Key Points
+- `System.out.println()` automatically adds a newline character after printing the data.
+- It can be used with any primitive data type or object.
+- The method is overloaded to handle different types of parameters.
+- It's commonly used for debugging purposes to print variable values and messages.
+### Conclusion
+Understanding `System.out.println()` is fundamental to Java programming. It's a versatile method for printing data to the console and is essential for debugging and communicating with the user.
+## System.in.read()
+`System.in.read()` is a method in Java that reads a single byte of data from the standard input stream (`System.in`). It primarily reads bytes of data, making it suitable for handling low-level input operations. This method can be useful in scenarios where more sophisticated input handling, such as reading strings or other data types, is not required.
+### Syntax
+```java
+public static int read() throws IOException
+```
+#### Example
+```java
+
+
+
+
From 3130ab7593d1a91460f8fa16d63f768b0a1e7f81 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 10:46:49 +0530
Subject: [PATCH 137/236] Update README.md
---
section_13/README.md | 27 +++++++++++++++++++++++++++
1 file changed, 27 insertions(+)
diff --git a/section_13/README.md b/section_13/README.md
index 1f9c93f..a1e300f 100644
--- a/section_13/README.md
+++ b/section_13/README.md
@@ -45,6 +45,33 @@ public static int read() throws IOException
```
#### Example
```java
+package com.eazybytes.input;
+
+import java.io.IOException;
+
+public class JavaBasicInputDemo {
+
+ public static void main(String[] args) throws IOException {
+ System.out.println("Please enter a value...");
+ int num = System.in.read();
+ System.out.println("The user entered a value: "+ num); // It will display the ASCII value of entered number
+ }
+
+}
+```
+### Return Value
+- Returns the next byte of data from the input stream as an integer in the range 0 to 255. If the end of the stream has been reached, the value -1 is returned.
+### Exceptions
+- IOException - If an I/O error occurs.
+### Notes
+- This method reads only one byte at a time, making it suitable for handling raw byte input. For reading characters or strings, consider using higher-level input operations provided by classes like `Scanner` or `BufferedReader`.
+- Since `System.in.read()` reads bytes, it may not handle multibyte characters correctly in all cases, especially when dealing with character encodings beyond the ASCII range.
+- Always wrap the call to `System.in.read()` within a try-catch block to handle any potential I/O errors.
+## BufferedReader
+BufferedReader is a class in Java that reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
+#### Example
+```java
+
From b65dbedbdc379d4559802af5817a91775407f3d2 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 11:09:23 +0530
Subject: [PATCH 138/236] Update README.md
---
section_13/README.md | 53 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 53 insertions(+)
diff --git a/section_13/README.md b/section_13/README.md
index a1e300f..889f6a0 100644
--- a/section_13/README.md
+++ b/section_13/README.md
@@ -71,6 +71,59 @@ public class JavaBasicInputDemo {
BufferedReader is a class in Java that reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
#### Example
```java
+package com.eazybytes.input;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+
+public class BufferedReaderDemo {
+
+ public static void main(String[] args) throws IOException {
+ InputStreamReader isr = new InputStreamReader(System.in);
+ BufferedReader bf = new BufferedReader(isr);
+ System.out.println("Please enter a value...");
+ String input = bf.readLine();
+ System.out.println("The user entered a value: "+ input);
+ bf.close();
+ }
+
+}
+```
+#### Example for identify even and odd numbers
+```java
+package com.eazybytes.input;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+
+public class BufferedReaderDemo {
+
+ public static void main(String[] args) throws IOException {
+ InputStreamReader isr = new InputStreamReader(System.in);
+ BufferedReader bf = new BufferedReader(isr);
+ System.out.println("Please enter a value...");
+ String input = bf.readLine();
+ // System.out.println("The user entered a value: "+ input);
+ int number = Integer.parseInt(input);
+ if(number % 2 == 0){
+ System.out.println("You have entered even number");
+ }else{
+ System.out.println("You have entered odd number");
+ }
+ bf.close();
+ }
+
+}
+```
+## Scanner
+## The `Scanner` class in Java is used to parse primitive types and strings from the standard input.
+#### Example
+```java
+
+
+
From 36ec8ef02954b0761cc4ad3be8fab2a79dbac1d5 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 11:17:08 +0530
Subject: [PATCH 139/236] Update README.md
---
section_13/README.md | 28 ++++++++++++++++++++++++++++
1 file changed, 28 insertions(+)
diff --git a/section_13/README.md b/section_13/README.md
index 889f6a0..9f8dd47 100644
--- a/section_13/README.md
+++ b/section_13/README.md
@@ -121,6 +121,34 @@ public class BufferedReaderDemo {
## The `Scanner` class in Java is used to parse primitive types and strings from the standard input.
#### Example
```java
+package com.eazybytes.input;
+
+import java.util.Scanner;
+
+public class ScannerDemo {
+
+ public static void main(String[] args) {
+ Scanner sc = new Scanner(System.in);
+ System.out.println("Enter your name:");
+ String name = sc.nextLine();
+ System.out.println("Enter your age:");
+ int age = sc.nextInt();
+ System.out.println("Hello "+ name+ " , you are "+ age+" years old.");
+ sc.close();
+ }
+
+}
+```
+## Java Logging
+Logging is an essential aspect of software development, providing insight into the behavior of applications during runtime. In Java, the `java.util.logging` package offers a straightforward logging solution that comes bundled with the JDK.
+### Features
+- Logging configuration
+- Log levels (INFO, WARNING, SEVERE)
+- Writing log messages to console and file
+#### Example
+```java
+
+
From 71411a6835688cc25d8bb6e2a0331ed4a92f9c92 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 11:20:20 +0530
Subject: [PATCH 140/236] Update README.md
---
section_13/README.md | 32 ++++++++++++++++++++++++++++++++
1 file changed, 32 insertions(+)
diff --git a/section_13/README.md b/section_13/README.md
index 9f8dd47..55768d9 100644
--- a/section_13/README.md
+++ b/section_13/README.md
@@ -147,6 +147,38 @@ Logging is an essential aspect of software development, providing insight into t
- Writing log messages to console and file
#### Example
```java
+package com.eazybytes.log;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class LoggingDemo {
+
+ private static Logger logger = Logger.getLogger(LoggingDemo.class.getName());
+
+ public static void main(String[] args) {
+ logger.setLevel(Level.SEVERE);
+ logger.info("This is info level logging");
+ logger.log(Level.WARNING, "This is warning level logging");
+ logger.severe("This is severe level logging");
+ System.out.println("Hello using System.out.println");
+ }
+
+}
+```
+### Usage
+- The `Logger` class is used to log messages in your Java code.
+- Log messages can be categorized into different levels such as INFO, WARNING, and SEVERE.
+- Use appropriate log levels to convey the importance of log messages.
+- Log messages can be directed to different destinations such as console, file, or custom handlers.
+### Conclusion
+- Logging plays a crucial role in understanding the behavior of Java applications during runtime. By integrating logging into your projects, you gain valuable insights into the execution flow, identify issues, and monitor application health.
+
+- This Java logging example demonstrates the fundamental concepts of logging, including configuring log levels, directing log output to different destinations, and utilizing the `java.util.logging` package effectively.
+
+- With the knowledge gained from this example, you can enhance the robustness and maintainability of your Java applications by implementing logging practices tailored to your specific use cases.
+
+
From 27d0209f7be5ffe5c5c5653578183cde117b2190 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 11:21:09 +0530
Subject: [PATCH 141/236] Create README.md
---
section_14/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_14/README.md
diff --git a/section_14/README.md b/section_14/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_14/README.md
@@ -0,0 +1 @@
+
From c4dcbdbbfae90b8e4d0dd3787a0fd2d10c6e91bb Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 11:55:45 +0530
Subject: [PATCH 142/236] Update README.md
---
section_14/README.md | 34 ++++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index 8b13789..d68d631 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -1 +1,35 @@
+# Exception handling using try, catch and finally
+In Java, an exception is an event that disrupts the normal flow of a program's instructions during execution. When an exceptional condition occurs, the Java runtime creates an exception object, which contains information about the error, such as its type and the state of the program when the error occurred. This exception object is then "thrown" from the point in the code where the error occurred, and the runtime searches for an exception handler that can handle it.
+
+There are two main types of exceptions in Java: checked exceptions and unchecked exceptions. Checked exceptions are exceptions that must be either caught or declared to be thrown by the method in which they may occur. Unchecked exceptions, on the other hand, are exceptions that do not need to be explicitly caught or declared, and they typically indicate programming errors or other exceptional conditions that are beyond the control of the program.
+
+Java provides a robust exception handling mechanism through the use of try-catch blocks, where code that may throw exceptions is enclosed in a try block, and any exceptions that are thrown are caught and handled by catch blocks. Additionally, Java allows for the use of finally blocks to execute cleanup code regardless of whether an exception is thrown or not. This combination of try, catch, and finally blocks provides a powerful mechanism for managing exceptional conditions in Java programs.
+
+## Exception Hierarchy
+Throwable:
+
+- **Error :** Represents serious problems that are typically beyond the control of the application, such as OutOfMemoryError or StackOverflowError. Usually, it is not appropriate for applications to catch or handle Error instances.
+- **Exception :** Represents exceptional conditions that a program should catch and handle. This is further divided into:
+- **Checked Exceptions (Compiletime Exceptions) :** These are exceptions that must be either caught or declared in the method's throws clause. They are subclasses of Exception but not of RuntimeException.
+- **Unchecked Exceptions (RuntimeExceptions) :** These are exceptions that don't need to be caught or declared. They typically represent programming errors or other conditions that are beyond the control of the program. They are subclasses of RuntimeException.
+### Checked Exceptions:
+
+- **IOException :** Represents an error occurred during I/O operations.
+- **FileNotFoundException :** Indicates that a file could not be found.
+- **EOFException :** Indicates that the end of a file or stream has been reached unexpectedly.
+- **SQLException :** Indicates an error occurred while accessing a database.
+- **ClassNotFoundException :** Indicates that a class could not be found during runtime.
+And many more...
+### Unchecked Exceptions (RuntimeExceptions):
+
+- **ArithmeticException :** Indicates that an arithmetic operation has failed.
+- **NullPointerException :** Indicates an attempt to access or invoke a method on a null object.
+- **ArrayIndexOutOfBoundsException :** Indicates that an array has been accessed with an illegal index.
+- **IllegalArgumentException :** Indicates that a method has been passed an illegal or inappropriate argument.
+- **IllegalStateException :** Indicates that the application is in an inappropriate state for the requested operation.
+- **ClassCastException :** Indicates an invalid cast operation.
+And many more...
+### Example with try, catch block
+```java
+
From e5afa717222900dccfc1708be2244235d02bf5bb Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 12:01:03 +0530
Subject: [PATCH 143/236] Update README.md
---
section_14/README.md | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index d68d631..8ce1032 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -31,5 +31,30 @@ And many more...
And many more...
### Example with try, catch block
```java
+package com.eazybytes.exception;
+
+import java.util.InputMismatchException;
+import java.util.Scanner;
+
+public class ExceptionDemo {
+
+ public static void main(String[] args) {
+ Scanner scanner = null;
+ try {
+ scanner = new Scanner(System.in);
+ System.out.println("Enter a number....");
+ int number = scanner.nextInt();
+ System.out.println(number);
+ }
+ catch(Exception ex) {
+ System.out.println("Please provide input in numerical format only and try again...");
+ }
+ }
+}
+```
+### ArrayIndexOutofBoundsException
+`ArrayIndexOutOfBoundsException` is a runtime exception in Java that occurs when you try to access an index that is outside the bounds of an array. For example, if you have an array with 5 elements and you try to access the 6th element, it will throw `ArrayIndexOutOfBoundsException`.
+
+
From 5b42367f3e071453d1d0612b4cf70f6762a83d6d Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 12:03:12 +0530
Subject: [PATCH 144/236] Update README.md
---
section_14/README.md | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index 8ce1032..24411ca 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -54,6 +54,31 @@ public class ExceptionDemo {
```
### ArrayIndexOutofBoundsException
`ArrayIndexOutOfBoundsException` is a runtime exception in Java that occurs when you try to access an index that is outside the bounds of an array. For example, if you have an array with 5 elements and you try to access the 6th element, it will throw `ArrayIndexOutOfBoundsException`.
+```java
+package com.eazybytes.exception;
+
+import java.util.logging.Logger;
+
+public class ArrayIndexOutofBoundsExceptionDemo {
+
+ private static Logger logger = Logger.getLogger(
+ ArrayIndexOutofBoundsExceptionDemo.class.getName());
+
+ public static void main(String[] args) {
+ try {
+ int[] numbers = {1,2,3,4,5};
+ System.out.println(numbers[5]);
+ } catch (Exception ex) {
+ logger.severe("Invalid Array index. Please try again with a valid index number");
+ }
+
+ }
+}
+```
+### With Multipple catch blocks
+```java
+
+
From 144765efea4013b81bdf6268ae595453c6f12ecd Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 12:26:21 +0530
Subject: [PATCH 145/236] Update README.md
---
section_14/README.md | 48 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 48 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index 24411ca..a85a9da 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -77,6 +77,54 @@ public class ArrayIndexOutofBoundsExceptionDemo {
```
### With Multipple catch blocks
```java
+package com.eazybytes.exception;
+
+import java.io.IOException;
+import java.util.InputMismatchException;
+import java.util.logging.Logger;
+
+public class MultipleCatchDemo {
+
+ private static Logger logger = Logger.getLogger(
+ MultipleCatchDemo.class.getName());
+
+ public static void main(String[] args) {
+ String input = null;
+ try {
+ input = "Madan";
+ input = input.toUpperCase();
+ logger.info(input);
+ input = input.substring(1,10);
+ logger.info(input);
+ } catch (NullPointerException ex) {
+ logger.severe("An null pointer exception occurred. Please check your data");
+ } catch (StringIndexOutOfBoundsException | ArrayIndexOutOfBoundsException ex) {
+ logger.severe("IndexOutOfBoundsException exception occurred. Please check your input data");
+ } catch (Exception ex) {
+ logger.severe("An exception occurred. Please check your program");
+ }
+ }
+}
+```
+### finally block
+In Java, the `finally` block is used to define a block of code that will be executed after a `try` block has completed execution, whether an exception is thrown or not. This block ensures that certain cleanup or finalization tasks are performed, such as closing resources like files or database connections.
+### Syntax
+```java
+try {
+ // Code that may throw an exception
+} catch (Exception e) {
+ // Exception handling code
+} finally {
+ // Code to be executed regardless of whether an exception is thrown or not
+}
+```
+- The `try` block contains the code that may throw an exception.
+- The `catch` block is optional and is used to handle exceptions.
+- The `finally` block contains the code that will be executed regardless of whether an exception occurs or not.
+#### Example
+```java
+
+
From 543f78fa0a3c0ed3da2fc5b4fe7d1ada03809301 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 12:32:01 +0530
Subject: [PATCH 146/236] Update README.md
---
section_14/README.md | 44 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 44 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index a85a9da..6dd6323 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -123,6 +123,50 @@ try {
- The `finally` block contains the code that will be executed regardless of whether an exception occurs or not.
#### Example
```java
+package com.eazybytes.exception;
+
+import java.util.InputMismatchException;
+import java.util.Scanner;
+
+public class ExceptionDemo {
+
+ public static void main(String[] args) {
+ Scanner scanner = null;
+ try {
+ scanner = new Scanner(System.in);
+ System.out.println("Enter a number....");
+ int number = scanner.nextInt();
+ System.out.println(number);
+ }
+ catch(Exception ex) {
+ System.out.println("Please provide input in numerical format only and try again...");
+ }
+ finally {
+ System.out.println("finally block is being executed");
+ if(scanner != null) {
+ scanner.close();
+ }
+ }
+
+ }
+
+}
+```
+### Key Points
+- The `finally` block is always executed, even if an exception is thrown.
+- If an exception is thrown and caught, the `finally` block is executed after the `catch` block.
+- If no exception is thrown, the `finally` block is still executed after the `try` block.
+- The `finally` block is often used to perform cleanup tasks, such as closing resources opened in the `try` block.
+### Best Practices
+- **Resource Management :** Use the `finally` block to ensure that resources like files, database connections, or network connections are properly closed, regardless of whether an exception occurs.
+- **Error Cleanup :** Perform any necessary cleanup operations in the `finally` block to leave the program or system in a consistent state, even in the event of an error.
+- **Avoid Logic :** Keep the `finally` block free from complex logic to ensure that it executes quickly and reliably. Complex logic in the `finally` block can make code harder to understand and maintain.
+### Try-With-Resources
+Try-With-Resources is a feature introduced in Java 7 that simplifies resource management by automatically closing resources that are opened within the try block. It ensures that resources are closed properly without the need for explicit finally blocks.
+#### Example
+```java
+
+
From 1faae851f6958acc1c55f96d0c92bfec344ee84c Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 12:34:39 +0530
Subject: [PATCH 147/236] Update README.md
---
section_14/README.md | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index 6dd6323..5d0494d 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -165,6 +165,30 @@ public class ExceptionDemo {
Try-With-Resources is a feature introduced in Java 7 that simplifies resource management by automatically closing resources that are opened within the try block. It ensures that resources are closed properly without the need for explicit finally blocks.
#### Example
```java
+package com.eazybytes.exception;
+
+import java.util.Scanner;
+
+public class TryWithResourcesDemo {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ System.out.println("Enter a number....");
+ int number = scanner.nextInt();
+ System.out.println(number);
+ } catch(Exception ex) {
+ System.out.println("Please provide input in numerical format only and try again...");
+ }
+ }
+
+}
+```
+### Advantges
+**Automatic Resource Management :** With try-with-resources, resources are automatically closed after the try block, ensuring proper cleanup without the need for explicit finally blocks. This reduces the chance of resource leaks and simplifies code maintenance.
+
+**Concise and Readable Code :** By eliminating the need for boilerplate code to close resources in finally blocks, try-with-resources leads to cleaner and more readable code. Developers can focus on the core logic of the program without getting distracted by resource management concerns.
+
+**Improved Exception Handling :** Any exceptions thrown during the execution of the try block, as well as any exceptions thrown during resource closing, are properly handled. This simplifies error handling and makes code more robust.
From edaa9913d6a0c1e54156993ab64e06ff3c102a96 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 22 Mar 2024 19:52:45 +0530
Subject: [PATCH 148/236] Update README.md
From c5f4666c64845f9e8b979742c6d7aa5f32238393 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 1 Apr 2024 15:04:07 +0530
Subject: [PATCH 149/236] Update README.md
---
section_14/README.md | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index 5d0494d..9f64f95 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -189,6 +189,25 @@ public class TryWithResourcesDemo {
**Concise and Readable Code :** By eliminating the need for boilerplate code to close resources in finally blocks, try-with-resources leads to cleaner and more readable code. Developers can focus on the core logic of the program without getting distracted by resource management concerns.
**Improved Exception Handling :** Any exceptions thrown during the execution of the try block, as well as any exceptions thrown during resource closing, are properly handled. This simplifies error handling and makes code more robust.
+## Try-with-Resources
+Try-with-resources is a feature introduced in Java 7 that simplifies resource management by automatically closing resources at the end of their usage. This feature can significantly reduce the boilerplate code required for managing resources such as files, database connections, and network connections.
+### How to Use Try-with-Resources
+
+Using try-with-resources is straightforward. You declare the resources within the parentheses of the try statement. The resources must implement the `AutoCloseable` interface. Java automatically closes the resources at the end of the try block, whether an exception is thrown or not.
+
+Here's the basic syntax:
+
+```java
+try (ResourceType1 resource1 = new ResourceType1();
+ ResourceType2 resource2 = new ResourceType2();
+ // Add more resources as needed
+) {
+ // Code that uses the resources
+} catch (Exception e) {
+ // Exception handling
+}
+```
+Replace `ResourceType1`, `ResourceType2` etc., with the actual types of resources you want to manage.
From 451aa9125408f05dc3f9c3f612b7ab2047cf98da Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 1 Apr 2024 15:26:34 +0530
Subject: [PATCH 150/236] Update README.md
---
section_14/README.md | 32 ++++++++++++++++++++++++++++++++
1 file changed, 32 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index 9f64f95..acc322d 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -208,6 +208,38 @@ try (ResourceType1 resource1 = new ResourceType1();
}
```
Replace `ResourceType1`, `ResourceType2` etc., with the actual types of resources you want to manage.
+#### Example
+```java
+package com.eazybytes.exception;
+
+import java.util.Scanner;
+
+public class TryWithResourcesDemo {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ System.out.println("Enter a number....");
+ int number = scanner.nextInt();
+ System.out.println(number);
+ } catch(Exception ex) {
+ System.out.println("Please provide input in numerical format only and try again...");
+ }
+ }
+
+}
+```
+### Benefits of Try-with-Resources
+- Automatic Resource Management: Resources are automatically closed at the end of the try block, reducing the risk of resource leaks.
+- Concise and Readable: Try-with-resources reduces boilerplate code, making your code cleaner and easier to understand.
+- Exception Handling: Exceptions that occur during resource management are properly handled without the need for explicit finally blocks.
+### Conclusion
+Try-with-resources is a powerful feature in Java for managing resources efficiently and safely. By using this feature, you can simplify your code and improve its robustness by ensuring that resources are properly closed after use.
+## throws Keyword
+The `throws` keyword in Java is used in method declarations to indicate that the method may throw one or more specific exceptions during its execution. When a method uses `throws`, it essentially delegates the responsibility of handling the exception to the caller of the method.
+### Syntax
+```java
+return_type method_name(parameters) throws exception_type1, exception_type2, ...
+```
From 2c0db21eca359a059791bbc46be357a2d5defb5f Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 1 Apr 2024 15:27:29 +0530
Subject: [PATCH 151/236] Update README.md
---
section_14/README.md | 15 +++++++++++++++
1 file changed, 15 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index acc322d..9af84cb 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -240,6 +240,21 @@ The `throws` keyword in Java is used in method declarations to indicate that the
```java
return_type method_name(parameters) throws exception_type1, exception_type2, ...
```
+#### Example
+```java
+package com.eazybytes.exception;
+
+public class Division {
+
+ public double divide (String num1, String num2) throws
+ NumberFormatException, ArithmeticException {
+ int n1 = Integer.parseInt(num1);
+ int n2 = Integer.parseInt(num2);
+ return n1/n2;
+ }
+
+}
+
From cec3a583f8b2cdac85a770a7831eef816bf5ad8a Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 1 Apr 2024 15:33:47 +0530
Subject: [PATCH 152/236] Update README.md
---
section_14/README.md | 32 ++++++++++++++++++++++++++++++++
1 file changed, 32 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index 9af84cb..09482a8 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -255,6 +255,38 @@ public class Division {
}
+package com.eazybytes.exception;
+
+public class ThrowsDemo {
+
+ public static void main(String[] args) {
+ Division division = new Division();
+ try{
+ double ouput = division.divide("4", "2");
+ System.out.println(ouput);
+ } catch (NumberFormatException | ArithmeticException ex) {
+ System.out.println("Invalid data provided. Please provide valid numbers and try again..");
+ }
+ }
+
+}
+### Key Points
+- The `throws` keyword is used in method declarations.
+- It specifies the exceptions that a method might throw during its execution.
+- The caller of the method must handle the declared exceptions using try-catch blocks or propagate them using the throws clause.
+## throw Keyword
+In Java, the `throw` keyword is used to explicitly throw an exception. This means that when a certain condition occurs in your program, you can use the `throw` keyword to create and throw an exception manually.
+### Syntax
+The syntax for using the `throw` keyword is as follows:
+```java
+throw throwableObject;
+```
+Here, `throwableObject` is the exception object that you want to throw.
+
+
+
+
+
From 8e3066adbbc71aafabb35bc4e20df5ac5ea9554c Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 1 Apr 2024 16:07:30 +0530
Subject: [PATCH 153/236] Update README.md
---
section_14/README.md | 117 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 117 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index 09482a8..dbcc6d7 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -270,6 +270,7 @@ public class ThrowsDemo {
}
}
+```
### Key Points
- The `throws` keyword is used in method declarations.
- It specifies the exceptions that a method might throw during its execution.
@@ -282,6 +283,122 @@ The syntax for using the `throw` keyword is as follows:
throw throwableObject;
```
Here, `throwableObject` is the exception object that you want to throw.
+#### Example
+```java
+package com.eazybytes.exception;
+
+import java.util.Scanner;
+
+public class ThrowDemo {
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ System.out.println("Please enter the numerator value");
+ String num1 = scanner.next();
+ System.out.println("Please enter the denominator value");
+ String num2 = scanner.next();
+ Division division = new Division();
+ if(num2.equals("0")) {
+ throw new ArithmeticException("Division by zero");
+ }
+ double output = division.divide(num1, num2);
+ System.out.println(output);
+ }
+
+}
+
+package com.eazybytes.exception;
+
+public class Division {
+
+ public double divide (String num1, String num2) throws
+ NumberFormatException, ArithmeticException {
+ int n1 = Integer.parseInt(num1);
+ int n2 = Integer.parseInt(num2);
+ return n1/n2;
+ }
+
+}
+```
+### When to Use
+- Use the `throw` keyword when you encounter an exceptional condition in your program that you want to handle.
+- It is commonly used within methods or constructors to signal that something unexpected has occurred.
+### Conclusion
+The `throw` keyword in Java provides a way to manually throw exceptions in your code, allowing you to handle exceptional conditions gracefully. It is an essential part of Java's exception handling mechanism.
+## Exception Propagation
+Exception propagation is a mechanism in Java where an exception that is not caught in a method is automatically propagated to the calling method. This process continues until the exception is caught or until it reaches the top of the call stack.
+### How Exception Propagation Works
+1. **Exception Occurrence**: An exception occurs within a method.
+2. **Uncaught Exception**: If the exception is not caught within the method, it is automatically propagated to the calling method.
+3. **Propagation Continues**: The process of propagating the exception continues until it is either caught or it reaches the top of the call stack.
+4. **Handling the Exception**: If the exception is caught at any point during propagation, it can be handled using try-catch blocks or it can be propagated further up the call stack.
+#### Example
+
+```java
+public class ExceptionPropagationExample {
+
+ public static void main(String[] args) {
+ try {
+ method1();
+ } catch (Exception e) {
+ System.out.println("Exception caught in main method: " + e);
+ }
+ }
+
+ public static void method1() {
+ method2();
+ }
+
+ public static void method2() {
+ method3();
+ }
+
+ public static void method3() {
+ // Simulating an exception
+ int result = 10 / 0;
+ }
+}
+```
+In this example, an exception occurs in `method3()` due to division by zero. Since the exception is not caught within `method3()`, it is propagated to `method2()`, then to `method1()`, and finally caught in the `main` method.
+### Best Practices
+- Catch Exceptions at the Appropriate Level: Catch exceptions at a level where you can handle them effectively.
+- Use try-catch Blocks Judiciously: Use try-catch blocks only where necessary to maintain code readability and to handle exceptions appropriately.
+- Log Exceptions: Always log exceptions or at least handle them gracefully to provide useful information for debugging and troubleshooting.
+### Conclusion
+Understanding exception propagation is essential for writing robust and reliable Java applications. By knowing how exceptions propagate through method calls, you can effectively handle errors and ensure the stability of your code.
+## Nested Try Block
+In Java, exception handling is accomplished using try-catch blocks. A nested try block is a try block inside another try block. This allows for more granular handling of exceptions and enables developers to handle exceptions at different levels of code execution.
+### Usage
+Nested try blocks are particularly useful when dealing with complex code structures where different parts of the code may throw different types of exceptions. By nesting try blocks, you can handle exceptions more precisely and maintain the flow of your program.
+### Example
+```java
+public class NestedTryExample {
+ public static void main(String[] args) {
+ try {
+ int[] numbers = {1, 2, 3};
+ int result = numbers[5]; // This line will throw an ArrayIndexOutOfBoundsException
+ try {
+ int quotient = 10 / 0; // This line will throw an ArithmeticException
+ } catch (ArithmeticException ex) {
+ System.out.println("ArithmeticException caught: " + ex.getMessage());
+ }
+ } catch (ArrayIndexOutOfBoundsException ex) {
+ System.out.println("ArrayIndexOutOfBoundsException caught: " + ex.getMessage());
+ }
+ }
+}
+```
+In this example, we have an outer try block that contains an array access statement, which may throw an `ArrayIndexOutOfBoundsException`. Inside the outer try block, we have a nested try block that contains a division operation, which may throw an `ArithmeticException`. By using nested try blocks, we can handle these exceptions separately and provide specific error messages or take appropriate actions based on the type of exception thrown.
+### Conclusion
+Nested try blocks are a powerful feature of Java's exception handling mechanism that allows developers to handle exceptions at different levels of code execution. When used judiciously, nested try blocks can make your code more robust and maintainable by providing fine-grained control over exception handling.
+## Custom Checked Exceptions
+In Java, exceptions play a crucial role in handling errors and abnormal conditions that may occur during program execution. While Java provides a wide range of built-in exceptions, sometimes it's necessary to create custom exceptions to handle specific scenarios unique to your application.
+Custom exceptions allow you to define your own exception types tailored to the requirements of your application domain. Checked exceptions, in particular, are those that are checked at compile-time, ensuring that they are either caught or declared to be thrown by the method in which they may occur.
+
+
+
+
+
From c368619fa4f046cce009090b45c6afb01ce119dc Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 1 Apr 2024 16:08:24 +0530
Subject: [PATCH 154/236] Update README.md
---
section_14/README.md | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index dbcc6d7..dd03cb5 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -394,6 +394,28 @@ Nested try blocks are a powerful feature of Java's exception handling mechanism
## Custom Checked Exceptions
In Java, exceptions play a crucial role in handling errors and abnormal conditions that may occur during program execution. While Java provides a wide range of built-in exceptions, sometimes it's necessary to create custom exceptions to handle specific scenarios unique to your application.
Custom exceptions allow you to define your own exception types tailored to the requirements of your application domain. Checked exceptions, in particular, are those that are checked at compile-time, ensuring that they are either caught or declared to be thrown by the method in which they may occur.
+#### Example
+```java
+package com.eazybytes.exception;
+
+import com.eazybytes.exception.custom.InvalidAgeException;
+
+import java.util.Scanner;
+
+public class AcceptAgeDetails {
+
+ public static void main(String[] args) throws InvalidAgeException {
+ Scanner scanner = new Scanner(System.in);
+ System.out.println("Enter your Age:");
+ int age = scanner.nextInt();
+ if(age<0 || age>100) {
+ throw new InvalidAgeException("Invalid age details entered. Please enter a age between 0-100");
+ }
+ System.out.println("Your age is : "+age);
+ }
+
+}
+
From 23f91c12c2458f6f85e24302c4aee8cfcc56984d Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 1 Apr 2024 16:17:34 +0530
Subject: [PATCH 155/236] Update README.md
---
section_14/README.md | 70 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 70 insertions(+)
diff --git a/section_14/README.md b/section_14/README.md
index dd03cb5..8547956 100644
--- a/section_14/README.md
+++ b/section_14/README.md
@@ -416,6 +416,76 @@ public class AcceptAgeDetails {
}
+package com.eazybytes.exception.custom;
+
+public class InvalidAgeException extends Exception {
+
+ public InvalidAgeException() {
+ super();
+ }
+
+ public InvalidAgeException(String message) {
+ super(message);
+ }
+
+}
+```
+## Understanding final, finally, and finalize
+### final
+The `final` keyword in Java is used to declare constants, prevent method overriding, and restrict subclassing. Here's a brief overview of its usage:
+ - **Constant Declaration:** When a variable is declared with `final`, its value cannot be changed once initialized.
+ ```java
+ final int MAX_VALUE = 100;
+```
+- **Method Declaration :** When a method is declared as final, it cannot be overridden by subclasses.
+
+```java
+public final void display() {
+ // Method implementation
+}
+```
+- **Class Declaration :** When a class is declared as final, it cannot be subclassed.
+
+```java
+public final class MyClass {
+ // Class implementation
+}
+```
+### finally
+The `finally` block in Java is used in exception handling to execute code that must be run regardless of whether an exception is thrown or not. It is usually placed after the `try` block and/or `catch` block. Here's how it works:
+```java
+try {
+ // Code that may throw an exception
+} catch (Exception e) {
+ // Exception handling
+} finally {
+ // Code that always executes, irrespective of whether an exception occurred or not
+}
+```
+The `finally` block is often used for releasing resources like closing files or database connections, ensuring they are properly cleaned up.
+### finalize
+The `finalize()` method in Java is called by the garbage collector before an object is reclaimed. It's used for performing cleanup operations on an object before it is garbage collected. However, it's important to note that `finalize()` method has been deprecated in Java 9 and may be removed in future versions. It's generally not recommended to rely on `finalize()` for resource cleanup. Instead, developers should use explicit resource management techniques such as try-with-resources or implement AutoCloseable interface for resource cleanup.
+#### Example
+```java
+public class MyClass {
+ // Class implementation
+
+ @Override
+ protected void finalize() throws Throwable {
+ try {
+ // Cleanup operations
+ } finally {
+ super.finalize();
+ }
+ }
+}
+```
+### Conclusion
+Understanding the distinctions between `final`, `finally`, and `finalize` is crucial for writing robust and maintainable Java code. Proper usage of these constructs can lead to better resource management, exception handling, and class design.
+
+
+
+
From 1b651ddab0b4106c1f7ac1ba2517fba33cb130e7 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 1 Apr 2024 18:28:13 +0530
Subject: [PATCH 156/236] Create README.md
---
section_15/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_15/README.md
diff --git a/section_15/README.md b/section_15/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_15/README.md
@@ -0,0 +1 @@
+
From 130a06f5ff67219225a73640825b40be95bf221d Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 1 Apr 2024 18:38:22 +0530
Subject: [PATCH 157/236] Update README.md
---
section_15/README.md | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/section_15/README.md b/section_15/README.md
index 8b13789..d0859a2 100644
--- a/section_15/README.md
+++ b/section_15/README.md
@@ -1 +1,11 @@
+# Method in Object Class
+In Java, an ` Object` class refers to any class that extends the fundamental base class, Object. Every class in Java implicitly or explicitly extends Object, which is the root of the class hierarchy.
+## Object.getClass()
+The `getClass()` method in Java is a part of the Object class, which is the root of the Java class hierarchy. It returns the runtime class of an object. In other words, it returns an instance of the Class class representing the runtime class of the object.
+### Syntax
+```java
+public final Class> getClass()
+```
+### Return Value
+- Returns the runtime class of this object.
From 6c50e4b51df2f051a3cd499d0698607f665f93cb Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 1 Apr 2024 19:24:54 +0530
Subject: [PATCH 158/236] Update README.md
---
section_15/README.md | 163 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 163 insertions(+)
diff --git a/section_15/README.md b/section_15/README.md
index d0859a2..7c8b7fc 100644
--- a/section_15/README.md
+++ b/section_15/README.md
@@ -8,4 +8,167 @@ public final Class> getClass()
```
### Return Value
- Returns the runtime class of this object.
+#### Example
+```java
+package com.eazybytes.object.demo;
+
+public class GetClassDemo {
+
+ public static void main(String[] args) {
+ Person person = new Person();
+ Class prsnClass = person.getClass();
+ System.out.println(prsnClass.getName());
+ System.out.println(prsnClass.getSimpleName());
+ System.out.println(prsnClass.getPackageName());
+ }
+
+}
+```
+### Usage
+- Use `getClass()` when you need to determine the runtime class of an object at runtime.
+- It's commonly used in scenarios where the exact type of an object needs to be identified dynamically.
+### Notes
+- The `getClass()` method is a final method and cannot be overridden.
+- If the object is null, a `NullPointerException` will be thrown when getClass() is invoked on it.
+### The getClass() method is a final method and cannot be overridden.
+If the object is null, a NullPointerException will be thrown when getClass() is invoked on it.
+## Object.hashCode()
+In Java, `Object.hashCode()` is a method provided by the `Object` class, which is the root of the class hierarchy. This method returns a hash code value for the object. It is crucial for various algorithms, such as hashing-based collections like `HashMap` and `HashSet`.
+### Syntax
+```java
+public int hashCode()
+```
+### Description
+- Returns a hash code value for the object. This value is typically used to support hash-based collections.
+- The general contract of hashCode method is:
+ - Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same
+ - integer, provided no information used in equals comparisons on the object is modified.
+ - If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
+ - It's not required that if two objects are unequal according to the equals(Object) method, then calling the hashCode method on each of the two objects must
+ - produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
+#### Example
+```java
+public class MyClass {
+ private String name;
+ private int id;
+
+ public MyClass(String name, int id) {
+ this.name = name;
+ this.id = id;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ result = 31 * result + name.hashCode();
+ result = 31 * result + id;
+ return result;
+ }
+
+ // other methods...
+}
+```
+In this example, the `hashCode` method is overridden to generate a hash code based on the name and `id` fields of the object.
+### Best Practices
+- Consistency with `equals()` : If you override the `equals()` method, make sure to also override the `hashCode()` method and ensure that they are consistent with each other.
+- Efficiency: While it's not strictly required that hash codes be unique, producing distinct hash codes for distinct objects can improve the performance of hash-based collections.
+- Stable Hash Codes: Ensure that the hash code of an object remains the same over its lifetime, as long as the information used in `equals()` comparisons remains constant.
+- Use in Collections: Be mindful when using objects with mutable state as keys in hash-based collections, as changing the state of the object after it has been used as a key can lead to unexpected behavior.
+## Object.equals()
+`Object.equals()` is a method in Java that is used to compare the equality of two objects. It is inherited by all classes in Java since all classes ultimately extend the `Object` class.
+### Syntax
+```java
+public boolean equals(Object obj)
+```
+### Parameters
+- `obj` : The object to be compared for equality with this object.
+### Return Value
+- `true` if the specified object is equal to this object.
+- `false` otherwise.
+### Usage
+The `equals()` method is typically overridden in classes that need custom equality comparison. By default, it compares object references, i.e., whether the two object references point to the same memory location.
+```java
+public class MyClass {
+ private int value;
+
+ // Constructor, getters, setters...
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null || getClass() != obj.getClass())
+ return false;
+ MyClass myObj = (MyClass) obj;
+ return value == myObj.value;
+ }
+
+ // Other methods...
+}
+```
+In the above example, the `equals()` method is overridden to compare the `value` attribute of two `MyClass` objects for equality.
+### Best Practices
+- Override `equals()` when necessary : If your class needs a custom equality comparison, override the `equals()` method to provide it.
+- Follow the contract: Ensure that your implementation of `equals()` satisfies the contract defined in the Java documentation.
+- Override hashCode(): If you override `equals()`, it's recommended to also override the `hashCode()` method to maintain consistency.
+```java
+public class Main {
+ public static void main(String[] args) {
+ MyClass obj1 = new MyClass(10);
+ MyClass obj2 = new MyClass(10);
+
+ System.out.println(obj1.equals(obj2)); // Output: true
+ }
+}
+```
+## Object.toString()
+The `toString()` method in Java is a method provided by the `Object` class, which is the root of the Java class hierarchy. It returns a string representation of the object. The default implementation provided by the `Object` class returns a string consisting of the class name followed by the "@" character and the object's hashcode in hexadecimal format.
+### Syntax
+```java
+public String toString()
+```
+### Return Value
+- A string representation of the object.
+#### Example
+```java
+public class MyClass {
+ private int id;
+ private String name;
+
+ public MyClass(int id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return "MyClass{" +
+ "id=" + id +
+ ", name='" + name + '\'' +
+ '}';
+ }
+
+ public static void main(String[] args) {
+ MyClass obj = new MyClass(1, "Example");
+ System.out.println(obj.toString());
+ }
+}
+```
+```java
+MyClass{id=1, name='Example'}
+```
+### Usage
+- Override the `toString()` method in your custom classes to provide a meaningful string representation of the object.
+- Useful for debugging purposes to print object information.
+- Used in logging or displaying object information to users.
+### Note
+If you don't override `toString()` in your custom class, you'll get the default implementation provided by the `Object` class, which may not provide meaningful information about the object.
+
+
+
+
+
+
+
+
From 3b80ff1083085c1b3464dd9b7796b11ac25ce45f Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 2 Apr 2024 16:29:59 +0530
Subject: [PATCH 159/236] Update README.md
---
section_15/README.md | 36 +++++++++++++++++++++++++++++++++---
1 file changed, 33 insertions(+), 3 deletions(-)
diff --git a/section_15/README.md b/section_15/README.md
index 7c8b7fc..96a4f02 100644
--- a/section_15/README.md
+++ b/section_15/README.md
@@ -129,7 +129,7 @@ public String toString()
```
### Return Value
- A string representation of the object.
-#### Example
+#### Example π‘
```java
public class MyClass {
private int id;
@@ -157,12 +157,42 @@ public class MyClass {
```java
MyClass{id=1, name='Example'}
```
-### Usage
+### Usage π
- Override the `toString()` method in your custom classes to provide a meaningful string representation of the object.
- Useful for debugging purposes to print object information.
- Used in logging or displaying object information to users.
-### Note
+### Notes π π
If you don't override `toString()` in your custom class, you'll get the default implementation provided by the `Object` class, which may not provide meaningful information about the object.
+## Object.finalize()
+`Object.finalize()` is a method in Java that is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. It's provided as a means for an object to perform cleanup operations before it is garbage collected.
+However, it's important to note that `finalize()` is generally considered unreliable and should not be relied upon for critical resource cleanup. This is because there's no guarantee as to when or if the finalize method will be called.
+### Usage
+Here's a basic usage example:
+
+```java
+public class MyClass {
+ // Override finalize method
+ @Override
+ protected void finalize() throws Throwable {
+ try {
+ // Cleanup operations
+ } finally {
+ // Call superclass finalize method
+ super.finalize();
+ }
+ }
+}
+```
+### Considerations
+- **Unreliability :** As mentioned earlier, the finalize() method is not guaranteed to be called promptly or at all, so it should not be relied upon for critical cleanup tasks.
+- **Performance :** Invoking finalize() can have performance implications due to its impact on garbage collection. Objects with finalizers may take longer to be collected than those without.
+- **Alternative Approaches :** For resource cleanup, it's generally better to use other mechanisms such as try-with-resources statements (for managing resources that implement AutoCloseable) or explicit close() methods.
+## Object.clone()
+- In Java, `Object.clone()` is a method used to create a shallow copy of an object. This method is declared in the Object class and is protected, meaning it can be accessed only by the classes within the same package or subclasses.
+- A shallow copy of an object is a new object that is created, but it shares the same fields (references) with the original object. That means if the original object contains references to other objects, the copied object will also refer to the same objects.
+
+
+
From c26c0a9300ef4cc544e68a9a94f96bb87d219559 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 2 Apr 2024 19:27:15 +0530
Subject: [PATCH 160/236] Update README.md
---
section_15/README.md | 192 ++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 190 insertions(+), 2 deletions(-)
diff --git a/section_15/README.md b/section_15/README.md
index 96a4f02..791fb5e 100644
--- a/section_15/README.md
+++ b/section_15/README.md
@@ -161,12 +161,12 @@ MyClass{id=1, name='Example'}
- Override the `toString()` method in your custom classes to provide a meaningful string representation of the object.
- Useful for debugging purposes to print object information.
- Used in logging or displaying object information to users.
-### Notes π π
+### Notes π
If you don't override `toString()` in your custom class, you'll get the default implementation provided by the `Object` class, which may not provide meaningful information about the object.
## Object.finalize()
`Object.finalize()` is a method in Java that is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. It's provided as a means for an object to perform cleanup operations before it is garbage collected.
However, it's important to note that `finalize()` is generally considered unreliable and should not be relied upon for critical resource cleanup. This is because there's no guarantee as to when or if the finalize method will be called.
-### Usage
+### Usage π
Here's a basic usage example:
```java
@@ -190,6 +190,194 @@ public class MyClass {
## Object.clone()
- In Java, `Object.clone()` is a method used to create a shallow copy of an object. This method is declared in the Object class and is protected, meaning it can be accessed only by the classes within the same package or subclasses.
- A shallow copy of an object is a new object that is created, but it shares the same fields (references) with the original object. That means if the original object contains references to other objects, the copied object will also refer to the same objects.
+### Usage π
+To use `Object.clone()` effectively, follow these steps:
+1. **Implement the Cloneable Interface :** The Cloneable interface must be implemented by the class whose objects are to be cloned. This is a marker interface, meaning it does not contain any methods.
+```java
+public class MyClass implements Cloneable {
+ // Class definition
+}
+```
+2. **Override the clone() Method :** Override the `clone()` method in the class to specify how the cloning operation should be performed.
+```java
+@Override
+public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+}
+```
+It's important to throw CloneNotSupportedException if cloning is not supported by the class.
+3. **Handle Exceptions :** Ensure that `CloneNotSupportedException` is properly handled either by catching it or declaring it in the method signature.
+
+4. **Use clone() Method :** Call the `clone()` method on the object you want to clone.
+```java
+MyClass original = new MyClass();
+try {
+ MyClass copy = (MyClass) original.clone();
+} catch (CloneNotSupportedException e) {
+ e.printStackTrace();
+}
+```
+### Important Points
+- `Object.clone()` performs a shallow copy. If the object contains mutable fields, changes made in the cloned object will affect the original object and vice versa.
+- Deep cloning can be achieved by overriding the `clone()` method to create a new object and copying all mutable fields recursively.
+- `clone()` method returns Object, so explicit casting is required.
+- It's recommended to use `clone()` judiciously, as it can lead to unexpected behavior, especially when dealing with mutable objects.
+#### Example
+```java
+public class MyClass implements Cloneable {
+ private int id;
+ private String name;
+
+ public MyClass(int id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ @Override
+ public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+
+ public static void main(String[] args) {
+ MyClass original = new MyClass(1, "Original");
+ try {
+ MyClass copy = (MyClass) original.clone();
+ System.out.println("Original: " + original.getId() + ", " + original.getName());
+ System.out.println("Copy: " + copy.getId() + ", " + copy.getName());
+ } catch (CloneNotSupportedException e) {
+ e.printStackTrace();
+ }
+ }
+}
+```
+## Shallow Cloning and Deep Cloning
+In Java, cloning allows you to create a copy of an object. There are two types of cloning: shallow cloning and deep cloning.
+### Shallow Cloning
+Shallow cloning creates a new object and copies all of the fields of the original object to the new object. However, if the field of the original object is a reference to another object, only the reference is copied, not the actual object itself. This means that changes made to the original object's referenced objects will also be reflected in the cloned object.
+### Implementing Shallow Cloning
+To implement shallow cloning in Java, you need to override the `clone()` method of the `Object` class and use the `super.clone()` method to create a shallow copy of the object.
+```java
+@Override
+public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+}
+```
+### Deep Cloning
+Deep cloning creates a new object and recursively copies all of the fields of the original object as well as all of its referenced objects. This ensures that changes made to the original object or its referenced objects do not affect the cloned object.
+### Implementing Deep Cloning
+Implementing deep cloning in Java requires a bit more effort compared to shallow cloning. One common approach is to serialize the original object and then deserialize it to create a deep copy.
+```java
+public static T deepClone(T object) throws IOException, ClassNotFoundException {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(bos);
+ oos.writeObject(object);
+ oos.flush();
+ oos.close();
+ bos.close();
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ ObjectInputStream ois = new ObjectInputStream(bis);
+ T copy = (T) ois.readObject();
+ ois.close();
+ bis.close();
+
+ return copy;
+}
+```
+### Conclusion π
+- Understanding the differences between shallow cloning and deep cloning is crucial when working with objects in Java. Shallow cloning creates a new object with copies of the original object's fields, while deep cloning creates a new object with copies of both the original object's fields and its referenced objects.
+- For simple objects, shallow cloning may be sufficient. However, for complex objects with nested references, deep cloning is often necessary to ensure that changes made to the original object do not affect the cloned object.
+## Mutable vs Immutable Objects
+In Java, objects can be classified into two categories based on whether they can be modified after creation: mutable and immutable. Understanding the difference between them is crucial for writing efficient and bug-free code.
+### Mutable Objects
+Mutable objects are those whose state (data) can be modified after creation. This means that the values of their fields can change over time.
+#### Example: StringBuilder π‘
+```java
+```java
+StringBuilder mutableStr = new StringBuilder("Hello");
+mutableStr.append(", World!");
+System.out.println(mutableStr); // Output: Hello, World!
+```
+### Immutable Objects
+Immutable objects, on the other hand, are objects whose state cannot be modified after creation. Once instantiated, the values of their fields remain constant throughout their lifetime.
+#### Example: String π‘
+```java
+String immutableStr = "Hello";
+immutableStr.concat(", World!");
+System.out.println(immutableStr); // Output: Hello
+```
+In the above example, the String object is immutable. Even though we call the `concat()` method, it doesn't modify the original string. Instead, it returns a new string with the concatenated value.
+### Guidelines for Using Immutable Objects
+- Immutable objects are inherently thread-safe because their state cannot change, making them ideal for concurrent programming.
+- When designing classes, consider making them immutable if their state should not change once initialized.
+- Immutable objects are suitable for use as keys in hash maps and for caching.
+### Benefits of Immutability
+- Simplified concurrent programming: Immutable objects can be shared across threads without the need for synchronization.
+- Improved performance: Immutable objects can be cached and reused, leading to better memory management and potentially faster execution.
+- Enhanced reliability: Since immutable objects cannot be changed, they are less prone to unexpected side effects or bugs caused by unintended modifications.
+### When to Use Mutable Objects
+While immutable objects offer several advantages, mutable objects are still necessary in many scenarios, especially when dealing with data that needs to be modified frequently or when performance is a concern.
+### Conclusion π
+Understanding the distinction between mutable and immutable objects is essential for writing robust and efficient Java code. By leveraging immutable objects where appropriate, developers can improve code reliability, concurrency, and performance.
+## Record Class
+The `Record` class is a simple Java class designed to represent a record or entry in a data system. It provides a basic structure for storing information about a particular entity, such as a person, product, or event.
+### Features
+**Data Storage :** Stores information about a single entity.
+**Immutability :** Once initialized, the data stored in a Record instance cannot be modified.
+**Readability :** Provides methods to access individual fields of the record.
+**Easy Integration :** Can be easily integrated into larger Java applications.
+### Usage
+To use the Record class in your Java project, follow these steps:
+- **Download the `Record.java` file :** Download the Record.java file from this repository and add it to your project's source folder.
+
+- **Create a Record Instance :** Create a new instance of the Record class by providing values for its fields.
+```java
+Record record = new Record("John Doe", 30, "john.doe@example.com");
+```
+- **Access Record Fields :** Access individual fields of the record using getter methods.
+```java
+String name = record.getName();
+int age = record.getAge();
+String email = record.getEmail();
+```
+- **Immutable Nature :** Note that once a Record instance is created, its fields cannot be modified. This ensures data integrity.
+#### Example
+```java
+public class Main {
+ public static void main(String[] args) {
+ // Create a new Record instance
+ Record record = new Record("John Doe", 30, "john.doe@example.com");
+
+ // Access record fields
+ String name = record.getName();
+ int age = record.getAge();
+ String email = record.getEmail();
+
+ // Print record information
+ System.out.println("Name: " + name);
+ System.out.println("Age: " + age);
+ System.out.println("Email: " + email);
+ }
+}
+```
+## var Feature
+The `var` keyword in Java allows for type inference, reducing verbosity in variable declarations. Introduced in Java 10 as part of Project Amber, `var` enhances code readability and maintainability by emphasizing the intent over implementation details.
+### Benefits
+- **Conciseness :** Eliminates repetitive type declarations, resulting in cleaner code.
+- **Readability :** Focuses on the variable's purpose rather than its specific type.
+- **Flexibility :** Supports various contexts, including local variables, enhanced for loops, and try-with-resources statements.
+### Considerations
+- **Maintainability :** While var enhances readability, overuse may obfuscate code, especially in complex scenarios.
+- **Clarity :** Prioritize clarity over brevity; use var judiciously where type inference improves code comprehension.
+- **Compatibility :** Compatible with Java 10 and later versions; ensure compatibility with target runtime environments.
+### Example
+```java
+
+var list = new ArrayList();
+list.add("Java");
+list.add("is");
+list.add("awesome");
+```
From 82c20b6bfd39b903979ebfa0c335bf2659270715 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 2 Apr 2024 19:28:27 +0530
Subject: [PATCH 161/236] Update README.md
---
section_15/README.md | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/section_15/README.md b/section_15/README.md
index 791fb5e..4d3d3b9 100644
--- a/section_15/README.md
+++ b/section_15/README.md
@@ -1,4 +1,4 @@
-# Method in Object Class
+# Methods in Object Class
In Java, an ` Object` class refers to any class that extends the fundamental base class, Object. Every class in Java implicitly or explicitly extends Object, which is the root of the class hierarchy.
## Object.getClass()
The `getClass()` method in Java is a part of the Object class, which is the root of the Java class hierarchy. It returns the runtime class of an object. In other words, it returns an instance of the Class class representing the runtime class of the object.
@@ -222,7 +222,7 @@ try {
- Deep cloning can be achieved by overriding the `clone()` method to create a new object and copying all mutable fields recursively.
- `clone()` method returns Object, so explicit casting is required.
- It's recommended to use `clone()` judiciously, as it can lead to unexpected behavior, especially when dealing with mutable objects.
-#### Example
+#### Example π‘
```java
public class MyClass implements Cloneable {
private int id;
@@ -341,7 +341,7 @@ int age = record.getAge();
String email = record.getEmail();
```
- **Immutable Nature :** Note that once a Record instance is created, its fields cannot be modified. This ensures data integrity.
-#### Example
+#### Example π‘
```java
public class Main {
public static void main(String[] args) {
@@ -370,7 +370,7 @@ The `var` keyword in Java allows for type inference, reducing verbosity in varia
- **Maintainability :** While var enhances readability, overuse may obfuscate code, especially in complex scenarios.
- **Clarity :** Prioritize clarity over brevity; use var judiciously where type inference improves code comprehension.
- **Compatibility :** Compatible with Java 10 and later versions; ensure compatibility with target runtime environments.
-### Example
+### Example π‘
```java
var list = new ArrayList();
From cbb03e3a748ba61bded06f9d0f25fd232fb8a069 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 2 Apr 2024 20:31:28 +0530
Subject: [PATCH 162/236] Create README.md
---
section_16/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_16/README.md
diff --git a/section_16/README.md b/section_16/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_16/README.md
@@ -0,0 +1 @@
+
From e01a4ebb2eb92bd9372dd49e706b2d5da91d5f8a Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 2 Apr 2024 21:17:39 +0530
Subject: [PATCH 163/236] Update README.md
---
section_16/README.md | 189 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 189 insertions(+)
diff --git a/section_16/README.md b/section_16/README.md
index 8b13789..8cee698 100644
--- a/section_16/README.md
+++ b/section_16/README.md
@@ -1 +1,190 @@
+# Collections And Wrapper Classes
+## Collections
+In Java, collections are objects that group multiple elements into a single unit. They provide a way to work with groups of objects, such as lists, sets, maps, queues, etc., and offer various operations for manipulation, traversal, and searching of the elements they contain. Collections framework in Java is part of the Java Collections Framework (JCF), which provides a set of interfaces and classes to represent collections and manipulate them efficiently.
+Here are some common types of collections in Java:
+- **List :** A list is an ordered collection that allows duplicate elements. Common implementations include ArrayList, LinkedList, and Vector.
+
+- **Set :** A set is a collection that does not allow duplicate elements. Common implementations include HashSet, TreeSet, and LinkedHashSet.
+
+- **Map :** A map is a collection that maps keys to values. Each key must be unique, but the values can be duplicated. Common implementations include HashMap, TreeMap, and LinkedHashMap.
+
+- **Queue :** A queue is a collection used to hold elements before processing. Common implementations include LinkedList (which can act as both a list and a queue) and PriorityQueue.
+
+- **Deque :** A deque (double-ended queue) is a collection that supports insertion and deletion of elements at both ends. Common implementations include ArrayDeque and LinkedList.
+
+Java's collections framework provides several benefits, including type safety, performance, and interoperability between different collections and algorithms. It offers a rich set of APIs for common operations like adding, removing, searching, and iterating over elements, making it easier to work with collections in Java applications.
+## Wrapper Classes
+In Java, wrapper classes are classes that encapsulate primitive data types into objects. While primitive data types like int, float, double, etc., are basic data types provided by the language, they are not objects and don't have methods associated with them. Wrapper classes provide a way to treat primitive data types as objects and enable additional functionalities like conversion, manipulation, and passing them as arguments to methods that require objects.
+
+Here are the wrapper classes for primitive data types in Java:
+**Byte :** `java.lang.Byte`
+**Short :** `java.lang.Short`
+Integer :** `java.lang.Integer`
+**Long :** `java.lang.Long`
+**Float :** `java.lang.Float`
+**Double :** `java.lang.Double`
+**Character :** `java.lang.Character`
+**Boolean :** `java.lang.Boolean`
+- Each wrapper class provides methods to perform operations on the corresponding primitive data type. For example, you can convert a string representation of a number into an Integer object using methods like `parseInt()` in the Integer class. Similarly, you can convert an Integer object to a primitive int using methods like `intValue()`.
+- Wrapper classes are commonly used in scenarios where primitive data types need to be treated as objects, such as collections, generics, and reflection. Additionally, they are useful when dealing with APIs that require objects rather than primitive data types. However, it's important to be mindful of the potential performance overhead associated with using wrapper classes, especially in performance-sensitive applications.
+## Boxing
+In Java, the valueOf() method is a static method provided by wrapper classes to convert a string representation of the data into an object of the corresponding wrapper class. This method is particularly useful when you have data in string format and need to convert it into an object for further processing. This is called `Boxing` in java.
+### Syntax
+The syntax of the `valueOf()` method varies slightly depending on the wrapper class, but generally, it follows the format:
+```java
+WrapperClass.valueOf(String str);
+
+```
+Where:
+
+- WrapperClass is the name of the wrapper class (e.g., Integer, Double, Boolean, etc.).
+- str is the string representation of the data that you want to convert.
+### Converting String to Integer
+```java
+String str = "123";
+Integer intValue = Integer.valueOf(str);
+System.out.println("Integer value: " + intValue);
+```
+In this example:
+
+- We have a string "123".
+- We use `Integer.valueOf(str)` to convert the string to an `Integer` object.
+- The resulting intValue contains the integer value 123.
+### Converting String to Double
+```java
+String str = "3.14";
+Double doubleValue = Double.valueOf(str);
+System.out.println("Double value: " + doubleValue);
+```
+In this example:
+
+- We have a string "3.14".
+- We use `Double.valueOf(str)` to convert the string to a `Double object.
+- The resulting `doubleValue` contains the double value 3.14.
+### Conclusion
+The `valueOf()` method in Java is a convenient way to convert string representations of data into objects of the corresponding wrapper classes. It simplifies the process of parsing and converting strings into primitive data types, allowing for easier manipulation and processing of data in Java programs.
+## Unboxing
+In Java, unboxing refers to the automatic conversion of a wrapper class object to its corresponding primitive data type. When you retrieve the value from a wrapper class object, Java automatically unboxes it to its primitive type. This process simplifies code and improves readability by allowing you to work with primitive types in situations where wrapper class objects are used.
+### Unboxing Process
+Unboxing occurs implicitly when you assign a wrapper class object to a primitive type variable or when you use the value of a wrapper class object in an expression that expects a primitive type.
+#### Example
+```java
+Integer wrapperInt = Integer.valueOf(10); // Creating an Integer wrapper object
+int primitiveInt = wrapperInt; // Unboxing the Integer to int
+```
+In this example:
+
+- wrapperInt is an `Integer` object containing the value 10.
+- primitiveInt is an int variable.
+- When wrapperInt is assigned to primitiveInt, Java automatically unboxes the Integer object to its corresponding int value.
+### Example Usage
+```java
+Integer wrapperInt = Integer.valueOf(20);
+int primitiveInt = wrapperInt; // Unboxing
+
+Double wrapperDouble = Double.valueOf(3.14);
+double primitiveDouble = wrapperDouble; // Unboxing
+
+Boolean wrapperBoolean = Boolean.valueOf(true);
+boolean primitiveBoolean = wrapperBoolean; // Unboxing
+```
+In each of these examples, the value of the wrapper class object is automatically unboxed to its corresponding primitive type.
+### Benefits of Unboxing
+**Simplifies Code :** Unboxing eliminates the need for explicit conversion between wrapper class objects and primitive types, making the code cleaner and more concise.
+**Improves Readability :** Unboxing makes the code easier to understand by allowing you to work with primitive types directly, especially in situations where wrapper class objects are used, such as collections and generics.
+### Conclusion
+Unboxing in Java simplifies the process of converting wrapper class objects to their corresponding primitive types. By allowing you to work seamlessly with primitive types and wrapper class objects, unboxing improves code readability and makes Java programming more efficient.
+## Autoboxing and Auto-Unboxing in Java
+Autoboxing and auto-unboxing are features introduced in Java 5 that simplify the conversion between primitive data types and their corresponding wrapper classes. Autoboxing automatically converts primitive types to wrapper objects when necessary, while auto-unboxing automatically converts wrapper objects to their corresponding primitive types.
+### Autoboxing
+Autoboxing is the process of automatically converting primitive data types into their corresponding wrapper classes. This conversion is done implicitly by the Java compiler.
+#### Example
+```java
+// Autoboxing int to Integer
+int primitiveInt = 10;
+Integer wrapperInt = primitiveInt; // Autoboxing
+```
+In this example, the primitive `int` value 10 is automatically converted to an Integer wrapper class object.
+### Auto-Unboxing
+Auto-unboxing is the process of automatically converting wrapper class objects to their corresponding primitive data types. This conversion is also done implicitly by the Java compiler.
+#### Example
+```java
+// Auto-unboxing Integer to int
+Integer wrapperInt = Integer.valueOf(20);
+int primitiveInt = wrapperInt; // Auto-unboxing
+```
+In this example, the `Integer` wrapper class object containing the value 20 is automatically converted to a primitive int.
+#### Benefits of Autoboxing and Auto-Unboxing
+- **Simplifies Code :** Autoboxing and auto-unboxing eliminate the need for explicit conversion between primitive types and wrapper classes, making the code cleaner and more concise.
+- **Improves Readability :** These features make Java code more readable by allowing developers to work with primitive types and wrapper classes interchangeably, without having to manually perform conversions.
+#### Considerations
+- **Performance :** While autoboxing and auto-unboxing provide convenience, they may introduce performance overhead compared to manually handling conversions, especially in performance-sensitive code.
+- **Null Handling :** Auto-unboxing a null wrapper object will result in a NullPointerException.
+#### Conclusion
+Autoboxing and auto-unboxing in Java simplify the process of converting between primitive types and their corresponding wrapper classes. By automatically handling these conversions, these features improve code readability and make Java programming more convenient. However, developers should be mindful of performance implications and null handling when using autoboxing and auto-unboxing in their code.
+## Caching with valueOf()
+In Java, the `valueOf()` method provided by wrapper classes such as Integer, Double, Boolean, etc., often implements caching for certain commonly used values. This caching mechanism improves memory utilization and performance by reusing existing objects for frequently accessed values within a predefined range.
+### Caching Mechanism
+When you call the `valueOf()` method for certain primitive values within a specific range, the wrapper class implementation may return a cached object instead of creating a new one. This optimization is particularly useful for frequently used values, such as small integers.
+#### Example
+```java
+Integer int1 = Integer.valueOf(10);
+Integer int2 = Integer.valueOf(10);
+
+```
+In this example, both int1 and int2 will reference the same cached Integer object representing the value 10. Instead of creating a new object for each call to valueOf(10), Java reuses the existing cached object.
+### Benefits of Caching
+- **Memory Efficiency :** Caching reduces memory consumption by reusing existing objects for commonly used values, rather than creating new objects for each value.
+- **Improved Performance :** By reusing cached objects, Java avoids unnecessary object creation and garbage collection overhead, resulting in improved performance, especially in scenarios where the same values are used frequently.
+### Considerations
+- **Range Limitation :** Caching is typically implemented for values within a predefined range. Values outside this range may not be cached and will result in the creation of new objects.
+- **Thread Safety :** While caching improves performance, developers should ensure thread safety when working with mutable wrapper classes in a multi-threaded environment.
+### Conclusion
+Caching with `valueOf()` in Java improves memory efficiency and performance by reusing existing objects for commonly used values. By avoiding unnecessary object creation and leveraging cached objects, Java programs can achieve better memory utilization and faster execution, particularly in scenarios involving frequently accessed values. Developers should be aware of the caching behavior of wrapper classes and leverage it effectively to optimize their code.
+## Java Collection Hierarchy Framework
+The Java Collection Framework provides a unified architecture for representing and manipulating collections of objects. It includes interfaces, implementations, and algorithms to manage collections of objects efficiently. Understanding the collection hierarchy is essential for Java developers to utilize the appropriate collection types for their specific needs.
+### Interfaces
+#### 1. Collection
+- Represents a group of objects known as elements.
+- **Subinterfaces :** List, Set, and Queue.
+#### 2. List
+- Ordered collection (by index).
+- Allows duplicate elements.
+- **Subinterfaces :** ArrayList, LinkedList, Vector, Stack, etc.
+#### 3. Set
+- Collection that does not allow duplicate elements.
+- **Subinterfaces :** HashSet, LinkedHashSet, TreeSet.
+#### 4. Queue
+- Collection used to hold elements before processing.
+- Follows FIFO (First-In-First-Out) order.
+- **Subinterfaces :** Deque, PriorityQueue.
+#### 5. Map
+- Represents a mapping between keys and values.
+- Does not extend the Collection interface.
+- **Subinterfaces :** HashMap, LinkedHashMap, TreeMap.
+### Classes
+#### 1. ArrayList
+- Resizable array implementation of the List interface.
+- Allows fast random access but slower insertion/deletion at the middle.
+#### 2. LinkedList
+- Doubly-linked list implementation of the List interface.
+- Efficient for insertion/deletion at the beginning/middle.
+#### 3. HashSet
+- Implements the Set interface using a hash table.
+- Does not guarantee the order of elements.
+#### 4. TreeSet
+- Implements the Set interface using a Red-Black tree.
+- Maintains elements in sorted order.
+#### 5. HashMap
+- Implements the Map interface using a hash table.
+- Provides constant-time performance for basic operations (get and put).
+#### 6. TreeMap
+- Implements the Map interface using a Red-Black tree.
+- Maintains elements in sorted order based on keys.
+### Benefits
+** Standardized API :** Provides a common set of interfaces and classes for working with collections, promoting code reusability and interoperability.
+**Efficiency :** Offers efficient implementations for various collection types, catering to different use cases and performance requirements.
+**Flexibility :** Supports a wide range of operations and provides different implementations to suit specific application needs.
+### Conclusion
+The Java Collection Hierarchy Framework is a powerful tool for managing collections of objects in Java programs. By understanding its interfaces, classes, and their relationships, developers can effectively utilize collections to store, manipulate, and retrieve data efficiently. Whether working with lists, sets, queues, or maps, the Collection Framework provides a rich set of features to meet the diverse needs of Java applications.
From 5da274db067d4375516c93a05691f4d23d3e89f2 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 3 Apr 2024 14:41:20 +0530
Subject: [PATCH 164/236] Update README.md
---
section7/README.md | 35 +++++++++++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
diff --git a/section7/README.md b/section7/README.md
index 940be6e..eee5551 100644
--- a/section7/README.md
+++ b/section7/README.md
@@ -567,6 +567,41 @@ In this example :
- Not Suitable for Complex Logic: For complex conditions, using if-else statements is often more appropriate.
### Conclusion
The Ternary Conditional Operator is a powerful tool for writing concise conditional statements in Java. It can improve code readability and reduce verbosity for simple conditions. However, it should be used judiciously and avoided for complex logic to maintain code clarity and understandability.
+## Java Operators Precedence & Associativity
+In Java, operators have precedence and associativity, which determine the order of evaluation of expressions. Understanding these concepts is crucial for writing correct and efficient code.
+### Precedence
+Precedence refers to the priority of operators in an expression. Operators with higher precedence are evaluated before operators with lower precedence. Here's a summary of operator precedence in Java (from highest to lowest precedence):
+1. Postfix operators: `expr++`, `expr--`
+2. Unary operators: `++expr`, `--expr`, `+expr`, `-expr`, `~`, `!`
+3. Multiplicative operators: `*`, `/`, `%`
+4. Additive operators: `+`, `-`
+5. Shift operators: `<<`, `>>`, `>>>`
+6. Relational operators: `<`, `<=`, `>`, `>=`, `instanceof`
+7. Equality operators: `==`, `!=`
+8. Bitwise AND: `&`
+9. Bitwise XOR: `^`
+10. Bitwise OR: `|`
+11. Logical AND: `&&`
+12. Logical OR: `||`
+13. Ternary conditional: `? :`
+14. Assignment operators: `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, `>>>=`
+- Operators with higher precedence are evaluated first. For example, in `a + b * c`, `b * c` is evaluated first because `*` has higher precedence than `+`.
+### Associativity
+Associativity determines the order in which operators of the same precedence are evaluated. Java operators can be either left-associative or right-associative.
+- Left-associative operators are evaluated from left to right. For example, `a + b + c` is evaluated as `(a + b) + c`.
+- Right-associative operators are evaluated from right to left. Assignment operators (`=`) are the only right-associative operators in Java.
+#### Examples
+
+#### Precedence Example
+```java
+int result = 10 + 2 * 3; // Result is 16 (2 * 3 is evaluated first)
+```
+### Associativity Example
+```java
+int result = 10 - 5 - 2; // Result is 3 (left associative: (10 - 5) - 2)
+```
+### Conclusion
+Understanding operator precedence and associativity helps in writing code that behaves as expected. Always use parentheses to clarify expressions when needed, especially when dealing with complex expressions involving multiple operators.
From 9c6d7f5a8a4bec8256662f5dd47c8dac8970996b Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 3 Apr 2024 14:45:00 +0530
Subject: [PATCH 165/236] Create README.md
---
section_17/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_17/README.md
diff --git a/section_17/README.md b/section_17/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_17/README.md
@@ -0,0 +1 @@
+
From 079297627fde38c8517d900ace16064baaa50b85 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 3 Apr 2024 17:35:44 +0530
Subject: [PATCH 166/236] Update README.md
---
section_17/README.md | 371 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 371 insertions(+)
diff --git a/section_17/README.md b/section_17/README.md
index 8b13789..e0e77be 100644
--- a/section_17/README.md
+++ b/section_17/README.md
@@ -1 +1,372 @@
+# Lists and ArrayLists
+## List Interface
+The List interface in Java is a part of the Java Collections Framework. It extends the Collection interface and represents an ordered collection of elements where elements can be accessed and inserted by their index. Lists in Java allow duplicate elements and can hold elements of different data types. The List interface provides various methods to perform operations such as insertion, deletion, searching, and iteration over elements.
+### Key Features
+- **Ordered Collection**: Lists maintain the order of elements as they are inserted.
+- **Allows Duplicates**: Lists can contain duplicate elements.
+- **Random Access**: Elements in a List can be accessed using their index.
+- **Dynamic Size**: Lists automatically resize themselves as elements are added or removed.
+### Implementations
+Java provides several implementations of the List interface, each with its own characteristics:
+
+1. **ArrayList**: Implements a dynamic array that can grow as needed. Provides fast random access and is suitable for storing large collections of elements.
+
+2. **LinkedList**: Implements a doubly linked list, which allows for efficient insertion and deletion operations at the beginning, middle, or end of the list. It is not suitable for random access but provides better performance for frequent insertion and deletion operations.
+
+3. **Vector**: Similar to ArrayList but is synchronized, making it thread-safe. However, it is less efficient than ArrayList in terms of performance.
+
+4. **Stack**: Extends Vector and represents a last-in, first-out (LIFO) stack of objects.
+### Common Operations
+- **Adding Elements**: `add(E element)`, `add(int index, E element)`
+- **Accessing Elements**: `get(int index)`, `indexOf(Object o)`
+- **Removing Elements**: `remove(Object o)`, `remove(int index)`
+- **Size and Empty Check**: `size()`, `isEmpty()`
+- **Iteration**: Using enhanced for loop or iterators.
+### Example
+
+```java
+import java.util.*;
+
+public class ListExample {
+ public static void main(String[] args) {
+ // Creating a List
+ List names = new ArrayList<>();
+
+ // Adding elements
+ names.add("Alice");
+ names.add("Bob");
+ names.add("Charlie");
+
+ // Accessing elements
+ System.out.println("First name: " + names.get(0));
+
+ // Iterating over elements
+ for (String name : names) {
+ System.out.println(name);
+ }
+
+ // Removing an element
+ names.remove("Bob");
+ System.out.println("After removing Bob: " + names);
+ }
+}
+```
+### Conclusion
+The List interface in Java is a fundamental part of the Java Collections Framework, providing a versatile and efficient way to manage ordered collections of elements. With implementations like ArrayList, LinkedList, Vector, and Stack, Java developers have a variety of options to choose from based on their specific requirements for performance, thread safety, and usage patterns.
+
+Whether you need fast random access, efficient insertion and deletion, or thread-safe operations, the List interface has you covered. By leveraging its rich set of methods and features, you can build robust and scalable applications in Java.
+
+Keep exploring the Java Collections Framework and experiment with different List implementations to discover the most suitable solution for your projects.
+## ArrayList
+ArrayList is a part of the Java Collection Framework and is a dynamic array that can resize itself when elements are added or removed. It is similar to arrays, but with the ability to dynamically resize itself. ArrayList is implemented in the `java.util` package.
+### Features
+- **Dynamic Sizing**: ArrayList can dynamically resize itself to accommodate more elements.
+- **Random Access**: Elements can be accessed using their index, allowing for fast random access.
+- **Generic**: ArrayList is a generic class, allowing it to store elements of any data type.
+- **Iterable**: Implements the Iterable interface, allowing for easy iteration over its elements.
+- **Automatic Boxing and Unboxing**: ArrayList automatically handles the conversion between primitive types and their corresponding wrapper classes.
+### Creating an ArrayList
+```java
+import java.util.ArrayList;
+
+ArrayList list = new ArrayList<>();
+```
+### Adding Elements
+```java
+list.add("Java");
+list.add("Python");
+list.add("C++");
+```
+### Accessing Elements
+```java
+String element = list.get(0);
+System.out.println(element); // Output: Java
+```
+### Removing Elements
+```java
+list.remove("Python");
+```
+### Iterating over ArrayList
+```java
+for (String item : list) {
+ System.out.println(item);
+}
+```
+### Other Operations
+**size() :** Returns the number of elements in the ArrayList.
+**isEmpty() :** Returns true if the ArrayList is empty, false otherwise.
+**contains(Object o) :** Returns true if the ArrayList contains the specified element.
+**clear() :** Removes all elements from the ArrayList.
+### Performance
+- Insertion/Deletion: O(n)
+- Random Access: O(1)
+- Search: O(n)
+### Thread Safety
+ArrayList is not thread-safe. If multiple threads access an ArrayList concurrently and at least one of the threads modifies the list structurally, it must be synchronized externally.
+## Diamond Operator
+The diamond operator (`<>`) in Java is a feature introduced in Java 7 that simplifies the use of generics. It allows you to instantiate a generic class without specifying the type arguments if the compiler can infer the type arguments from the context.
+### Usage
+Consider the following example:
+```java
+```java
+// Before Java 7
+List list = new ArrayList();
+
+// With Diamond Operator (Java 7+)
+List list = new ArrayList<>();
+```
+In the second line of the example, the type arguments are omitted after new ArrayList<>. The compiler infers the type arguments from the declaration of list.
+### Benefits
+Using the diamond operator provides several benefits:
+
+**Conciseness :** It reduces boilerplate code by omitting redundant type arguments.
+**Readability :** The code becomes cleaner and easier to read, especially for complex generic types.
+**Maintainability :** It simplifies code maintenance as there are fewer explicit type declarations to update when modifying code.
+### Limitations
+While the diamond operator offers convenience, there are certain limitations to be aware of:
+
+**Type Inference :** The type inference performed by the compiler may not always produce the expected results, especially in complex scenarios.
+**Compatibility :** Code using the diamond operator is not compatible with Java versions prior to Java 7.
+### Best Practices
+To make the most of the diamond operator, consider the following best practices:
+
+**Use Where Appropriate :** Apply the diamond operator where type inference is straightforward and enhances code readability.
+**Avoid Overuse :** While the diamond operator reduces verbosity, avoid overusing it in scenarios where explicit type arguments are necessary for clarity.
+**Keep Code Compatible :** Ensure that your codebase is compatible with Java 7 or higher if you plan to utilize the diamond operator extensively.
+### Conclusion
+The diamond operator in Java is a convenient feature for simplifying generic type instantiation. By allowing type inference, it reduces boilerplate code and enhances code readability. However, it's important to use it judiciously and be aware of its limitations to maintain code clarity and compatibility.
+## Creating Immutable List Objects
+In Java, immutable objects are objects whose state cannot be modified after they are created. This prevents unintended changes to the object's data and promotes safer, more predictable code. Immutable list objects are particularly useful when you need to ensure that a collection of elements remains unchanged throughout the program's execution.
+### Why Use Immutable Lists?
+- **Thread Safety**: Immutable lists are inherently thread-safe because their state cannot change once they are created. This eliminates the need for synchronization and helps prevent concurrency issues.
+
+- **Predictable Behavior**: Since immutable lists cannot be modified after creation, they provide predictable behavior, making it easier to reason about your code and avoid unexpected side effects.
+
+- **Security**: Immutable lists can be shared freely without the risk of their contents being altered. This is especially important when dealing with sensitive data or in distributed systems.
+### How to Create Immutable Lists
+- Using `Collections.unmodifiableList()`
+```java
+import java.util.*;
+
+public class ImmutableListExample {
+ public static void main(String[] args) {
+ List mutableList = new ArrayList<>();
+ mutableList.add("Apple");
+ mutableList.add("Banana");
+ mutableList.add("Orange");
+
+ List immutableList = Collections.unmodifiableList(mutableList);
+
+ // Attempting to modify the immutable list will throw UnsupportedOperationException
+ // immutableList.add("Grapes"); // This will throw UnsupportedOperationException
+ }
+}
+```
+### Using List.of() (Java 9 and later)
+```java
+import java.util.*;
+
+public class ImmutableListExample {
+ public static void main(String[] args) {
+ List immutableList = List.of("Apple", "Banana", "Orange");
+
+ // Attempting to modify the immutable list will throw UnsupportedOperationException
+ // immutableList.add("Grapes"); // This will throw UnsupportedOperationException
+ }
+}
+```
+
+Sure, here's a README.md file for creating Immutable list objects in Java:
+
+vbnet
+Copy code
+# Creating Immutable List Objects in Java
+
+In Java, immutable objects are objects whose state cannot be modified after they are created. This prevents unintended changes to the object's data and promotes safer, more predictable code. Immutable list objects are particularly useful when you need to ensure that a collection of elements remains unchanged throughout the program's execution.
+
+## Why Use Immutable Lists?
+
+- **Thread Safety**: Immutable lists are inherently thread-safe because their state cannot change once they are created. This eliminates the need for synchronization and helps prevent concurrency issues.
+
+- **Predictable Behavior**: Since immutable lists cannot be modified after creation, they provide predictable behavior, making it easier to reason about your code and avoid unexpected side effects.
+
+- **Security**: Immutable lists can be shared freely without the risk of their contents being altered. This is especially important when dealing with sensitive data or in distributed systems.
+
+## How to Create Immutable Lists in Java
+
+Java provides several ways to create immutable lists:
+
+### Using `Collections.unmodifiableList()`
+
+```java
+import java.util.*;
+
+public class ImmutableListExample {
+ public static void main(String[] args) {
+ List mutableList = new ArrayList<>();
+ mutableList.add("Apple");
+ mutableList.add("Banana");
+ mutableList.add("Orange");
+
+ List immutableList = Collections.unmodifiableList(mutableList);
+
+ // Attempting to modify the immutable list will throw UnsupportedOperationException
+ // immutableList.add("Grapes"); // This will throw UnsupportedOperationException
+ }
+}
+Using List.of() (Java 9 and later)
+java
+Copy code
+import java.util.*;
+
+public class ImmutableListExample {
+ public static void main(String[] args) {
+ List immutableList = List.of("Apple", "Banana", "Orange");
+
+ // Attempting to modify the immutable list will throw UnsupportedOperationException
+ // immutableList.add("Grapes"); // This will throw UnsupportedOperationException
+ }
+}
+```
+### Using Third-party Libraries
+Several third-party libraries like Guava and Apache Commons Collections provide utilities for creating immutable lists. Here's an example using Guava:
+
+```java
+import com.google.common.collect.ImmutableList;
+
+public class ImmutableListExample {
+ public static void main(String[] args) {
+ ImmutableList immutableList = ImmutableList.of("Apple", "Banana", "Orange");
+
+ // Attempting to modify the immutable list will throw UnsupportedOperationException
+ // immutableList.add("Grapes"); // This will throw UnsupportedOperationException
+ }
+}
+```
+### Conclusion
+Immutable lists in Java provide a convenient and safe way to work with collections of data. By ensuring that lists cannot be modified after creation, they help improve code clarity, maintainability, and reliability.
+## Iterating ArrayList with for-each and Iterator()
+### Iterating with Enhanced For Loop (for-each)
+The enhanced for loop, also known as the for-each loop, provides a concise and readable way to iterate over elements in a collection such as an ArrayList.
+```java
+ArrayList list = new ArrayList<>();
+// Add elements to the ArrayList
+
+for (String element : list) {
+ System.out.println(element);
+}
+```
+In this example, element represents each item in the `ArrayList` list, and the loop iterates through all elements of the list, printing each one.
+### Iterating with Iterator
+The `Iterator` interface provides a way to iterate over elements in a collection sequentially. It allows for safe removal of elements during iteration.
+```java
+ArrayList list = new ArrayList<>();
+// Add elements to the ArrayList
+
+Iterator iterator = list.iterator();
+while (iterator.hasNext()) {
+ String element = iterator.next();
+ System.out.println(element);
+}
+```
+In this example, `iterator()` method returns an iterator over the elements in the ArrayList list. The `hasNext()` method checks if there are more elements to iterate over, and `next()` returns the next element in the iteration.
+
+### Conclusion
+Both the enhanced for loop and the Iterator interface provide effective ways to iterate over an ArrayList in Java. Choose the one that suits your coding style and requirements.
+## Iterating ArrayList using listIterator()
+In Java, the `ArrayList` class provides a convenient way to store and manipulate collections of objects dynamically. Iterating over elements of an `ArrayList` is a common operation. One way to iterate over an `ArrayList` is by using the `listIterator()` method, which allows traversal of the list in both forward and backward directions.
+### 1. Import ArrayList and ListIterator classes
+```java
+import java.util.ArrayList;
+import java.util.ListIterator;
+```
+### 2. Create an ArrayList
+```java
+ArrayList arrayList = new ArrayList<>();
+```
+### 3. Add elements to the ArrayList
+```java
+arrayList.add("Element 1");
+arrayList.add("Element 2");
+arrayList.add("Element 3");
+```
+### 4. Iterate over the ArrayList using listIterator()
+```java
+ListIterator iterator = arrayList.listIterator();
+while (iterator.hasNext()) {
+ String element = iterator.next();
+ System.out.println(element);
+}
+```
+### 5. Iterate over the ArrayList in reverse order using listIterator()
+```java
+while (iterator.hasPrevious()) {
+ String element = iterator.previous();
+ System.out.println(element);
+}
+```
+### Conclusion
+Using listIterator() provides a flexible way to iterate over an ArrayList in both forward and backward directions. This allows for efficient traversal and manipulation of elements in the list.
+## Sorting ArrayList in Java using `sort()`
+
+This guide demonstrates how to sort an ArrayList in Java using the `sort()` method from the `java.util.Collections` class.
+
+## Steps
+
+1. **Create an ArrayList**: First, create an ArrayList and add elements to it. For example:
+ ```java
+ import java.util.ArrayList;
+
+ public class Main {
+ public static void main(String[] args) {
+ ArrayList numbers = new ArrayList<>();
+ numbers.add(5);
+ numbers.add(2);
+ numbers.add(8);
+ numbers.add(1);
+ numbers.add(10);
+
+ System.out.println("Original ArrayList: " + numbers);
+ }
+ }
+ ```
+
+2. **Sort the ArrayList**: Use the `sort()` method from the `java.util.Collections` class to sort the ArrayList. For example:
+ ```java
+ import java.util.Collections;
+
+ // After adding elements to the ArrayList (numbers)
+ Collections.sort(numbers);
+
+ System.out.println("Sorted ArrayList: " + numbers);
+ ```
+
+3. **Complete code**:
+ ```java
+ import java.util.ArrayList;
+ import java.util.Collections;
+
+ public class Main {
+ public static void main(String[] args) {
+ ArrayList numbers = new ArrayList<>();
+ numbers.add(5);
+ numbers.add(2);
+ numbers.add(8);
+ numbers.add(1);
+ numbers.add(10);
+
+ System.out.println("Original ArrayList: " + numbers);
+
+ Collections.sort(numbers);
+
+ System.out.println("Sorted ArrayList: " + numbers);
+ }
+ }
+ ```
+
+## Conclusion
+Sorting an ArrayList in Java is straightforward using the `sort()` method provided by the `java.util.Collections` class. This method arranges the elements of the ArrayList in ascending order.
+
+
+
From ce951c3f857cd35fb045a7135e15e2e2e2a4980d Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 3 Apr 2024 17:49:38 +0530
Subject: [PATCH 167/236] Update README.md
---
section_17/README.md | 215 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 215 insertions(+)
diff --git a/section_17/README.md b/section_17/README.md
index e0e77be..3870f0e 100644
--- a/section_17/README.md
+++ b/section_17/README.md
@@ -366,6 +366,221 @@ This guide demonstrates how to sort an ArrayList in Java using the `sort()` meth
## Conclusion
Sorting an ArrayList in Java is straightforward using the `sort()` method provided by the `java.util.Collections` class. This method arranges the elements of the ArrayList in ascending order.
+## Sorting ArrayList using Custom Comparator
+In Java, you can sort an `ArrayList` using a custom comparator to define your own sorting logic. This is particularly useful when you want to sort objects based on certain criteria that are not directly supported by their natural ordering.
+### Custom Comparator
+A custom comparator is an implementation of the `Comparator` interface that defines how objects should be compared for sorting. You can create a custom comparator by implementing the `compare` method.
+
+Here's a simple example of a custom comparator for sorting strings based on their lengths:
+
+```java
+```java
+import java.util.Comparator;
+
+public class StringLengthComparator implements Comparator {
+ @Override
+ public int compare(String s1, String s2) {
+ return Integer.compare(s1.length(), s2.length());
+ }
+}
+```
+### Sorting ArrayList using Custom Comparator
+Once you have defined your custom comparator, you can use it to sort an `ArrayList` of objects. Here's how you can sort an `ArrayList` of strings using the StringLengthComparator:
+
+```java
+import java.util.ArrayList;
+import java.util.Collections;
+
+public class Main {
+ public static void main(String[] args) {
+ ArrayList strings = new ArrayList<>();
+ strings.add("apple");
+ strings.add("banana");
+ strings.add("orange");
+
+ // Create an instance of the custom comparator
+ StringLengthComparator comparator = new StringLengthComparator();
+
+ // Sort the ArrayList using the custom comparator
+ Collections.sort(strings, comparator);
+
+ // Print the sorted ArrayList
+ System.out.println("Sorted ArrayList:");
+ for (String str : strings) {
+ System.out.println(str);
+ }
+ }
+}
+```
+In this example, the ArrayList of strings is sorted based on their lengths using the `StringLengthComparator`.
+
+### Conclusion
+Using a custom comparator gives you the flexibility to define your own sorting logic when sorting `ArrayList` or any other collections in Java.
+## Sorting ArrayList of Custom Data Type Using Comparable in Java
+
+This guide will walk you through sorting an ArrayList of custom data types using the `Comparable` interface in Java. By implementing the `Comparable` interface, you can define a natural ordering for your custom objects, allowing them to be sorted using built-in sorting methods.
+
+
+## Steps
+
+### 1. Define Your Custom Data Type
+
+First, you need to define a class for your custom data type. Ensure that it implements the `Comparable` interface and overrides the `compareTo()` method to define the natural ordering of objects.
+
+```java
+public class CustomObject implements Comparable {
+ private int value;
+
+ public CustomObject(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ @Override
+ public int compareTo(CustomObject other) {
+ // Implement comparison logic based on the 'value' field
+ return Integer.compare(this.value, other.value);
+ }
+}
+```
+### 2. Create and Populate ArrayList
+Next, create an ArrayList of your custom data type and populate it with objects.
+
+```java
+import java.util.ArrayList;
+import java.util.Collections;
+
+public class Main {
+ public static void main(String[] args) {
+ ArrayList customList = new ArrayList<>();
+ customList.add(new CustomObject(5));
+ customList.add(new CustomObject(2));
+ customList.add(new CustomObject(8));
+ }
+}
+```
+### 3. Sort ArrayList
+Use the `Collections.sort()` method to sort the ArrayList. Since your custom data type implements the Comparable interface, it will automatically use the `compareTo()` method for sorting.
+
+```java
+Collections.sort(customList);
+```
+### 4. Complete Example
+Here's the complete example:
+
+```java
+import java.util.ArrayList;
+import java.util.Collections;
+
+public class Main {
+ public static void main(String[] args) {
+ ArrayList customList = new ArrayList<>();
+ customList.add(new CustomObject(5));
+ customList.add(new CustomObject(2));
+ customList.add(new CustomObject(8));
+
+ // Sort the ArrayList
+ Collections.sort(customList);
+
+ // Print sorted ArrayList
+ for (CustomObject obj : customList) {
+ System.out.println(obj.getValue());
+ }
+ }
+}
+
+class CustomObject implements Comparable {
+ private int value;
+
+ public CustomObject(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ @Override
+ public int compareTo(CustomObject other) {
+ return Integer.compare(this.value, other.value);
+ }
+}
+```
+### Conclusion
+Using the `Comparable` interface in Java allows you to define the natural ordering of custom objects, enabling you to easily sort `ArrayLists` containing these objects. By following the steps outlined in this guide, you can effectively sort `ArrayLists` of custom data types using `Comparable` in Java.
+## Sorting ArrayList of Custom Data Type using Comparator in Java
+
+This guide demonstrates how to sort an ArrayList containing custom data types in Java using the `Comparator` interface.
+
+
+### Sorting ArrayList of Custom Data Type
+
+1. **Create your custom data type:** Define a class representing your custom data type. For example, let's consider a `Person` class with `name` and `age` attributes.
+
+ ```java
+ public class Person {
+ private String name;
+ private int age;
+
+ // Constructor, getters, and setters
+ }
+ ```
+
+2. **Implement Comparator interface:** Implement the `Comparator` interface to define custom comparison logic for your custom data type. Override the `compare` method.
+
+ ```java
+ import java.util.Comparator;
+
+ public class PersonComparator implements Comparator {
+ @Override
+ public int compare(Person p1, Person p2) {
+ // Custom comparison logic, e.g., comparing by age
+ return Integer.compare(p1.getAge(), p2.getAge());
+ }
+ }
+ ```
+
+3. **Sort ArrayList using Comparator:** Use the `Collections.sort()` method to sort the ArrayList using your custom Comparator.
+
+ ```java
+ import java.util.ArrayList;
+ import java.util.Collections;
+
+ public class Main {
+ public static void main(String[] args) {
+ // Create ArrayList of Person objects
+ ArrayList people = new ArrayList<>();
+ people.add(new Person("Alice", 30));
+ people.add(new Person("Bob", 25));
+ people.add(new Person("Charlie", 35));
+
+ // Sort the ArrayList using Comparator
+ Collections.sort(people, new PersonComparator());
+
+ // Print sorted ArrayList
+ for (Person person : people) {
+ System.out.println(person.getName() + ", " + person.getAge());
+ }
+ }
+ }
+ ```
+
+### Running the Code
+
+1. Compile the Java files: `javac Main.java Person.java PersonComparator.java`
+2. Run the compiled Java program: `java Main`
+
+You should see the sorted list of `Person` objects printed in the console.
+
+### Conclusion
+
+Sorting an ArrayList of custom data types in Java using Comparator provides flexibility in defining custom comparison logic. By implementing the `Comparator` interface, you can sort the ArrayList based on any attributes or criteria specific to your application.
+
+
+
From 62712ca1df11eb3cee97414df678a4f15c74dfc4 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 3 Apr 2024 18:06:10 +0530
Subject: [PATCH 168/236] Update README.md
From a09393270c7f8fe3ef1df16acbcd8e2d3085eda1 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 4 Apr 2024 14:52:58 +0530
Subject: [PATCH 169/236] Create README.md
---
section_18/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_18/README.md
diff --git a/section_18/README.md b/section_18/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_18/README.md
@@ -0,0 +1 @@
+
From 7c9821c412099f8a14f1242227eda2890ca00765 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 4 Apr 2024 15:19:00 +0530
Subject: [PATCH 170/236] Update README.md
---
section_18/README.md | 130 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 130 insertions(+)
diff --git a/section_18/README.md b/section_18/README.md
index 8b13789..999aecf 100644
--- a/section_18/README.md
+++ b/section_18/README.md
@@ -1 +1,131 @@
+# LinkedList in Java π
+In Java, LinkedList is a class that implements the List interface and represents a linked list data structure. It is a linear data structure where each element, known as a node, contains a reference to the next node in the sequence, forming a chain-like structure. Unlike arrays, which have contiguous memory allocation, linked lists use dynamic memory allocation, which allows for efficient insertion and deletion operations, especially in the middle of the list.
+Here are some key points about LinkedList in Java:
+
+**Node Structure :** Each node in a LinkedList contains two fields: the data field, which holds the element value, and the next field, which holds a reference to the next node in the sequence.
+
+**Doubly Linked List :** In Java, the LinkedList class implements a doubly linked list, meaning each node contains references to both the next node and the previous node in the sequence. This allows for efficient traversal in both directions.
+
+**Dynamic Size :** Unlike arrays, linked lists do not have a fixed size. They can grow or shrink dynamically as elements are added or removed.
+
+**Random Access :** Unlike arrays, accessing elements in a linked list by index requires traversing the list from the beginning or end, which can be less efficient for large lists compared to arrays.
+
+**Insertion and Deletion :** Linked lists excel at insertion and deletion operations, especially in the middle of the list, as they only require adjusting references between nodes, rather than shifting elements like in arrays.
+
+Here's a simple example of how to use LinkedList in Java:
+
+```java
+import java.util.LinkedList;
+
+public class Main {
+ public static void main(String[] args) {
+ // Creating a LinkedList
+ LinkedList linkedList = new LinkedList<>();
+
+ // Adding elements
+ linkedList.add("Apple");
+ linkedList.add("Banana");
+ linkedList.add("Orange");
+
+ // Printing elements
+ System.out.println("LinkedList: " + linkedList);
+
+ // Removing an element
+ linkedList.remove("Banana");
+ System.out.println("LinkedList after removing 'Banana': " + linkedList);
+ }
+}
+```
+Output:
+```java
+LinkedList: [Apple, Banana, Orange]
+LinkedList after removing 'Banana': [Apple, Orange]
+```
+## Iterating over a LinkedList
+LinkedList is a class in Java that provides a linked-list data structure. It implements the List interface and provides methods to manipulate the elements in the list. Iterating over a LinkedList is a common operation in Java programming.
+### Using Iterator
+```java
+import java.util.LinkedList;
+import java.util.Iterator;
+
+public class IterateLinkedList {
+ public static void main(String[] args) {
+ LinkedList linkedList = new LinkedList<>();
+ linkedList.add("Apple");
+ linkedList.add("Banana");
+ linkedList.add("Orange");
+
+ // Using Iterator
+ Iterator iterator = linkedList.iterator();
+ while(iterator.hasNext()) {
+ String element = iterator.next();
+ System.out.println(element);
+ }
+ }
+}
+```
+### Using Enhanced for Loop
+```java
+import java.util.LinkedList;
+
+public class IterateLinkedList {
+ public static void main(String[] args) {
+ LinkedList linkedList = new LinkedList<>();
+ linkedList.add("Apple");
+ linkedList.add("Banana");
+ linkedList.add("Orange");
+
+ // Using Enhanced for Loop
+ for(String element : linkedList) {
+ System.out.println(element);
+ }
+ }
+}
+```
+### Using ListIterator
+```java
+import java.util.LinkedList;
+import java.util.ListIterator;
+
+public class IterateLinkedList {
+ public static void main(String[] args) {
+ LinkedList linkedList = new LinkedList<>();
+ linkedList.add("Apple");
+ linkedList.add("Banana");
+ linkedList.add("Orange");
+
+ // Using ListIterator
+ ListIterator listIterator = linkedList.listIterator();
+ while(listIterator.hasNext()) {
+ String element = listIterator.next();
+ System.out.println(element);
+ }
+ }
+}
+```
+These are the common ways to iterate over a LinkedList in Java. Choose the method that suits your requirements best based on factors like performance, readability, and specific use case.
+## Sorting a LinkedList Using Collections.sort()
+Java's `Collections.sort()` method can be used to sort elements in a `LinkedList`. This method sorts the elements in their natural order or using a specified comparator.
+### Example π‘
+```java
+import java.util.LinkedList;
+import java.util.Collections;
+
+public class Main {
+ public static void main(String[] args) {
+ LinkedList linkedList = new LinkedList<>();
+ linkedList.add(5);
+ linkedList.add(3);
+ linkedList.add(8);
+ linkedList.add(1);
+
+ System.out.println("Original LinkedList: " + linkedList);
+
+ // Sorting using Collections.sort()
+ Collections.sort(linkedList);
+
+ System.out.println("Sorted LinkedList: " + linkedList);
+ }
+}
+```
From a93ccb8da8c74f3d1f2d266c8bd84ad23168b675 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 4 Apr 2024 15:19:45 +0530
Subject: [PATCH 171/236] Create README.md
---
section_19/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_19/README.md
diff --git a/section_19/README.md b/section_19/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_19/README.md
@@ -0,0 +1 @@
+
From d49fef0bfa5d780c47f419de87467fa8b2f616c8 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 4 Apr 2024 16:38:27 +0530
Subject: [PATCH 172/236] Update README.md
---
section_19/README.md | 107 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 107 insertions(+)
diff --git a/section_19/README.md b/section_19/README.md
index 8b13789..6647d0b 100644
--- a/section_19/README.md
+++ b/section_19/README.md
@@ -1 +1,108 @@
+# Generics in Java π
+Generics in Java are a powerful feature that allow you to write code that can work with different types while providing compile-time type safety. They were introduced in Java 5 to enable developers to create classes, interfaces, and methods that operate on a wide range of data types without sacrificing type safety.
+## Why we need Generics in java
+Generics in Java serve several important purposes:
+
+**Type Safety :** Generics provide compile-time type checking, which helps catch type-related errors at compile time rather than runtime. This ensures that you cannot insert the wrong type of object into a generic container, reducing the likelihood of bugs and making code more robust.
+
+**Code Reusability :** Generics enable you to write code that can operate on a wide range of data types without sacrificing type safety. This promotes code reuse, as you can write generic classes, interfaces, and methods that work with different types of data.
+
+**Abstraction :** Generics allow you to write code that is more abstract and flexible, as it can work with different types of data. This promotes cleaner, more modular code that is easier to maintain and extend.
+
+**Performance :** Generics can improve performance by eliminating the need for type casting in many situations. This can lead to more efficient code execution, especially in performance-critical applications.
+
+**API Design :** Generics enable you to design APIs that are more flexible and easier to use. By using generics, you can create APIs that are type-safe and provide better compile-time checking, leading to improved usability and readability.
+
+Overall, generics in Java are essential for writing robust, reusable, and type-safe code, and they play a crucial role in modern Java programming. They help improve code quality, maintainability, and performance, making them an indispensable feature of the language.
+## Generic Class
+GenericClass.java
+```java
+public class GenericClass {
+ private T data;
+
+ public GenericClass(T data) {
+ this.data = data;
+ }
+
+ public T getData() {
+ return data;
+ }
+
+ public void setData(T data) {
+ this.data = data;
+ }
+
+ public void printType() {
+ System.out.println("Type of data: " + data.getClass().getName());
+ }
+}
+```
+### GenericClass in Java
+
+This is a simple Java class `GenericClass` that demonstrates the use of generics in Java programming.
+
+The `GenericClass` is a generic class, where `T` is a type parameter. This allows the class to be flexible in handling different data types without the need for explicit casting.
+
+## Usage
+
+1. **Instantiate GenericClass with a specific data type:**
+
+ ```java
+ // Instantiate GenericClass with String data
+ GenericClass stringGenericClass = new GenericClass<>("Hello, world!");
+ ```
+
+2. **Set and Get Data:**
+
+ ```java
+ // Set new data
+ stringGenericClass.setData("New data");
+
+ // Get data
+ String data = stringGenericClass.getData();
+ ```
+
+3. **Print Type:**
+
+ ```java
+ // Print the type of data
+ stringGenericClass.printType();
+ ```
+
+### Example
+
+```java
+public class Main {
+ public static void main(String[] args) {
+ // Instantiate GenericClass with String data
+ GenericClass stringGenericClass = new GenericClass<>("Hello, world!");
+
+ // Set new data
+ stringGenericClass.setData("New data");
+
+ // Get data
+ String data = stringGenericClass.getData();
+ System.out.println("Data: " + data);
+
+ // Print the type of data
+ stringGenericClass.printType();
+ }
+}
+```
+## Generic Methods
+Generic methods are methods that introduce their own type parameters. This allows you to create methods that operate on parameterized types. They are essential in writing reusable and type-safe code in Java. This README provides an overview of generic methods in Java and how to use them effectively.
+### Why Use Generic Methods?
+- **Reusability**: Generic methods allow you to write methods that can work with any type, enhancing code reusability.
+- **Type Safety**: With generic methods, you can catch type mismatches at compile time, reducing runtime errors.
+- **Cleaner Code**: By using generics, you can write cleaner and more concise code, avoiding the need for casting.
+### Syntax
+
+A generic method declaration looks like a regular method declaration, except that it includes a type parameter section delimited by angle brackets (< and >) before the method's return type.
+
+```java
+public void methodName(T parameter) {
+ // Method implementation
+}
+```
+
From b490047b94e990ab58d3b479d4b7daf7bc74a5b5 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 4 Apr 2024 17:01:19 +0530
Subject: [PATCH 173/236] Update README.md
---
section_19/README.md | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
diff --git a/section_19/README.md b/section_19/README.md
index 6647d0b..b5d6261 100644
--- a/section_19/README.md
+++ b/section_19/README.md
@@ -104,5 +104,30 @@ public void methodName(T parameter) {
// Method implementation
}
```
+#### Example
+```java
+package com.eazybytes.generics;
+
+public class GenericMethodDemo {
+
+ public static void main(String[] args) {
+ String[] stringArray = {"Hello", "World"};
+ printArray(stringArray);
+ Integer[] intArray = {1,2,3,4,5};
+ printArray(intArray);
+ }
+
+ public static void printArray(T[] array){
+ for(T element:array){
+ System.out.println(element);
+ }
+ }
+
+}
+```
+## Collections without Generics
+Java collections framework provides a set of classes and interfaces to store and manipulate groups of objects. Before the introduction of generics, these collections could hold any type of objects, which could lead to runtime errors if the wrong type of object was added or retrieved.
+#### Example
+
From b655af39f33157b753b2a673f332a6d10931082e Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 4 Apr 2024 17:55:26 +0530
Subject: [PATCH 174/236] Update README.md
---
section_19/README.md | 137 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 137 insertions(+)
diff --git a/section_19/README.md b/section_19/README.md
index b5d6261..f60b9d8 100644
--- a/section_19/README.md
+++ b/section_19/README.md
@@ -128,6 +128,143 @@ public class GenericMethodDemo {
## Collections without Generics
Java collections framework provides a set of classes and interfaces to store and manipulate groups of objects. Before the introduction of generics, these collections could hold any type of objects, which could lead to runtime errors if the wrong type of object was added or retrieved.
#### Example
+```java
+package com.eazybytes.generics;
+
+import java.util.ArrayList;
+
+public class WithOutGenericsDemo {
+
+ public static void main(String[] args) {
+ ArrayList list = new ArrayList();
+ list.add("Hello");
+ list.add(123);
+ list.add(true);
+
+ String greeting = (String) list.get(0);
+ int number = (Integer) list.get(1);
+ boolean flag = (Boolean) list.get(2);
+
+ ArrayList list1 = new ArrayList<>();
+ list1.add("Hello");
+ // list1.add(123);
+ // list1.add(true);
+
+ String greeting1 = list1.get(0);
+ // int number = (Integer) list.get(1);
+ // boolean flag = (Boolean) list.get(0);
+
+ }
+
+}
+```
+## Covariance
+### What is Covariance?
+Covariance is a concept in object-oriented programming that allows a subclass to override a method in its superclass with a return type that is a subclass of the return type of the superclass method. This enables more flexibility in method overriding and allows for a more specific return type in the subclass.
+
+In Java, covariance is primarily used in the context of method overriding and return types in inheritance hierarchies.
+### Understanding Covariance
+In Java, covariance can be illustrated with the use of method overriding and inheritance. Consider a scenario where you have a superclass `Animal` and a subclass `Dog` that extends `Animal`. If the `Animal` class has a method `makeSound()` that returns an `Animal` object, the `Dog` class can override this method to return a `Dog` object instead, thanks to covariance.
+#### Example
+```java
+class Animal {
+ Animal makeSound() {
+ System.out.println("Some sound");
+ return new Animal();
+ }
+}
+
+class Dog extends Animal {
+ @Override
+ Dog makeSound() {
+ System.out.println("Woof");
+ return new Dog();
+ }
+}
+
+public class Main {
+ public static void main(String[] args) {
+ Animal animal = new Dog();
+ animal.makeSound();
+ }
+}
+```
+In this example, the `makeSound()` method in the `Dog` class overrides the same method in the `Animal` class with a more specific return type (Dog).
+## Upper Bound Wildcards
+Upper bound wildcards in Java are a feature of generics that allow greater flexibility when working with generic types. They are denoted by the ` extends T>` syntax, where `T` is a specific type.
+### What are Upper Bound Wildcards?
+Upper bound wildcards are used when you want to specify that a parameterized type may be any subtype of a certain type. For instance, if you have a method that accepts a List of any type that is a subtype of Number, you can use an upper bound wildcard to indicate this:
+```java
+```java
+public void processNumbers(List extends Number> numbers) {
+ // Method implementation
+}
+```
+This method can accept a `List`, `List`, or any other `List` containing elements that extend Number.
+### Key Points to Remember
+- Upper bound wildcards are indicated by extends T> where T is the upper bound type.
+- They allow methods to accept generic types that are subtypes of a specific type.
+- When using upper bound wildcards, you can only read from the collection, not write to it. This is because the compiler cannot guarantee the type safety of adding elements to the collection.
+- Upper bound wildcards are useful when you want to write methods that operate on collections of objects of unknown types but with a certain upper limit.
+
+#### Example
+```java
+import java.util.List;
+
+public class UpperBoundExample {
+ public static double sum(List extends Number> numbers) {
+ double sum = 0.0;
+ for (Number num : numbers) {
+ sum += num.doubleValue();
+ }
+ return sum;
+ }
+
+ public static void main(String[] args) {
+ List integers = List.of(1, 2, 3, 4, 5);
+ List doubles = List.of(1.1, 2.2, 3.3, 4.4, 5.5);
+
+ System.out.println("Sum of integers: " + sum(integers)); // Output: Sum of integers: 15.0
+ System.out.println("Sum of doubles: " + sum(doubles)); // Output: Sum of doubles: 16.5
+ }
+}
+```
+In this example, the sum method can accept both List and List because they both extend Number.
+
+### Conclusion
+Upper bound wildcards in Java provide a powerful tool for writing flexible and reusable code when working with generic types. By using them, you can create methods that accept collections of any subtype of a specific type, enhancing the versatility of your code.
+## Lower Bounded Wildcards
+This Java project demonstrates the use of lower bounded wildcards in Java generics. Lower bounded wildcards are used to relax the restrictions on the type of objects that can be passed as arguments to a method. This README provides an overview of how lower bounded wildcards work and includes examples to illustrate their usage.
+### What are Lower Bounded Wildcards?
+- In Java generics, wildcards (`?`) can be used to represent unknown types. Lower bounded wildcards are denoted by ` super T>`, where `T` is a specific type. Lower bounded wildcards allow for greater flexibility when dealing with generic types by specifying that the type parameter must be either of type `T` or a superclass of `T`.
+- Consider a scenario where we have a method `addAllNumbers` that adds numbers from a list to another list. We want to ensure that the destination list can accept any type that is a superclass of `Number`. We can achieve this using a lower bounded wildcard.
+```java
+import java.util.List;
+
+public class LowerBoundedWildcardExample {
+
+ public static void addAllNumbers(List super Number> dest, List extends Number> src) {
+ dest.addAll(src);
+ }
+
+ public static void main(String[] args) {
+ List numbers = new ArrayList<>();
+ numbers.add(10);
+ numbers.add(20.5);
+
+ List integers = Arrays.asList(1, 2, 3);
+
+ addAllNumbers(numbers, integers);
+
+ System.out.println("Combined List: " + numbers);
+ }
+}
+```
+In this example, the `addAllNumbers` method accepts a destination list (dest) with a lower bounded wildcard ` super Number>`, which means it can accept any type that is a superclass of Number. The source list (src) uses an upper bounded wildcard ` extends Number> to specify that it can accept any subtype of Number. This allows us to add elements from the source list to the destination list without worrying about the specific type of elements in the source list.
+
+
+
+
From 42f41d28dcc0d423b4689a19fafa2df502af301d Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 4 Apr 2024 17:59:09 +0530
Subject: [PATCH 175/236] Update README.md
---
section_19/README.md | 71 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 71 insertions(+)
diff --git a/section_19/README.md b/section_19/README.md
index f60b9d8..cc0e262 100644
--- a/section_19/README.md
+++ b/section_19/README.md
@@ -261,9 +261,80 @@ public class LowerBoundedWildcardExample {
}
```
In this example, the `addAllNumbers` method accepts a destination list (dest) with a lower bounded wildcard ` super Number>`, which means it can accept any type that is a superclass of Number. The source list (src) uses an upper bounded wildcard ` extends Number> to specify that it can accept any subtype of Number. This allows us to add elements from the source list to the destination list without worrying about the specific type of elements in the source list.
+## Unbounded Wildcards in Java
+In Java, wildcards are used in generics to represent an unknown type. Unbounded wildcards, denoted by the question mark (?), allow flexibility by accepting any type. They are particularly useful when the code doesn't rely on the specific type of objects in a generic class or method.
+### Syntax
+The syntax for an unbounded wildcard is simply a question mark (?).
+
+```java
+List> list;
+```
+### Use Cases
+Unbounded wildcards are commonly used in the following scenarios:
+
+When the code is agnostic about the type: If the code doesn't depend on the specific type of objects in a generic class or method, unbounded wildcards can be used to provide flexibility.
+
+When working with collections of unknown types: When dealing with collections where the type of elements is unknown or irrelevant, unbounded wildcards can be used to ensure compatibility.
+
+As a parameter or return type in methods: Unbounded wildcards can be used as parameter types or return types in methods to accept or return any type of object.
+
+
+### Examples
+### Example 1: Using Unbounded Wildcards with Collections
+```java
+import java.util.List;
+public class UnboundedWildcardsExample {
+ public static double sum(List> list) {
+ double sum = 0.0;
+ for (Object obj : list) {
+ if (obj instanceof Number) {
+ sum += ((Number) obj).doubleValue();
+ }
+ }
+ return sum;
+ }
+ public static void main(String[] args) {
+ List integers = List.of(1, 2, 3);
+ List doubles = List.of(1.5, 2.5, 3.5);
+ System.out.println("Sum of integers: " + sum(integers));
+ System.out.println("Sum of doubles: " + sum(doubles));
+ }
+}
+```
+In this example, the sum method accepts a list of any type `(List>). It iterates over the elements of the list and sums up the values if they are instances of Number. This method can accept lists of integers, doubles, or any other numeric type.
+
+### Example 2: Using Unbounded Wildcards with Methods
+```java
+import java.util.Arrays;
+import java.util.List;
+
+public class UnboundedWildcardsExample {
+ public static void printList(List> list) {
+ for (Object obj : list) {
+ System.out.print(obj + " ");
+ }
+ System.out.println();
+ }
+
+ public static void main(String[] args) {
+ List integers = Arrays.asList(1, 2, 3);
+ List strings = Arrays.asList("Hello", "World");
+
+ System.out.print("Integers: ");
+ printList(integers);
+
+ System.out.print("Strings: ");
+ printList(strings);
+ }
+}
+```
+In this example, the printList method accepts a list of any type `(List>)`. It prints the elements of the list without knowing their specific type. This method can be used to print lists of integers, strings, or any other type.
+
+### Conclusion
+Unbounded wildcards `(?)` in Java generics provide flexibility when the code doesn't rely on the specific type of objects in a generic class or method. They are useful for scenarios where the type is unknown or irrelevant, allowing for more versatile and reusable code.
From b4bbe70e89ddf11d673ef2befa69d2c4de75e180 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 4 Apr 2024 22:16:14 +0530
Subject: [PATCH 176/236] Update README.md
---
section_19/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section_19/README.md b/section_19/README.md
index cc0e262..d7eb523 100644
--- a/section_19/README.md
+++ b/section_19/README.md
@@ -1,7 +1,7 @@
# Generics in Java π
Generics in Java are a powerful feature that allow you to write code that can work with different types while providing compile-time type safety. They were introduced in Java 5 to enable developers to create classes, interfaces, and methods that operate on a wide range of data types without sacrificing type safety.
## Why we need Generics in java
-Generics in Java serve several important purposes:
+Generics in Java serve several important purposes :
**Type Safety :** Generics provide compile-time type checking, which helps catch type-related errors at compile time rather than runtime. This ensures that you cannot insert the wrong type of object into a generic container, reducing the likelihood of bugs and making code more robust.
From ddff7c2f929884a536fb6b5b7a0efc3f50df6014 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 5 Apr 2024 15:01:33 +0530
Subject: [PATCH 177/236] Create README.md
---
section_20/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_20/README.md
diff --git a/section_20/README.md b/section_20/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_20/README.md
@@ -0,0 +1 @@
+
From bf960a6b54cc331b14636ce6bfe02543e583f7eb Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 5 Apr 2024 15:42:39 +0530
Subject: [PATCH 178/236] Update README.md
---
section_20/README.md | 183 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 183 insertions(+)
diff --git a/section_20/README.md b/section_20/README.md
index 8b13789..8cc0fe2 100644
--- a/section_20/README.md
+++ b/section_20/README.md
@@ -1 +1,184 @@
+# Map in Java π
+In Java, a Map is an interface that represents a collection of key-value pairs. Each key in a Map must be unique, and it is used to retrieve its corresponding value. Map does not allow duplicate keys, but it allows duplicate values.
+
+There are several implementations of the Map interface in Java, including:
+
+**HashMap :** This implementation uses a hash table to store key-value pairs. It provides constant-time performance for basic operations (add, remove, get, contains), assuming the hash function disperses the elements properly among the buckets.
+
+**TreeMap :** This implementation maintains its keys in sorted order. It is based on a Red-Black tree, providing log(n) time complexity for most operations.
+
+**LinkedHashMap :** This implementation maintains the insertion order of the elements. It is implemented as a hash table with a linked list running through it, providing predictable iteration order.
+
+These are some of the common implementations of the Map interface in Java, each suited for different use cases based on factors such as performance, order preservation, and key type.
+## HashMap π
+HashMap is a part of the Java Collections Framework and provides a convenient way to store key-value pairs.
+### Features π
+**Add Key-Value Pair :** Demonstrates how to add key-value pairs to a HashMap.
+**Retrieve Value by Key :** Shows how to retrieve values by providing the corresponding key.
+**Update Value :** Illustrates updating the value associated with a key.
+**Remove Key-Value Pair :** Shows how to remove key-value pairs from the HashMap.
+**Iterate Over Entries :** Demonstrates how to iterate over all key-value pairs in the HashMap.
+### Example π‘
+Here's a simple example demonstrating the basic usage of the HashMap:
+
+```java
+import java.util.HashMap;
+
+public class DemoHashMap {
+ public static void main(String[] args) {
+ // Create a new HashMap
+ HashMap hashMap = new HashMap<>();
+
+ // Add key-value pairs
+ hashMap.put("apple", 10);
+ hashMap.put("banana", 20);
+ hashMap.put("orange", 15);
+
+ // Retrieve value by key
+ System.out.println("Value associated with 'banana': " + hashMap.get("banana"));
+
+ // Update value
+ hashMap.put("apple", 25);
+
+ // Remove key-value pair
+ hashMap.remove("orange");
+
+ // Iterate over entries
+ System.out.println("All entries in the HashMap:");
+ for (String key : hashMap.keySet()) {
+ System.out.println(key + ": " + hashMap.get(key));
+ }
+ }
+}
+```
+### Iterating HashMap using values
+```java
+import java.util.HashMap;
+import java.util.Map;
+
+public class DemoHashMap {
+ public static void main(String[] args) {
+ // Create a new HashMap
+ HashMap hashMap = new HashMap<>();
+
+ // Add key-value pairs
+ hashMap.put("apple", 10);
+ hashMap.put("banana", 20);
+ hashMap.put("orange", 15);
+
+ // Iterate over values
+ System.out.println("All values in the HashMap:");
+ for (Integer value : hashMap.values()) {
+ System.out.println(value);
+ }
+ }
+}
+```
+### Conclusion π
+In conclusion, this demo showcases the basic functionality of the HashMap data structure in Java. It covers adding key-value pairs, retrieving values by keys, updating values, removing key-value pairs, and iterating over entries. The provided example code serves as a starting point for understanding how to use HashMaps in your Java projects.
+## TreeMap π
+The `TreeMap` class in Java is a part of the Java Collections Framework and provides an efficient way to store key-value pairs in a sorted order based on the natural ordering of its keys or by a custom comparator.
+This demo will illustrate basic operations such as insertion, deletion, and retrieval of elements from a TreeMap.
+### Example
+
+```java
+import java.util.TreeMap;
+
+public class TreeMapDemo {
+ public static void main(String[] args) {
+ // Creating a TreeMap
+ TreeMap treeMap = new TreeMap<>();
+
+ // Inserting elements
+ treeMap.put(3, "Apple");
+ treeMap.put(1, "Banana");
+ treeMap.put(2, "Orange");
+
+ // Removing an element
+ treeMap.remove(2);
+
+ // Displaying TreeMap contents
+ System.out.println("TreeMap after operations: " + treeMap);
+ }
+}
+```
+### Conclusion π
+TreeMap in Java is a powerful data structure provided by the Java Collections Framework. It offers efficient storage of key-value pairs in a sorted order, either based on the natural ordering of its keys or using a custom comparator. The TreeMap provides logarithmic time complexity for most of its operations such as insertion, deletion, and retrieval, making it suitable for scenarios where sorted data and efficient search operations are required. With its versatility and performance characteristics, the TreeMap serves as a valuable tool for developers working on projects that involve the organization and manipulation of key-value data in a sorted manner.
+## LinkedHashMap π
+The `LinkedHashMap` class in Java is a part of the Java Collections Framework and extends the `HashMap` class. It maintains the insertion order of its elements, which means the order in which elements are inserted is preserved. Additionally, it also provides optional access-ordering, where the entries are ordered based on their access order.
+This demo will illustrate basic operations such as insertion, deletion, and retrieval of elements from a LinkedHashMap.
+#### Example
+```java
+import java.util.LinkedHashMap;
+
+public class LinkedHashMapDemo {
+ public static void main(String[] args) {
+ // Creating a LinkedHashMap
+ LinkedHashMap linkedHashMap = new LinkedHashMap<>();
+
+ // Inserting elements
+ linkedHashMap.put(3, "Apple");
+ linkedHashMap.put(1, "Banana");
+ linkedHashMap.put(2, "Orange");
+
+ // Removing an element
+ linkedHashMap.remove(2);
+
+ // Displaying LinkedHashMap contents
+ System.out.println("LinkedHashMap after operations: " + linkedHashMap);
+ }
+}
+```
+### Conclusion
+ LinkedHashMap in Java is a versatile data structure provided by the Java Collections Framework. It extends the HashMap class and maintains the insertion order of its elements, making it suitable for scenarios where the order of insertion needs to be preserved. Additionally, LinkedHashMap also offers optional access-ordering, allowing entries to be ordered based on their access patterns.
+
+The LinkedHashMap provides efficient performance for basic operations such as insertion, deletion, and retrieval of elements. It combines the features of a HashMap with the ability to maintain the insertion order, making it a valuable tool for developers working on projects that require both fast lookup operations and preservation of the order in which elements are added.
+
+With its flexibility and performance characteristics, the LinkedHashMap is a useful choice for a wide range of applications, from implementing caches to maintaining ordered collections of data.
+## Creating Immutable Map Objects
+Immutable objects are objects whose state cannot be modified after they are created. In Java, immutable objects are useful for ensuring thread safety, simplifying code, and avoiding unexpected side effects. Immutable maps, in particular, are useful for representing fixed collections of key-value pairs.
+### Using Map.of()
+Starting from Java 9, you can create immutable map objects using the `Map.of()` method. This method provides a convenient way to create small immutable maps with up to 10 key-value pairs.
+
+```java
+import java.util.Map;
+
+public class ImmutableMapExample {
+ public static void main(String[] args) {
+ // Creating an immutable map with three key-value pairs
+ Map immutableMap = Map.of(
+ "key1", 1,
+ "key2", 2,
+ "key3", 3
+ );
+
+ // Attempting to modify the immutable map will result in an UnsupportedOperationException
+ // immutableMap.put("key4", 4); // This will throw UnsupportedOperationException
+ }
+}
+```
+### Using Map.ofEntries()
+If you need to create an immutable map with more than 10 key-value pairs, you can use the Map.ofEntries() method.
+
+```java
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class ImmutableMapExample {
+ public static void main(String[] args) {
+ // Creating an immutable map with more than 10 key-value pairs
+ Map immutableMap = Map.ofEntries(
+ Map.entry("key1", 1),
+ Map.entry("key2", 2),
+ Map.entry("key3", 3),
+ // Add more entries as needed
+ );
+
+ // Attempting to modify the immutable map will result in an UnsupportedOperationException
+ // immutableMap.put("key4", 4); // This will throw UnsupportedOperationException
+ }
+}
+```
+### Conclusion π
+Creating immutable map objects in Java using the `Map.of()` method provides a concise and convenient way to define fixed collections of `key-value` pairs. Whether you need a small map with up to 10 entries or a larger map with more entries, you can leverage these methods to ensure data integrity and thread safety in your applications.
From 9599edb5fdf1661038aba699cf1ebce13fc7fc3c Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 5 Apr 2024 15:43:50 +0530
Subject: [PATCH 179/236] Update README.md
---
section_20/README.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/section_20/README.md b/section_20/README.md
index 8cc0fe2..0357620 100644
--- a/section_20/README.md
+++ b/section_20/README.md
@@ -79,7 +79,7 @@ In conclusion, this demo showcases the basic functionality of the HashMap data s
## TreeMap π
The `TreeMap` class in Java is a part of the Java Collections Framework and provides an efficient way to store key-value pairs in a sorted order based on the natural ordering of its keys or by a custom comparator.
This demo will illustrate basic operations such as insertion, deletion, and retrieval of elements from a TreeMap.
-### Example
+### Example π‘
```java
import java.util.TreeMap;
@@ -107,7 +107,7 @@ TreeMap in Java is a powerful data structure provided by the Java Collections Fr
## LinkedHashMap π
The `LinkedHashMap` class in Java is a part of the Java Collections Framework and extends the `HashMap` class. It maintains the insertion order of its elements, which means the order in which elements are inserted is preserved. Additionally, it also provides optional access-ordering, where the entries are ordered based on their access order.
This demo will illustrate basic operations such as insertion, deletion, and retrieval of elements from a LinkedHashMap.
-#### Example
+#### Example π‘
```java
import java.util.LinkedHashMap;
@@ -129,7 +129,7 @@ public class LinkedHashMapDemo {
}
}
```
-### Conclusion
+### Conclusion π
LinkedHashMap in Java is a versatile data structure provided by the Java Collections Framework. It extends the HashMap class and maintains the insertion order of its elements, making it suitable for scenarios where the order of insertion needs to be preserved. Additionally, LinkedHashMap also offers optional access-ordering, allowing entries to be ordered based on their access patterns.
The LinkedHashMap provides efficient performance for basic operations such as insertion, deletion, and retrieval of elements. It combines the features of a HashMap with the ability to maintain the insertion order, making it a valuable tool for developers working on projects that require both fast lookup operations and preservation of the order in which elements are added.
From 0bd9b482e0a55d278b5fe677e891f8ce06d77f30 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 5 Apr 2024 15:46:23 +0530
Subject: [PATCH 180/236] Update README.md
---
section_20/README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/section_20/README.md b/section_20/README.md
index 0357620..4d08d69 100644
--- a/section_20/README.md
+++ b/section_20/README.md
@@ -182,3 +182,5 @@ public class ImmutableMapExample {
### Conclusion π
Creating immutable map objects in Java using the `Map.of()` method provides a concise and convenient way to define fixed collections of `key-value` pairs. Whether you need a small map with up to 10 entries or a larger map with more entries, you can leverage these methods to ensure data integrity and thread safety in your applications.
+Keep coding happily! π
+
From 393ec8f0f7aee2c35a443fddc4b3bf41491c4b4a Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 5 Apr 2024 15:48:12 +0530
Subject: [PATCH 181/236] Create README.md
---
section_21/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_21/README.md
diff --git a/section_21/README.md b/section_21/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_21/README.md
@@ -0,0 +1 @@
+
From 74f769c1d8d4061d39cbd533f43c0d895141aeb4 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Fri, 5 Apr 2024 22:12:28 +0530
Subject: [PATCH 182/236] Update README.md
---
section_21/README.md | 274 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 274 insertions(+)
diff --git a/section_21/README.md b/section_21/README.md
index 8b13789..19809b6 100644
--- a/section_21/README.md
+++ b/section_21/README.md
@@ -1 +1,275 @@
+# Set in Java π
+n Java, a Set is a collection that cannot contain duplicate elements. It models the mathematical set abstraction and provides methods to perform set operations such as union, intersection, and difference. Sets do not guarantee the order of elements, and they typically do not have methods to access elements by index.
+
+Java provides several implementations of the Set interface, including HashSet, TreeSet, and LinkedHashSet.
+
+
+**HashSet :** It stores elements using a hash table, which provides constant-time performance for basic operations like add, remove, and contains, assuming a good hash function is used. However, it does not maintain the insertion order of elements.
+
+**TreeSet :** It maintains elements in sorted order (according to their natural ordering or a custom Comparator provided at construction time). It is implemented as a red-black tree, providing guaranteed `log(n)` time cost for the basic operations.
+
+**LinkedHashSet :** It maintains the insertion order of elements, in addition to providing the Set interface's functionalities. It achieves this by using a doubly linked list internally.
+## HashSet π
+HashSet is a part of the Java Collections Framework and provides an unordered collection of unique elements.
+### Example π‘
+
+Here's a simple example demonstrating the usage of HashSet:
+
+```java
+import java.util.HashSet;
+
+public class HashSetDemo {
+ public static void main(String[] args) {
+ // Creating a HashSet
+ HashSet fruits = new HashSet<>();
+
+ // Adding elements to the HashSet
+ fruits.add("Apple");
+ fruits.add("Banana");
+ fruits.add("Orange");
+
+ // Displaying the HashSet
+ System.out.println("HashSet: " + fruits);
+
+ // Adding a duplicate element
+ fruits.add("Apple");
+
+ // Displaying the HashSet after adding a duplicate element
+ System.out.println("HashSet after adding duplicate element: " + fruits);
+
+ // Removing an element
+ fruits.remove("Banana");
+
+ // Displaying the HashSet after removing an element
+ System.out.println("HashSet after removing an element: " + fruits);
+
+ // Checking if an element exists
+ System.out.println("Does HashSet contain Orange? " + fruits.contains("Orange"));
+
+ // Clearing the HashSet
+ fruits.clear();
+
+ // Displaying the HashSet after clearing
+ System.out.println("HashSet after clearing: " + fruits);
+ }
+}
+```
+Output:
+```java
+HashSet: [Apple, Orange, Banana]
+HashSet after adding duplicate element: [Apple, Orange, Banana]
+HashSet after removing an element: [Apple, Orange]
+Does HashSet contain Orange? true
+HashSet after clearing: []
+```
+### Iterating HashSet
+### Using Iterator:
+```java
+import java.util.HashSet;
+import java.util.Iterator;
+
+public class HashSetIteration {
+ public static void main(String[] args) {
+ HashSet set = new HashSet<>();
+
+ // Adding elements to the HashSet
+ set.add("Apple");
+ set.add("Banana");
+ set.add("Orange");
+
+ // Iterating through the HashSet using Iterator
+ Iterator iterator = set.iterator();
+ while (iterator.hasNext()) {
+ String element = iterator.next();
+ System.out.println(element);
+ }
+ }
+}
+```
+### Using Enhanced For Loop:
+```java
+import java.util.HashSet;
+
+public class HashSetIteration {
+ public static void main(String[] args) {
+ HashSet set = new HashSet<>();
+
+ // Adding elements to the HashSet
+ set.add("Apple");
+ set.add("Banana");
+ set.add("Orange");
+
+ // Iterating through the HashSet using enhanced for loop
+ for (String element : set) {
+ System.out.println(element);
+ }
+ }
+}
+```
+### Conclusion π
+In conclusion, HashSet in Java provides a powerful and efficient way to store unique elements. It offers constant-time performance for basic operations like adding, removing, and checking for the presence of elements. HashSet is based on a hash table data structure, which ensures fast retrieval and storage of elements.
+
+Here are some key points to remember about HashSet:
+
+Unique Elements: HashSet does not allow duplicate elements. It ensures that each element is unique within the set.
+
+**Hashing :** HashSet uses hashing to store elements. This ensures that elements are distributed evenly across the internal data structure, providing fast access and retrieval.
+
+**Performance :** HashSet offers constant-time performance for basic operations, such as add, remove, and contains, making it ideal for scenarios where fast access to unique elements is required.
+
+**No Ordering :** HashSet does not maintain any order of elements. Elements are stored based on their hash codes, and the order of insertion is not preserved.
+
+**Iterating :** While HashSet does not provide any specific order of iteration, you can iterate through the elements using an iterator or enhanced for loop.
+
+**Concurrency :** HashSet is not thread-safe. If multiple threads need to access a HashSet concurrently, external synchronization is required.
+
+**Null Elements :** HashSet allows the insertion of a single null element.
+
+HashSet is part of the Java Collections Framework and is widely used in various applications where a collection of unique elements is required.
+
+In summary, HashSet in Java is a versatile and efficient data structure for storing unique elements, offering excellent performance and ease of use for developers.
+## TreeSet π
+`TreeSet` is a part of the Java Collections Framework and implements the `Set` interface. It provides an ordered collection of unique elements, where the elements are stored in a sorted tree structure.
+
+In this demo, we'll cover the following:
+- Creating a TreeSet
+- Adding elements to the TreeSet
+- Removing elements from the TreeSet
+- Performing basic operations like checking for element existence and getting the size of the TreeSet
+### Example π‘
+```java
+import java.util.*;
+
+public class TreeSetDemo {
+ public static void main(String[] args) {
+ // Create a TreeSet
+ TreeSet treeSet = new TreeSet<>();
+
+ // Adding elements
+ treeSet.add("Apple");
+ treeSet.add("Banana");
+ treeSet.add("Orange");
+
+ // Displaying the TreeSet
+ System.out.println("TreeSet: " + treeSet);
+
+ // Removing an element
+ treeSet.remove("Banana");
+
+ // Displaying the TreeSet after removal
+ System.out.println("TreeSet after removal: " + treeSet);
+
+ // Checking if an element exists
+ System.out.println("Contains Orange? " + treeSet.contains("Orange"));
+
+ // Getting the size of the TreeSet
+ System.out.println("Size of TreeSet: " + treeSet.size());
+
+ // Iterate over the TreeSet using Iterator
+ Iterator iterator = treeSet.iterator();
+ while (iterator.hasNext()) {
+ String element = iterator.next();
+ System.out.println(element);
+ }
+
+ // Iterate over the TreeSet using Enhanced For Loop
+ for (String element : treeSet) {
+ System.out.println(element);
+ }
+ }
+}
+```
+### Conclusion π
+TreeSet class in Java is a powerful implementation of the Set interface that provides a sorted set of unique elements. Here's a summary of its key features and advantages:
+
+**Ordered Collection :** TreeSet maintains elements in sorted order, according to their natural ordering or a specified comparator.
+
+**Unique Elements :** Like other implementations of the Set interface, TreeSet ensures that it contains only unique elements. Duplicate elements are automatically discarded.
+
+**Efficient Operations :** TreeSet offers efficient performance for basic operations such as insertion, deletion, and searching, with time complexity of O(log n) for most operations.
+
+**Useful in Sorted Operations :** Its sorted nature makes TreeSet particularly useful for scenarios where elements need to be maintained in sorted order, such as when retrieving elements in a specific order.
+
+**Backed by Red-Black Tree :** Internally, a TreeSet is backed by a Red-Black Tree, which is a self-balancing binary search tree. This ensures efficient insertion, deletion, and retrieval operations.
+
+**Iterating Elements :** TreeSet provides various methods for iterating over its elements, including iterators, enhanced for loops, and Java 8 streams.
+
+When using a TreeSet, it's important to consider the overhead of maintaining the sorted order, especially for large data sets. Additionally, the choice of comparator or relying on natural ordering can affect the behavior and performance of the TreeSet.
+
+Overall, TreeSet is a versatile and efficient data structure for maintaining a sorted set of unique elements, making it a valuable tool in Java programming, especially when ordered collections are required.
+## LinkedHashSet π
+LinkedHashSet is a part of the Java Collections Framework that extends HashSet, providing a linked-list implementation of the Set interface. It maintains the insertion order of elements, which means that when you iterate through a LinkedHashSet using an iterator, the elements are returned in the order in which they were inserted.
+
+### Features π
+**Insertion Order :** LinkedHashSet maintains the order in which elements are inserted.
+**No Duplicate Elements :** Like HashSet, LinkedHashSet does not allow duplicate elements.
+**Backed by a Hash Table :** Internally, it uses a hash table for storing elements, providing constant-time performance for basic operations such as add, remove, contains, and size.
+### Usage π
+Initialization
+```java
+// Creating a LinkedHashSet of String type
+LinkedHashSet linkedHashSet = new LinkedHashSet<>();
+
+// Adding elements to the LinkedHashSet
+linkedHashSet.add("Apple");
+linkedHashSet.add("Banana");
+linkedHashSet.add("Orange");
+```
+### Iteration
+```java
+// Iterating through the LinkedHashSet
+for (String element : linkedHashSet) {
+ System.out.println(element);
+}
+```
+### Removing an Element
+```java
+// Removing an element from the LinkedHashSet
+linkedHashSet.remove("Banana");
+```
+### Checking if an Element Exists
+```java
+// Checking if an element exists in the LinkedHashSet
+boolean exists = linkedHashSet.contains("Orange");
+```
+### Size of LinkedHashSet
+```java
+// Getting the size of the LinkedHashSet
+int size = linkedHashSet.size();
+```
+### Advantages over HashSet π
+- **Preserves Insertion Order :** LinkedHashSet preserves the order of elements insertion while HashSet does not.
+- **Faster Iteration :** Iterating through a LinkedHashSet is generally faster compared to a HashSet because of its linked-list implementation.
+### Limitations π«
+- **Higher Memory Consumption :** LinkedHashSet consumes slightly more memory than HashSet because it maintains a doubly-linked list in addition to the hash table.
+### When to Use
+- Use LinkedHashSet when you need to maintain the order of insertion.
+- If you require fast iteration over the elements and you don't have a concern about memory consumption, LinkedHashSet is a good choice.
+## Creating Immutable Sets
+Immutable sets in Java are sets whose contents cannot be changed after they are created. This ensures that once a set is created, its elements cannot be added, removed, or modified. Immutable sets are useful in scenarios where you want to guarantee that the data remains constant throughout the program execution.
+### 1. Using `Collections.unmodifiableSet()`
+This technique involves using the `Collections.unmodifiableSet()` method to create an immutable wrapper around an existing set.
+```java
+import java.util.*;
+
+public class ImmutableSetExample {
+ public static void main(String[] args) {
+ Set mutableSet = new HashSet<>();
+ mutableSet.add("apple");
+ mutableSet.add("banana");
+ mutableSet.add("orange");
+
+ Set immutableSet = Collections.unmodifiableSet(mutableSet);
+
+ // Any attempt to modify immutableSet will throw UnsupportedOperationException
+ // immutableSet.add("grape"); // This will throw UnsupportedOperationException
+ }
+}
+```
+### Advantages of Immutable Sets
+**Thread-safe :** Immutable sets are inherently thread-safe because their contents cannot be modified after creation.
+**Security :** Immutable sets prevent accidental or malicious modification of data.
+**Performance :** Immutable sets can be optimized by the compiler and runtime environment, leading to better performance in certain scenarios.
+### Conclusion
+Creating immutable sets in Java ensures data integrity and can simplify concurrent programming. Choose the technique that best fits your requirements and coding style.
From 8fd1c180951a3035007f80366b5bfdd836b3226c Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 8 Apr 2024 12:10:51 +0530
Subject: [PATCH 183/236] Create README.md
---
section_22/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_22/README.md
diff --git a/section_22/README.md b/section_22/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_22/README.md
@@ -0,0 +1 @@
+
From 47124f08a8194ea830dc393ea554f94813016be6 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 8 Apr 2024 12:57:34 +0530
Subject: [PATCH 184/236] Update README.md
---
section_22/README.md | 203 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 203 insertions(+)
diff --git a/section_22/README.md b/section_22/README.md
index 8b13789..1425982 100644
--- a/section_22/README.md
+++ b/section_22/README.md
@@ -1 +1,204 @@
+# Enum in Java π
+In Java, an enum (short for "enumeration") is a special data type that enables a variable to be a set of predefined constants. These constants represent a fixed number of meaningful, named values that don't change during the execution of a program. Enums are particularly useful when you have a fixed set of options or states that a variable can have.
+## Why Enums are Introduced
+Enums were introduced in Java to provide a cleaner and safer way to represent fixed sets of constants. Before enums were introduced, developers often used integer constants or sets of static final variables to represent such sets. However, using integers or strings for this purpose could lead to errors and make the code less readable and maintainable.
+
+Enums provide several advantages over these older approaches:
+
+**Type Safety :** Enums are type-safe, meaning you can't assign arbitrary values to an enum variable. You are restricted to using only the constants defined within the enum type.
+
+**Readability :** Enums improve code readability because you can use meaningful names for the constants, which makes the code self-documenting.
+
+**Maintainability :** Since enums are self-contained types, adding, removing, or modifying constants is straightforward and doesn't require changes throughout your codebase.
+
+**Compiler Support :** The compiler can help catch errors related to the usage of enums, such as missing cases in switch statements, which can help prevent bugs.
+
+Overall, enums in Java provide a more robust and expressive way to represent fixed sets of constants, leading to more reliable and maintainable code.
+
+Sure, let's compare how enums improve code compared to using integer constants or strings with examples:
+
+### Integer Constants Approach:
+```java
+public class DayConstants {
+ public static final int SUNDAY = 0;
+ public static final int MONDAY = 1;
+ public static final int TUESDAY = 2;
+ // Other days...
+}
+public class Main {
+ public static void main(String[] args) {
+ int today = DayConstants.MONDAY;
+
+ switch (today) {
+ case DayConstants.MONDAY:
+ System.out.println("Today is Monday.");
+ break;
+ // Other cases for the rest of the days...
+ }
+ }
+}
+```
+With this approach, there's no inherent type safety; any integer can be assigned to today, even if it doesn't correspond to a valid day.
+
+### String Constants Approach:
+```java
+public class DayConstants {
+ public static final String SUNDAY = "Sunday";
+ public static final String MONDAY = "Monday";
+ public static final String TUESDAY = "Tuesday";
+ // Other days...
+}
+
+public class Main {
+ public static void main(String[] args) {
+ String today = DayConstants.MONDAY;
+
+ if (today.equals(DayConstants.MONDAY)) {
+ System.out.println("Today is Monday.");
+ }
+ // Other checks for the rest of the days...
+ }
+}
+```
+While this approach is more readable than using integers, it's still prone to errors if the wrong string is assigned to today.
+
+### Enum Approach:
+```java
+public enum Day {
+ SUNDAY,
+ MONDAY,
+ TUESDAY,
+ // Other days...
+}
+
+public class Main {
+ public static void main(String[] args) {
+ Day today = Day.MONDAY;
+
+ switch (today) {
+ case MONDAY:
+ System.out.println("Today is Monday.");
+ break;
+ // Other cases for the rest of the days...
+ }
+ }
+}
+```
+With enums, the code becomes more concise, readable, and type-safe. You can't assign anything other than one of the defined enum constants to today, reducing the chance of errors. Additionally, adding or removing days from the enum is straightforward and doesn't require changes to other parts of the code.
+## Associating Data to Enum
+In Java, you can associate data with each enum constant by adding instance variables and a constructor to the enum. Here's an example demonstrating how to associate data with enums:
+
+```java
+// Define an enum called "Day" representing days of the week
+public enum Day {
+ // Each enum constant can have associated data
+ SUNDAY("Sun"),
+ MONDAY("Mon"),
+ TUESDAY("Tue"),
+ WEDNESDAY("Wed"),
+ THURSDAY("Thu"),
+ FRIDAY("Fri"),
+ SATURDAY("Sat");
+
+ // Instance variable to hold the abbreviation of the day
+ private final String abbreviation;
+
+ // Constructor to initialize the abbreviation
+ Day(String abbreviation) {
+ this.abbreviation = abbreviation;
+ }
+
+ // Getter method to retrieve the abbreviation
+ public String getAbbreviation() {
+ return abbreviation;
+ }
+}
+
+// Using the enum
+public class Main {
+ public static void main(String[] args) {
+ // Accessing the associated data for each enum constant
+ System.out.println("Abbreviations of the days:");
+ for (Day day : Day.values()) {
+ System.out.println(day + ": " + day.getAbbreviation());
+ }
+ }
+}
+```
+In this example:
+
+- Each enum constant in the Day enum has an associated abbreviation stored as an instance variable.
+- The constructor `Day(String abbreviation)` initializes the abbreviation for each enum constant.
+- The `getAbbreviation()` method allows accessing the abbreviation associated with each enum constant.
+- In the `Main` class, we iterate through all enum constants using `Day.values()` and print their names along with their associated abbreviations.
+- This approach allows you to associate any type of data with each enum constant, providing flexibility and encapsulation within the enum type.
+## EnumSet in Java
+EnumSet is a specialized Set implementation in Java designed for use with enum types. It is part of the java.util package and provides a high-performance, type-safe way to work with a fixed set of enum constants.
+## Features
+- **Type Safety**: EnumSet ensures type safety by only allowing elements of the declared enum type.
+- **Efficient**: EnumSet is highly efficient and compact, especially for enum types with a small number of elements.
+- **Fast Operations**: Operations like add, remove, and contains are performed with constant time complexity, making EnumSet suitable for performance-critical applications.
+- **Iteration Order**: EnumSet iteration order matches the order in which the enum constants are declared.
+- **No Nulls**: EnumSet does not allow null elements.
+
+## Usage
+### Creating an EnumSet
+```java
+import java.util.EnumSet;
+
+public class Main {
+ enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
+
+ public static void main(String[] args) {
+ EnumSet weekdays = EnumSet.of(Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY, Day.THURSDAY, Day.FRIDAY);
+ System.out.println(weekdays); // Output: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY]
+ }
+}
+```
+### Operations
+```java
+EnumSet weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);
+
+// Adding an element
+weekend.add(Day.SATURDAY);
+
+// Removing an element
+weekend.remove(Day.SUNDAY);
+
+// Checking if an element exists
+boolean containsSunday = weekend.contains(Day.SUNDAY);
+
+// Checking the size of the EnumSet
+int size = weekend.size();
+
+// Iterating over the EnumSet
+for (Day day : weekend) {
+ System.out.println(day);
+}
+```
+### Important Notes
+**Immutable :** EnumSet is not immutable. However, it does not support adding elements of a different enum type after creation.
+**Not Thread-safe :** EnumSet is not thread-safe. If multiple threads access an EnumSet concurrently and at least one of the threads modifies the set structurally, it must be synchronized externally.
+### Conclusion
+EnumSet provides a lightweight, efficient, and type-safe way to work with enum constants in Java. It is particularly useful when dealing with a fixed set of enum values, offering fast operations and minimal memory overhead.
+
+## Advantages of Enum's
+**Type Safety :** Enums provide type safety, ensuring that only predefined enum constants can be assigned to variables of the enum type. This helps catch errors at compile time rather than runtime.
+
+**Readability and Clarity :** Enums enhance code readability by providing meaningful and self-descriptive names for constants. Instead of using arbitrary integers or strings to represent states or options, enums offer descriptive labels, making the code easier to understand and maintain.
+
+**Compile-Time Checking :** Since enum constants are known at compile time, any usage of enums is checked by the compiler for correctness. This prevents common programming errors such as passing invalid values or mistyping constants.
+
+**Singleton Pattern :** Enums can be used to implement the singleton design pattern, ensuring that only one instance of the enum constant exists within the JVM. This simplifies the implementation of singleton classes, reducing the risk of bugs related to thread safety and lazy initialization.
+
+**Iteration and Switch Statements :** Enums support iteration over their constants and can be used in switch statements. This makes code more concise and readable, especially when dealing with a fixed set of options or states.
+
+**Enhanced Functionality :** Enums in Java can have fields, constructors, methods, and even implement interfaces. This allows enums to encapsulate behavior and data associated with each constant, making them more powerful than simple sets of named constants.
+
+**Robustness :** Enums promote robust code by providing a clear contract for valid values. By restricting the possible values to a predefined set, enums reduce the likelihood of runtime errors due to unexpected inputs.
+
+**Integration with Libraries :** Many libraries and frameworks in Java leverage enums for configuration, state management, and defining constants. Using enums in your codebase aligns well with standard Java practices and facilitates integration with third-party libraries.
+
+
+
From 4e9e37e5b686d566a612a702a80cd887d64e9e9b Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 8 Apr 2024 17:27:59 +0530
Subject: [PATCH 185/236] Create README.md
---
section_23/README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section_23/README.md
diff --git a/section_23/README.md b/section_23/README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section_23/README.md
@@ -0,0 +1 @@
+
From 5ca1c7a80126c0573b8f4c5c25482d07d9bd39ee Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 8 Apr 2024 17:46:57 +0530
Subject: [PATCH 186/236] Update README.md
---
section_23/README.md | 62 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 62 insertions(+)
diff --git a/section_23/README.md b/section_23/README.md
index 8b13789..59bc9a3 100644
--- a/section_23/README.md
+++ b/section_23/README.md
@@ -1 +1,63 @@
+# Date and Time π
+Java offers comprehensive support for handling date and time through its built-in libraries in the `java.time` package. This package was introduced in Java 8 as part of the Java Date and Time API (JSR 310), providing a modern, flexible, and thread-safe API for working with dates and times.
+## Why new Date API introduced in Java 8 π€
+The new Date and Time API introduced in Java 8, also known as the `java.time` package, addressed several limitations and issues present in the older `java.util.Date` and `java.util.Calendar` classes. Here are some reasons why the new API was introduced:
+**Immutability :** Objects in the `java.time` package are immutable, meaning their state cannot be modified after creation. This ensures thread safety, simplifies concurrency, and reduces the risk of unintended side effects.
+**Clarity and Readability :** The new API provides clearer and more intuitive class names like `LocalDate`, `LocalTime`, and `ZonedDateTime`, making code more readable and expressive compared to the ambiguous `Date` and `Calendar` classes.
+
+**Null-Safe :** The old API had issues with null values and was prone to `NullPointerExceptions`. The new API is designed to handle null values more gracefully, reducing the risk of runtime errors.
+
+**Consistency :** The old API had inconsistent and error-prone methods for date and time manipulation. The new API provides consistent and comprehensive methods for various date and time operations, reducing the complexity of code and improving maintainability.
+
+**Interoperability :** The new API is designed to work seamlessly with other modern Java features such as lambdas, streams, and the java.time.temporal package. This improves interoperability and makes it easier to integrate date and time functionality with other parts of the Java ecosystem.
+
+**Localization Support :** The new API provides better support for internationalization and localization, allowing developers to format and parse dates and times according to different locales and languages.
+
+**Better Time Zone Handling :** The old API had limited support for time zones and often led to errors and inconsistencies when working with different time zones. The new API provides robust support for time zones, including the `ZoneId` and `ZonedDateTime` classes, making it easier to handle date and time calculations across different time zones.
+
+Overall, the introduction of the new Date and Time API in Java 8 aimed to address the shortcomings of the old API, providing a more modern, robust, and developer-friendly solution for working with dates and times in Java applications.
+
+## java.util.Date
+The `java.util.Date` class represents a specific instant in time, with millisecond precision. It is widely used in Java applications for handling dates and times. However, it's important to note that this class has been largely superseded by the `java.time` package in Java 8 and later versions. Nevertheless, understanding its usage can still be beneficial, especially when dealing with legacy codebases.
+### Example π‘
+
+Here's a simple example demonstrating some common operations with `java.util.Date`:
+
+```java
+import java.util.Date;
+
+public class DateDemo {
+ public static void main(String[] args) {
+ // Create a new Date object representing the current date and time
+ Date currentDate = new Date();
+
+ // Print the current date and time
+ System.out.println("Current Date and Time: " + currentDate);
+
+ // Get the milliseconds since January 1, 1970, 00:00:00 GMT
+ long milliseconds = currentDate.getTime();
+ System.out.println("Milliseconds since January 1, 1970: " + milliseconds);
+
+ // Set the time of the date object to a specific timestamp
+ Date specificDate = new Date(1617888000000L); // April 9, 2021, 00:00:00 GMT
+ System.out.println("Specific Date: " + specificDate);
+
+ // Compare two dates
+ if (currentDate.after(specificDate)) {
+ System.out.println("The current date is after the specific date.");
+ } else if (currentDate.before(specificDate)) {
+ System.out.println("The current date is before the specific date.");
+ } else {
+ System.out.println("The current date is equal to the specific date.");
+ }
+
+ // Check if a date is equal to another date
+ if (currentDate.equals(specificDate)) {
+ System.out.println("The current date is equal to the specific date.");
+ } else {
+ System.out.println("The current date is not equal to the specific date.");
+ }
+ }
+}
+```
From d2489387336878f07c9bbbe571493f66de6a10bb Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 8 Apr 2024 17:51:53 +0530
Subject: [PATCH 187/236] Update README.md
---
section_23/README.md | 60 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 60 insertions(+)
diff --git a/section_23/README.md b/section_23/README.md
index 59bc9a3..effaae8 100644
--- a/section_23/README.md
+++ b/section_23/README.md
@@ -61,3 +61,63 @@ public class DateDemo {
}
}
```
+## Date Formatting and Parsing using SimpleDateFormat
+Formatting dates involves converting a `Date` object into a string representation according to a specified pattern, while parsing dates involves converting a string representation of a date into a `Date` object.
+
+### Formatting Dates
+
+To format a date into a string representation, follow these steps:
+
+1. Create a `SimpleDateFormat` object with the desired date pattern.
+2. Call the `format()` method on the `SimpleDateFormat` object, passing the `Date` object you want to format.
+
+#### Example:
+```java
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+public class DateFormattingExample {
+ public static void main(String[] args) {
+ Date currentDate = new Date();
+ SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
+ String formattedDate = formatter.format(currentDate);
+ System.out.println("Formatted Date: " + formattedDate);
+ }
+}
+```
+
+### Parsing Dates
+To parse a string representation of a date into a Date object, follow these steps:
+
+- Create a `SimpleDateFormat` object with the date pattern matching the format of the string representation.
+- Call the `parse()` method on the `SimpleDateFormat` object, passing the string representation of the date.
+#### Example:
+
+```java
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+public class DateParsingExample {
+ public static void main(String[] args) {
+ String dateString = "08-04-2024 14:30:00";
+ SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
+ try {
+ Date parsedDate = formatter.parse(dateString);
+ System.out.println("Parsed Date: " + parsedDate);
+ } catch (ParseException e) {
+ e.printStackTrace();
+ }
+ }
+}
+```
+### Date Patterns
+You can use various patterns to format and parse dates according to your requirements. Some commonly used patterns include:
+
+- `dd` - Day of the month (01-31)
+- `MM` - Month in year (01-12)
+- `yyyy` - Year (e.g., 2024)
+- `HH` - Hour in day (00-23)
+- `mm` - Minute in hour (00-59)
+- `ss` - Second in minute (00-59)
+
From dfc9570381057e9a4632f4d3788df2ee72682510 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 8 Apr 2024 18:10:25 +0530
Subject: [PATCH 188/236] Update README.md
---
section_23/README.md | 176 ++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 174 insertions(+), 2 deletions(-)
diff --git a/section_23/README.md b/section_23/README.md
index effaae8..ef08afd 100644
--- a/section_23/README.md
+++ b/section_23/README.md
@@ -71,7 +71,7 @@ To format a date into a string representation, follow these steps:
1. Create a `SimpleDateFormat` object with the desired date pattern.
2. Call the `format()` method on the `SimpleDateFormat` object, passing the `Date` object you want to format.
-#### Example:
+#### Example π‘
```java
import java.text.SimpleDateFormat;
import java.util.Date;
@@ -91,7 +91,7 @@ To parse a string representation of a date into a Date object, follow these step
- Create a `SimpleDateFormat` object with the date pattern matching the format of the string representation.
- Call the `parse()` method on the `SimpleDateFormat` object, passing the string representation of the date.
-#### Example:
+#### Example π‘
```java
import java.text.ParseException;
@@ -120,4 +120,176 @@ You can use various patterns to format and parse dates according to your require
- `HH` - Hour in day (00-23)
- `mm` - Minute in hour (00-59)
- `ss` - Second in minute (00-59)
+## java.sql.Date
+`java.sql.Date` is a class in the Java API that represents a specific instant in time, with millisecond precision, corresponding to SQL `DATE` format. It's a part of the java.sql package, primarily used for database operations where you need to work with dates without time components.
+
+### Features
+**Simple Demo :** Demonstrates basic usage of `java.sql.Date`.
+**Input Validation :** Validates user input for date values.
+**Database Interaction :** Illustrates how `java.sql.Date` can be used in JDBC for database operations.
+### Requirements
+- Java Development Kit (JDK) 8 or higher.
+- Any IDE or text editor for Java development.
+- JDBC driver for your database (if you intend to interact with a database).
+#### Example π‘
+```java
+import java.sql.Date;
+import java.time.LocalDate;
+
+public class Main {
+ public static void main(String[] args) {
+ // Create a java.sql.Date object representing today's date
+ Date today = new Date(System.currentTimeMillis());
+
+ // Display today's date
+ System.out.println("Today's date: " + today);
+
+ // Add 5 days to today's date
+ Date futureDate = addDays(today, 5);
+ System.out.println("Date after adding 5 days: " + futureDate);
+
+ // Subtract 2 months from today's date
+ Date pastDate = subtractMonths(today, 2);
+ System.out.println("Date after subtracting 2 months: " + pastDate);
+
+ // Check if today's date is before a specific date
+ Date comparisonDate = Date.valueOf("2024-05-01");
+ boolean isBefore = isBefore(today, comparisonDate);
+ System.out.println("Is today's date before " + comparisonDate + "? " + isBefore);
+ }
+
+ // Method to add days to a given date
+ private static Date addDays(Date date, int days) {
+ LocalDate localDate = date.toLocalDate().plusDays(days);
+ return Date.valueOf(localDate);
+ }
+
+ // Method to subtract months from a given date
+ private static Date subtractMonths(Date date, int months) {
+ LocalDate localDate = date.toLocalDate().minusMonths(months);
+ return Date.valueOf(localDate);
+ }
+
+ // Method to check if one date is before another date
+ private static boolean isBefore(Date date1, Date date2) {
+ return date1.before(date2);
+ }
+}
+```
+This example demonstrates adding days, subtracting months, and comparing dates using `java.sql.Date`. Note that java.sql.Date extends `java.util.Date`, so you can use all the methods available in `java.util.Date` as well.
+
+### Conclusion π
+In conclusion, the java.sql.Date class in Java is a useful tool for handling date values in applications, particularly in scenarios involving database operations. This demonstration showcased its basic functionalities, including creating instances, performing date arithmetic operations, and comparing dates.
+
+Key takeaways from this example include:
+
+**Creation of Date Instances :** You can create java.sql.Date instances representing specific dates or the current system date.
+
+**Date Manipulations :** Operations such as adding days and subtracting months from a date are straightforward using methods like addDays and subtractMonths.
+
+**Date Comparison :** Comparing dates for order can be done easily with methods like isBefore.
+
+By leveraging these features, developers can effectively manage and manipulate date values in Java applications, ensuring accurate and reliable handling of temporal data.
+## java.util.Calendar
+`java.util.Calendar` is an abstract class in Java that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week.
+
+### Features
+**Date Manipulation :** Allows manipulation of dates and time-related operations.
+**Locale-Sensitive :** Calendar computations are locale-sensitive and calendar systems are defined in the `java.util.Locale` class.
+**Time Zone Support :** Supports time zone computations and conversions.
+**Internationalization :** Provides support for internationalized date and time formats.
+### Example
+```java
+import java.util.Calendar;
+
+public class Main {
+ public static void main(String[] args) {
+ // Get a Calendar instance based on the current time in the default time zone and locale.
+ Calendar calendar = Calendar.getInstance();
+
+ // Get the current date and time
+ System.out.println("Current Date and Time: " + calendar.getTime());
+
+ // Set specific date and time fields
+ calendar.set(Calendar.YEAR, 2024);
+ calendar.set(Calendar.MONTH, Calendar.APRIL);
+ calendar.set(Calendar.DAY_OF_MONTH, 8);
+ calendar.set(Calendar.HOUR_OF_DAY, 15);
+ calendar.set(Calendar.MINUTE, 30);
+ calendar.set(Calendar.SECOND, 0);
+
+ // Get the modified date and time
+ System.out.println("Modified Date and Time: " + calendar.getTime());
+
+ // Perform operations like adding or subtracting days
+ calendar.add(Calendar.DAY_OF_MONTH, 7);
+
+ // Get the date after adding 7 days
+ System.out.println("Date after adding 7 days: " + calendar.getTime());
+ }
+}
+````
+### Calender class some operations
+### Get Current Date and Time:
+
+```java
+Calendar calendar = Calendar.getInstance();
+Date currentDate = calendar.getTime();
+System.out.println("Current Date and Time: " + currentDate);
+```
+### Set Specific Date and Time:
+
+```java
+calendar.set(Calendar.YEAR, 2024);
+calendar.set(Calendar.MONTH, Calendar.APRIL);
+calendar.set(Calendar.DAY_OF_MONTH, 8);
+calendar.set(Calendar.HOUR_OF_DAY, 15);
+calendar.set(Calendar.MINUTE, 30);
+calendar.set(Calendar.SECOND, 0);
+```
+### Add or Subtract Days/Months/Years:
+
+```java
+calendar.add(Calendar.DAY_OF_MONTH, 7); // Add 7 days
+calendar.add(Calendar.MONTH, -1); // Subtract 1 month
+calendar.add(Calendar.YEAR, 2); // Add 2 years
+```
+### Get Specific Date Components:
+
+```java
+int year = calendar.get(Calendar.YEAR);
+int month = calendar.get(Calendar.MONTH); // Month starts from 0 (January)
+int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
+int hour = calendar.get(Calendar.HOUR_OF_DAY);
+int minute = calendar.get(Calendar.MINUTE);
+int second = calendar.get(Calendar.SECOND);
+```
+### Get Day of the Week:
+
+```java
+int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // Sunday (1) to Saturday (7)
+```
+### Compare Dates:
+
+```java
+Calendar otherCalendar = Calendar.getInstance();
+otherCalendar.set(2024, Calendar.APRIL, 8);
+int comparison = calendar.compareTo(otherCalendar);
+// comparison < 0 if this calendar is before otherCalendar
+// comparison == 0 if this calendar is equal to otherCalendar
+// comparison > 0 if this calendar is after otherCalendar
+```
+### Check for Leap Year:
+
+```java
+boolean isLeapYear = calendar.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
+```
+### Clear Specific Fields:
+
+```java
+calendar.clear(Calendar.HOUR_OF_DAY);
+```
+
+
+
From 9385223fa7141558d2898a36288471e6821adf12 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 8 Apr 2024 22:22:10 +0530
Subject: [PATCH 189/236] Update README.md
---
section_23/README.md | 36 ++++++++++++++++++++++++++++++++++++
1 file changed, 36 insertions(+)
diff --git a/section_23/README.md b/section_23/README.md
index ef08afd..e484929 100644
--- a/section_23/README.md
+++ b/section_23/README.md
@@ -289,7 +289,43 @@ boolean isLeapYear = calendar.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
```java
calendar.clear(Calendar.HOUR_OF_DAY);
```
+These are just a few examples of the operations you can perform with java.util.Calendar. Depending on your requirements, you can use these methods to manipulate dates and times in various ways.
+## TimeZone specific Date and Time
+"TimeZone Specific Date and Time" refers to the representation of date and time information adjusted according to a specific geographical timezone. Timezones are regions of the Earth that have the same standard time. Since the Earth is divided into 24 time zones, each one corresponds to roughly 15 degrees of longitude, with local time being approximately one hour ahead of the previous timezone to the west.
+
+When dealing with time and date information in software applications, it's essential to consider timezones, especially when working with global audiences or handling data from different geographical locations. TimeZone Specific Date and Time involves:
+
+Specifying the Timezone: Identifying the geographical region or offset from Coordinated Universal Time (UTC) where the time and date are relevant. Timezone identifiers like "America/New_York" or "Europe/London" are commonly used.
+
+Converting Timezones: Transforming date and time values from one timezone to another. This is crucial when presenting data to users in different regions or when dealing with data stored in a standardized timezone.
+
+Accounting for Daylight Saving Time (DST): Some timezones observe DST, where the clocks are adjusted forward or backward by one hour during certain periods of the year. Handling DST changes accurately is essential for precise time calculations.
+
+In Java, the java.time package introduced in Java 8 provides robust support for working with `TimeZone` Specific Date and Time through classes like `ZonedDateTime`, `ZoneId`, and `OffsetDateTime`. These classes enable developers to handle timezones, convert between timezones, and perform various date and time operations while considering timezone information.
+### Example
+
+Here's a simple example demonstrating how to retrieve the current time and date in a specific timezone:
+
+```java
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+public class TimeZoneExample {
+
+ public static void main(String[] args) {
+ // Specify the timezone
+ ZoneId zoneId = ZoneId.of("America/New_York");
+
+ // Get the current time in the specified timezone
+ ZonedDateTime currentTime = ZonedDateTime.now(zoneId);
+
+ // Print the current time
+ System.out.println("Current time in New York: " + currentTime);
+ }
+}
+```
From e1c5bfccd22214e7bbbd958740240dcb904f56a6 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 9 Apr 2024 12:29:38 +0530
Subject: [PATCH 190/236] Create Section24
---
Section24 | 1 +
1 file changed, 1 insertion(+)
create mode 100644 Section24
diff --git a/Section24 b/Section24
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/Section24
@@ -0,0 +1 @@
+
From eb251dc36f32d24bb35a72948e80dba16c7328d9 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 9 Apr 2024 16:54:19 +0530
Subject: [PATCH 191/236] Update README.md
---
section_23/README.md | 276 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 276 insertions(+)
diff --git a/section_23/README.md b/section_23/README.md
index e484929..0e79d48 100644
--- a/section_23/README.md
+++ b/section_23/README.md
@@ -326,6 +326,282 @@ public class TimeZoneExample {
}
}
```
+## Java 8 Date and Time API
+### Introduction
+Java 8 introduced a new Date and Time API under the `java.time` package. This new API provides significant improvements over the old `java.util.Date` and `java.util.Calendar` classes, making date and time manipulation easier, more intuitive, and less error-prone.
+### Features
+### 1. Immutable Classes
+
+The Date and Time API introduces several immutable classes for representing date, time, and datetime values, such as `LocalDate`, `LocalTime`, and `LocalDateTime`. Immutable objects are inherently thread-safe and can simplify code by eliminating concerns about mutability.
+
+### 2. Separation of Concerns
+
+The API clearly separates date, time, and datetime representations, which simplifies development and reduces ambiguity. For example, you can work with just dates (`LocalDate`) or times (`LocalTime`) without needing to deal with both simultaneously.
+
+### 3. Comprehensive API
+
+The API provides a wide range of functionality for manipulating dates, times, and datetime values, including arithmetic operations, formatting and parsing, timezone support, and querying capabilities. Additionally, it offers support for leap years, daylight saving time, and other calendrical calculations.
+
+### 4. Timezone Support
+
+The Date and Time API includes classes such as `ZoneId` and `ZoneOffset` to handle timezones effectively. This makes it easier to work with dates and times in different regions of the world and to convert between different timezone representations.
+
+### 5. Fluent API Design
+
+The API is designed with a fluent and method-chaining style, which makes code more readable and expressive. Operations such as adding or subtracting time intervals, adjusting date and time values, and formatting output can be performed with concise and intuitive syntax.
+
+## Getting Started
+
+To start using the Java 8 Date and Time API in your project, ensure that you are using Java 8 or later, as this API is not available in earlier versions of Java.
+
+You can begin by importing the necessary classes from the `java.time` package into your Java source files:
+
+```java
+import java.time.LocalDate;
+import java.time.LocalTime;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+```
+Once imported, you can create instances of LocalDate, LocalTime, or LocalDateTime to represent specific dates, times, or datetime values. You can then perform various operations and manipulations using the methods provided by these classes.
+
+Here's a simple example demonstrating how to work with dates and times using the Java 8 Date and Time API:
+
+```java
+import java.time.LocalDate;
+import java.time.LocalTime;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+
+public class Main {
+ public static void main(String[] args) {
+ // Create instances of LocalDate, LocalTime, and LocalDateTime
+ LocalDate currentDate = LocalDate.now();
+ LocalTime currentTime = LocalTime.now();
+ LocalDateTime currentDateTime = LocalDateTime.now();
+
+ // Print the current date, time, and datetime
+ System.out.println("Current Date: " + currentDate);
+ System.out.println("Current Time: " + currentTime);
+ System.out.println("Current DateTime: " + currentDateTime);
+
+ // Format and print the current datetime
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+ String formattedDateTime = currentDateTime.format(formatter);
+ System.out.println("Formatted DateTime: " + formattedDateTime);
+ }
+}
+```
+
+## java.time Date and Time API - `of()` Methods
+The `java.time` package in Java provides a powerful API for handling date and time. One of the key features of this API is the `of()` method, which is used to create instances of various date and time objects.
+
+The `of()` method is a static factory method used to create instances of date and time objects in the `java.time` package. It is available in several classes, including `LocalDate`, `LocalTime`, `LocalDateTime`, `ZonedDateTime`, `OffsetDateTime`, `OffsetTime`, `Year`, `YearMonth`, `MonthDay`, `Duration`, and `Period`.
+
+### LocalDate
+
+```java
+LocalDate date = LocalDate.of(year, month, dayOfMonth);
+```
+
+### LocalTime
+```java
+LocalTime time = LocalTime.of(hour, minute);
+```
+### LocalDateTime
+```java
+LocalDateTime dateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute, second);
+```
+### ZonedDateTime
+```java
+ZonedDateTime zonedDateTime = ZonedDateTime.of(year, month, dayOfMonth, hour, minute, second, nano, zoneId);
+```
+### OffsetDateTime
+```java
+OffsetDateTime offsetDateTime = OffsetDateTime.of(year, month, dayOfMonth, hour, minute, second, nano, zoneOffset);
+```
+### OffsetTime
+```java
+OffsetTime offsetTime = OffsetTime.of(hour, minute, second, nano, zoneOffset);
+```
+### Year
+```java
+Year year = Year.of(year);
+```
+### YearMonth
+```java
+YearMonth yearMonth = YearMonth.of(year, month);
+```
+### MonthDay
+```java
+MonthDay monthDay = MonthDay.of(month, dayOfMonth);
+```
+### Duration
+```java
+Duration duration = Duration.ofDays(days).plusHours(hours).plusMinutes(minutes).plusSeconds(seconds).plusNanos(nanos);
+```
+### Period
+```java
+Period period = Period.ofYears(years).plusMonths(months).plusDays(days);
+```
+### Conclusion
+The of() methods in the java.time package provide a convenient way to create instances of date and time objects in Java. By using these methods, developers can easily work with dates, times, and durations in their applications.
+### `from()`
+```java
+LocalDate date = LocalDate.from(temporal);
+LocalTime time = LocalTime.from(temporal);
+LocalDateTime dateTime = LocalDateTime.from(temporal);
+ZonedDateTime zonedDateTime = ZonedDateTime.from(temporal);
+OffsetDateTime offsetDateTime = OffsetDateTime.from(temporal);
+OffsetTime offsetTime = OffsetTime.from(temporal);
+Year year = Year.from(temporal);
+YearMonth yearMonth = YearMonth.from(temporal);
+MonthDay monthDay = MonthDay.from(temporal);
+```
+### withXxx()
+```java
+LocalDate newDate = date.withYear(year);
+LocalTime newTime = time.withHour(hour);
+LocalDateTime newDateTime = dateTime.withMonth(month);
+ZonedDateTime newZonedDateTime = zonedDateTime.withDayOfMonth(dayOfMonth);
+OffsetDateTime newOffsetDateTime = offsetDateTime.withHour(hour);
+OffsetTime newOffsetTime = offsetTime.withMinute(minute);
+Year newYear = year.with(year);
+YearMonth newYearMonth = yearMonth.withMonth(month);
+MonthDay newMonthDay = monthDay.withDayOfMonth(dayOfMonth);
+```
+### Conclusion
+The `from()` and `withXxx()` methods in the java.time package provide additional flexibility for working with date and time objects in Java. By using these methods, developers can easily obtain instances of date and time objects from existing objects and manipulate their fields as needed.
+## toXxx() and atXxx()
+The `toXxx()` methods are used to convert date and time objects to other types, while the `atXxx()` methods are used to combine date and time objects with other temporal fields to create new instances.
+```java
+LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
+LocalDate localDate = zonedDateTime.toLocalDate();
+LocalTime localTime = zonedDateTime.toLocalTime();
+OffsetDateTime offsetDateTime = zonedDateTime.toOffsetDateTime();
+OffsetTime offsetTime = zonedDateTime.toOffsetTime();
+```
+## atXxx()
+```java
+LocalDateTime newLocalDateTime = localDate.atTime(localTime);
+ZonedDateTime newZonedDateTime = localDateTime.atZone(zoneId);
+ZonedDateTime newZonedDateTimeWithOffset = localDateTime.atZoneSameInstant(zoneId);
+OffsetDateTime newOffsetDateTime = localDateTime.atOffset(offset);
+```
+### Conclusion
+The `toXxx()` and `atXxx()` methods in the java.time package provide additional functionality for converting and combining date and time objects in Java. By using these methods, developers can easily work with different types of date and time representations and perform various temporal operations.
+
+## getXxx(), plusXxx() and minusXxx()
+The `getXxx()` methods are used to retrieve specific fields or values from date and time objects. The `plusXxx()` methods are used to add or subtract amounts of time to date and time objects, while the `minusXxx()` methods are used to subtract amounts of time.
+
+### `getXxx()`
+
+```java
+int year = localDate.getYear();
+Month month = localDate.getMonth();
+int dayOfMonth = localDate.getDayOfMonth();
+int hour = localTime.getHour();
+int minute = localTime.getMinute();
+int second = localTime.getSecond();
+```
+
+### plusXxx()
+```java
+LocalDateTime newDateTime = localDateTime.plusDays(daysToAdd);
+LocalDateTime newDateTimeWithPeriod = localDateTime.plus(period);
+```
+### minusXxx()
+```java
+LocalDateTime newDateTime = localDateTime.minusHours(hoursToSubtract);
+LocalDateTime newDateTimeWithDuration = localDateTime.minus(duration);
+```
+### Conclusion
+The `getXxx()`, `plusXxx()`, and `minusXxx()` methods in the java.time package provide additional functionality for working with date and time objects in Java. By using these methods, developers can easily retrieve specific fields, perform arithmetic operations, and manipulate date and time objects according to their requirements.
+
+## Instant
+
+The `Instant` class represents an instantaneous point on the time-line, typically used for converting between representations of the same instant in time. It's a point in time on the time-line, usually represented in UTC time. It's not affected by time zone or daylight saving time changes.
+
+```java
+```java
+Instant instant = Instant.now(); // Current instant
+Instant specificInstant = Instant.ofEpochSecond(epochSecond, nanoAdjustment);
+```
+## Duration
+The Duration class represents a time-based amount of time, such as "15 seconds" or "3 hours and 30 minutes". It can be used to measure the amount of time between two Instant objects.
+
+### Usage
+```java
+Duration duration = Duration.ofSeconds(seconds);
+Duration anotherDuration = Duration.ofMinutes(minutes).plusSeconds(seconds);
+```
+### Conclusion
+The `Instant` and `Duration` classes in the `java.time` package provide essential functionalities for dealing with time-based values in Java. By using these classes, developers can easily work with instants and measure time durations accurately in their applications.
+## Period
+
+The `Period` class represents a period of time with date-based values, such as years, months, and days. It can be used to measure the amount of time between two `LocalDate` objects or to manipulate date-based values.
+
+### Usage
+
+```java
+Period period = Period.ofYears(years).plusMonths(months).plusDays(days);
+Period anotherPeriod = Period.between(startDate, endDate);
+```
+
+### Conclusion
+The `Period` class in the `java.time` package provides essential functionalities for dealing with date-based periods in Java. By using this class, developers can easily work with date-based values and measure time durations accurately in their applications.
+
+## `multipliedBy()`
+
+The `multipliedBy()` method is used to multiply a time-based value by a scalar factor.
+
+```java
+Duration multipliedDuration = duration.multipliedBy(3);
+```
+## dividedBy()
+The dividedBy() method is used to divide a time-based value by a divisor.
+
+```java
+Duration dividedDuration = duration.dividedBy(2);
+```
+## negatedBy()
+The negatedBy() method is used to negate a time-based value.
+
+```java
+Duration negatedDuration = duration.negated();
+```
+### Conclusion
+The `multipliedBy()`, `dividedBy()`, and `negatedBy()` methods in the java.time package provide additional functionalities for performing arithmetic operations on time-based values in Java. By using these methods, developers can easily manipulate time durations according to their requirements.
+
+## `truncatedTo()`
+
+The `truncatedTo()` method is used to truncate a time-based value to a specified unit, such as hours, minutes, or seconds.
+
+```java
+LocalTime truncatedTime = time.truncatedTo(ChronoUnit.MINUTES);
+```
+### Conclusion
+The `truncatedTo()` method in the `java.time` package provides essential functionality for truncating time-based values to a specified unit in Java. By using this method, developers can easily adjust time values according to their requirements.
+
+## ZoneId
+
+The `ZoneId` class represents a time zone identifier. It can be used to represent a time zone in which rules are used to convert between instant and local date-time.
+
+### Usage
+
+```java
+ZoneId zoneId = ZoneId.of("Europe/Paris");
+```
+## ZonedDateTime
+The ZonedDateTime class represents a date-time with a time-zone in the ISO-8601 calendar system, such as "2024-04-09T12:34:56+02:00[Europe/Paris]".
+
+### Usage
+```java
+ZonedDateTime zonedDateTime = ZonedDateTime.now(); // Current date and time with default time zone
+ZonedDateTime specificZonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
+```
+### Conclusion
+The `ZoneId` and `ZonedDateTime` classes in the `java.time` package provide essential functionalities for dealing with time zones in Java. By using these classes, developers can easily work with date-times in different time zones and handle time zone conversions accurately in their applications.
+
From 1bc71d723347f92b59e4c9b35905997d6b4d6f34 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 9 Apr 2024 17:32:38 +0530
Subject: [PATCH 192/236] Update README.md
---
section_23/README.md | 45 +++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 44 insertions(+), 1 deletion(-)
diff --git a/section_23/README.md b/section_23/README.md
index 0e79d48..272d413 100644
--- a/section_23/README.md
+++ b/section_23/README.md
@@ -572,7 +572,7 @@ Duration negatedDuration = duration.negated();
### Conclusion
The `multipliedBy()`, `dividedBy()`, and `negatedBy()` methods in the java.time package provide additional functionalities for performing arithmetic operations on time-based values in Java. By using these methods, developers can easily manipulate time durations according to their requirements.
-## `truncatedTo()`
+## truncatedTo()
The `truncatedTo()` method is used to truncate a time-based value to a specified unit, such as hours, minutes, or seconds.
@@ -602,6 +602,49 @@ ZonedDateTime specificZonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
### Conclusion
The `ZoneId` and `ZonedDateTime` classes in the `java.time` package provide essential functionalities for dealing with time zones in Java. By using these classes, developers can easily work with date-times in different time zones and handle time zone conversions accurately in their applications.
+## ZoneOffset
+
+The `ZoneOffset` class represents a time zone offset from Greenwich/UTC, such as "+02:00" or "-05:00".
+
+### Usage
+
+```java
+ZoneOffset zoneOffset = ZoneOffset.of("+02:00");
+```
+### Conclusion
+The `ZoneOffset` class in the `java.time` package provides essential functionality for dealing with time zone offsets in Java. By using this class, developers can easily represent and work with time zone offsets accurately in their applications.
+
+## OffsetDateTime
+
+The `OffsetDateTime` class represents a date-time with an offset from UTC/Greenwich, such as "2024-04-09T12:34:56+02:00".
+
+### Usage
+
+```java
+OffsetDateTime offsetDateTime = OffsetDateTime.now(); // Current date-time with default offset
+OffsetDateTime specificOffsetDateTime = OffsetDateTime.of(localDateTime, zoneOffset);
+```
+## OffsetTime
+The OffsetTime class represents a time with an offset from UTC/Greenwich, such as "12:34:56+02:00".
+
+### Usage
+```java
+OffsetTime offsetTime = OffsetTime.now(); // Current time with default offset
+OffsetTime specificOffsetTime = OffsetTime.of(localTime, zoneOffset);
+```
+### Conclusion
+The OffsetDateTime and OffsetTime classes in the java.time package provide essential functionalities for dealing with date-time and time with offsets in Java. By using these classes, developers can easily work with date-times and times in specific offsets from UTC/Greenwich and handle time zone offsets accurately in their applications.
+
+
+
+
+
+
+
+
+
+
+
From a5fb29152c4b70bebd0aba17b20839137cc722cb Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 9 Apr 2024 17:45:07 +0530
Subject: [PATCH 193/236] Update README.md
---
section_23/README.md | 166 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 166 insertions(+)
diff --git a/section_23/README.md b/section_23/README.md
index 272d413..c6b805a 100644
--- a/section_23/README.md
+++ b/section_23/README.md
@@ -635,6 +635,172 @@ OffsetTime specificOffsetTime = OffsetTime.of(localTime, zoneOffset);
### Conclusion
The OffsetDateTime and OffsetTime classes in the java.time package provide essential functionalities for dealing with date-time and time with offsets in Java. By using these classes, developers can easily work with date-times and times in specific offsets from UTC/Greenwich and handle time zone offsets accurately in their applications.
+## Day Lught saving with ZonedDateTime
+```java
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+public class DaylightSavingDemo {
+ public static void main(String[] args) {
+ // Define a date-time before daylight saving time starts
+ LocalDateTime dateTimeBeforeDST = LocalDateTime.of(2024, 3, 10, 1, 30);
+
+ // Define a time zone
+ ZoneId zone = ZoneId.of("Europe/Paris");
+
+ // Create a ZonedDateTime for the given date-time and time zone
+ ZonedDateTime zonedDateTimeBeforeDST = ZonedDateTime.of(dateTimeBeforeDST, zone);
+
+ // Display the ZonedDateTime
+ System.out.println("ZonedDateTime before daylight saving time: " + zonedDateTimeBeforeDST);
+
+ // Define a date-time after daylight saving time starts
+ LocalDateTime dateTimeAfterDST = LocalDateTime.of(2024, 3, 10, 3, 30);
+
+ // Create a ZonedDateTime for the given date-time and time zone
+ ZonedDateTime zonedDateTimeAfterDST = ZonedDateTime.of(dateTimeAfterDST, zone);
+
+ // Display the ZonedDateTime
+ System.out.println("ZonedDateTime after daylight saving time: " + zonedDateTimeAfterDST);
+ }
+}
+```
+In this demo, we create two LocalDateTime objects representing two different times on the day when daylight saving time starts in Paris in 2024: one just before the clock moves forward and one just after. Then, we create ZonedDateTime objects using these LocalDateTime instances and the time zone Europe/Paris. Finally, we print out these ZonedDateTime instances.
+
+When you run this demo, you'll observe that the output shows the difference in the offset due to daylight saving time:
+
+```java
+ZonedDateTime before daylight saving time: 2024-03-10T01:30+01:00[Europe/Paris]
+ZonedDateTime after daylight saving time: 2024-03-10T03:30+02:00[Europe/Paris]
+```
+You can see that the offset changes from +01:00 to +02:00 when daylight saving time starts. This demonstrates how ZonedDateTime handles daylight saving time transitions automatically according to the specified time zone.
+
+Java's java.time API primarily focuses on the ISO calendar system, but it does provide support for other calendar systems through the java.time.chrono package. While the ISO calendar is widely used and recommended, other calendars such as the Hijrah (Islamic) calendar and the Japanese calendar are supported for specific use cases.
+
+Here's a brief overview of how you can work with non-ISO calendars in the java.time Date and Time API:
+
+Hijrah (Islamic) Calendar: You can work with the Hijrah calendar using the HijrahChronology class. This calendar is used primarily in Islamic countries and calculates dates based on lunar cycles.
+
+Japanese Calendar: The Japanese calendar is supported through the JapaneseChronology class. It is used in Japan and counts years based on the reigns of Japanese emperors.
+
+Here's a simple example demonstrating how to work with the Hijrah calendar:
+
+java
+Copy code
+import java.time.LocalDate;
+import java.time.chrono.HijrahChronology;
+import java.time.chrono.HijrahDate;
+import java.time.format.DateTimeFormatter;
+
+public class NonISOCalendarDemo {
+ public static void main(String[] args) {
+ // Create a LocalDate in the Hijrah calendar
+ LocalDate hijrahDate = LocalDate.of(1443, 8, 15); // Hijrah year 1443, Shawwal month, 15th day
+
+ // Convert to HijrahDate
+ HijrahDate hijrahDateConverted = HijrahChronology.INSTANCE.date(hijrahDate);
+
+ // Format and display the Hijrah date
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+ System.out.println("Hijrah Date: " + formatter.format(hijrahDateConverted));
+ }
+}
+This example creates a LocalDate object representing a date in the Hijrah calendar, converts it to a HijrahDate using HijrahChronology.INSTANCE, and then formats and displays the date.
+
+Similarly, you can work with the Japanese calendar by using JapaneseChronology in a similar manner.
+
+Keep in mind that support for non-ISO calendars may vary depending on the version of Java you're using, so be sure to consult the documentation for the specific version you're working with.
+
+## Formatting Dates and Times using DateTimeFormatter
+
+Formatting dates and times using the DateTimeFormatter class in Java allows you to represent date and time objects in various formats, such as "yyyy-MM-dd HH:mm:ss" or "MMM dd, yyyy hh:mm a".
+
+Here's a basic example demonstrating how to format dates and times using DateTimeFormatter:
+
+```java
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+
+public class DateTimeFormattingDemo {
+ public static void main(String[] args) {
+ // Create a LocalDateTime object representing the current date and time
+ LocalDateTime dateTime = LocalDateTime.now();
+
+ // Define a custom date and time format
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+
+ // Format the LocalDateTime object using the formatter
+ String formattedDateTime = dateTime.format(formatter);
+
+ // Display the formatted date and time
+ System.out.println("Formatted Date and Time: " + formattedDateTime);
+ }
+}
+```
+In this example:
+
+We create a LocalDateTime object representing the current date and time.
+We define a custom date and time format using the DateTimeFormatter.ofPattern() method. In this case, "yyyy-MM-dd HH:mm:ss" represents the format "year-month-day hour:minute:second".
+We format the LocalDateTime object using the defined formatter with the format() method.
+Finally, we print out the formatted date and time.
+Output:
+
+```sql
+Formatted Date and Time: 2024-04-10 15:30:45
+```
+You can create various formats by adjusting the pattern string passed to ofPattern(). Here are some commonly used pattern letters:
+
+
+- `y`: year
+- `M`: month
+- `d`: day of month
+- `H`: hour (0-23)
+- `m`: minute
+- `s`: second
+- `a`: AM/PM marker
+## Parsing dates and times using the DateTimeFormatter
+
+Parsing dates and times in Java using the DateTimeFormatter class allows you to convert textual representations of dates and times into LocalDate, LocalTime, LocalDateTime, or other date/time types provided by the java.time package.
+
+Here's a basic example demonstrating how to parse dates and times using DateTimeFormatter:
+
+```java
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+
+public class DateTimeParsingDemo {
+ public static void main(String[] args) {
+ // Define a date string in a specific format
+ String dateString = "2024-04-10";
+
+ // Define a custom date format
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+
+ // Parse the date string using the formatter
+ LocalDate date = LocalDate.parse(dateString, formatter);
+
+ // Display the parsed date
+ System.out.println("Parsed Date: " + date);
+ }
+}
+```
+In this example:
+
+We define a date string "2024-04-10" in the format "yyyy-MM-dd".
+We define a custom date format using the DateTimeFormatter.ofPattern() method.
+We parse the date string using the defined formatter with the parse() method, which returns a LocalDate object.
+Finally, we print out the parsed date.
+Output:
+
+```yaml
+Parsed Date: 2024-04-10
+```
+
+You can similarly parse time strings or combined date-time strings by using LocalTime.parse() or LocalDateTime.parse(), respectively. Just make sure the pattern in the DateTimeFormatter matches the format of the string you are trying to parse.
+
+If the input string does not match the specified format, a DateTimeParseException will be thrown. You can handle this exception using standard Java exception handling mechanisms.
+
From 22ef357db539742928671a3c1c26603956180bba Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 10 Apr 2024 15:22:11 +0530
Subject: [PATCH 194/236] Create section24.README.md
---
section24.README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section24.README.md
diff --git a/section24.README.md b/section24.README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section24.README.md
@@ -0,0 +1 @@
+
From 2dfc15b358d2b12bede29f9cef7669a810007757 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 10 Apr 2024 15:41:55 +0530
Subject: [PATCH 195/236] Update section24.README.md
---
section24.README.md | 92 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 92 insertions(+)
diff --git a/section24.README.md b/section24.README.md
index 8b13789..3b71b46 100644
--- a/section24.README.md
+++ b/section24.README.md
@@ -1 +1,93 @@
+# Functional programming using Lambda Expressions π
+Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. In functional programming, functions are first-class citizens, meaning they can be passed as arguments to other functions, returned as values from other functions, and assigned to variables.
+
+Key concepts in functional programming include:
+
+**Pure Functions :** Functions that produce output based only on their inputs, with no side effects. Given the same input, a pure function will always return the same output, making it easier to reason about and test.
+
+**Immutability :** Data structures, once created, cannot be modified. Instead of changing the state of existing data, functional programming encourages creating new data structures with the desired modifications.
+
+**Higher-order Functions :** Functions that can take other functions as arguments or return functions as results. This allows for powerful abstractions and concise code.
+
+**Recursion :** Recursion is often used instead of looping constructs like for or while loops. Functions call themselves with modified arguments until a base case is reached.
+
+**Referential Transparency :** The idea that an expression can be replaced with its value without changing the program's behavior. This facilitates reasoning about code and enables optimizations.
+
+**Functional Composition :** Combining smaller functions to create larger functions, often using techniques like function composition or chaining.
+
+**Lazy Evaluation :** Delaying the evaluation of an expression until its value is actually needed. This can improve performance and support infinite data structures.
+
+Languages that support functional programming include Haskell, Scala, Clojure, Erlang, and Lisp. However, many mainstream languages, such as JavaScript, Python, and Java, also incorporate functional programming features to varying degrees.
+
+# Lambda Expressions in Java
+
+Lambda expressions were introduced in Java 8 to provide a concise way to express instances of single-method interfaces (also known as functional interfaces). They enable you to treat functionality as a method argument or to create anonymous classes more concisely. Lambda expressions primarily aim to simplify the syntax needed to create anonymous inner classes.
+
+## What are Lambda Expressions?
+
+Lambda expressions, also known simply as lambdas, are anonymous methods (functions) that can be passed around and executed later. They allow you to treat functionality as a method argument or to create anonymous classes more concisely.
+
+## Syntax of Lambda Expressions
+
+The syntax of a lambda expression consists of three parts:
+
+1. **Parameters**: A lambda expression can have zero or more parameters. The type of each parameter can be explicitly declared or inferred.
+
+2. **Arrow token (->)**: It is used to separate the parameter list from the body of the lambda expression. It is also called the lambda operator.
+
+3. **Body**: It contains the code that defines the functionality of the lambda expression. It can consist of a single expression or a block of code.
+
+Here's the basic syntax:
+
+```java
+(parameters) -> expression
+```
+or
+
+```java
+(parameters) -> { statements; }
+```
+### Examples
+### 1. Lambda with No Parameters:
+```java
+() -> System.out.println("Hello Lambda!");
+```
+### 2. Lambda with Single Parameter:
+```java
+(x) -> x * x
+```
+### 3. Lambda with Multiple Parameters:
+```java
+(x, y) -> x + y
+```
+### 4. Lambda with Body:
+```java
+(x, y) -> {
+ int sum = x + y;
+ return sum;
+}
+```
+### 5. Lambda as Method Parameter:
+```java
+List names = Arrays.asList("Alice", "Bob", "Charlie");
+names.forEach(name -> System.out.println(name));
+```
+### Benefits of Lambda Expressions
+**Conciseness :** Lambda expressions reduce boilerplate code and make your code more readable by focusing on the actual functionality.
+
+**Improved Code Organization :** By allowing code to be passed around more flexibly, lambdas can promote a more modular and organized code structure.
+
+**Parallelism :** Lambdas facilitate writing code that can be executed in parallel using features like Java's Stream API.
+
+**Enhanced APIs :** Many new APIs introduced in Java 8 and later are designed to work seamlessly with lambdas, providing developers with more powerful and expressive tools.
+
+**Functional Programming Paradigm :** Lambda expressions encourage the use of functional programming paradigms, leading to cleaner, more declarative code.
+
+### Conclusion
+Lambda expressions are a powerful addition to the Java language, enabling developers to write more expressive and concise code. By understanding their syntax and benefits, you can leverage lambdas to make your Java code more efficient and maintainable.
+
+
+
+
+
From 64142db145469b3264d68707b7109f485bcc559b Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 10 Apr 2024 18:27:59 +0530
Subject: [PATCH 196/236] Update section24.README.md
---
section24.README.md | 122 +++++++++++++++++++++++++++++++++++++++++---
1 file changed, 115 insertions(+), 7 deletions(-)
diff --git a/section24.README.md b/section24.README.md
index 3b71b46..3c37e13 100644
--- a/section24.README.md
+++ b/section24.README.md
@@ -19,13 +19,11 @@ Key concepts in functional programming include:
Languages that support functional programming include Haskell, Scala, Clojure, Erlang, and Lisp. However, many mainstream languages, such as JavaScript, Python, and Java, also incorporate functional programming features to varying degrees.
-# Lambda Expressions in Java
-
-Lambda expressions were introduced in Java 8 to provide a concise way to express instances of single-method interfaces (also known as functional interfaces). They enable you to treat functionality as a method argument or to create anonymous classes more concisely. Lambda expressions primarily aim to simplify the syntax needed to create anonymous inner classes.
+## How to Build Lambda Expressions in Java
+Lambda expressions in Java are a powerful feature introduced in Java 8, allowing you to treat functionality as a method argument, or to create anonymous functions. This README provides a guide on how to build lambda expressions in Java.
## What are Lambda Expressions?
-
-Lambda expressions, also known simply as lambdas, are anonymous methods (functions) that can be passed around and executed later. They allow you to treat functionality as a method argument or to create anonymous classes more concisely.
+Lambda expressions introduce the concept of functional programming to Java. They allow you to treat functionality as a method argument, or to create anonymous functions. Lambda expressions are particularly useful when working with collections and streams, where you need to pass behavior as a parameter.
## Syntax of Lambda Expressions
@@ -47,7 +45,7 @@ or
```java
(parameters) -> { statements; }
```
-### Examples
+### Examples π‘
### 1. Lambda with No Parameters:
```java
() -> System.out.println("Hello Lambda!");
@@ -83,9 +81,119 @@ names.forEach(name -> System.out.println(name));
**Functional Programming Paradigm :** Lambda expressions encourage the use of functional programming paradigms, leading to cleaner, more declarative code.
-### Conclusion
+### Conclusion π
Lambda expressions are a powerful addition to the Java language, enabling developers to write more expressive and concise code. By understanding their syntax and benefits, you can leverage lambdas to make your Java code more efficient and maintainable.
+## Functional Interface
+Functional Interface in Java is an interface that contains only one abstract method. It can have any number of default or static methods but must contain exactly one abstract method. They are also known as Single Abstract Method (SAM) interfaces.
+
+Functional Interfaces play a crucial role in enabling functional programming features in Java, particularly with the introduction of lambda expressions in Java 8.
+
+## Usage
+
+To define a functional interface in Java, you can use the `@FunctionalInterface` annotation. This annotation is not mandatory, but it's recommended as it ensures the interface has only one abstract method.
+
+```java
+@FunctionalInterface
+interface MyFunctionalInterface {
+ void myMethod();
+}
+```
+Now, you can use this functional interface to create lambda expressions or method references
+
+
+```java
+public class Main {
+ public static void main(String[] args) {
+ // Using lambda expression
+ MyFunctionalInterface myLambda = () -> System.out.println("Hello from lambda");
+ myLambda.myMethod();
+
+ // Using method reference
+ MyFunctionalInterface myMethodRef = Main::someMethod;
+ myMethodRef.myMethod();
+ }
+
+ static void someMethod() {
+ System.out.println("Hello from method reference");
+ }
+}
+```
+
+### Characteristics
+Single Abstract Method (SAM): Functional interfaces must contain exactly one abstract method.
+@FunctionalInterface Annotation: While not mandatory, using this annotation helps to ensure that the interface is intended to be used as a functional interface.
+Lambda Expressions: Functional interfaces are often used with lambda expressions to provide concise implementations of the abstract method.
+Method References: Method references allow you to refer to methods or constructors without invoking them.
+### Examples
+Here are some common examples of functional interfaces in Java:
+
+- **Runnable :** Represents a task that can be executed.
+- **Callable :** Represents a task that returns a result and may throw an exception.
+- **Comparator :** Used to compare two objects.
+- **Supplier :** Provides a value without taking any input.
+- **Consumer :** Consumes a value without returning any result.
+- **Function :** Represents a function that accepts one argument and produces a result.
+### Benefits
+- **Concise Code :** Functional interfaces combined with lambda expressions allow for more concise and expressive code.
+- **Readability :** Lambda expressions can make the code more readable by focusing on what needs to be done rather than how it is done.
+- **Flexibility :** Functional interfaces provide flexibility in designing APIs, allowing methods to accept behaviors as parameters.
+### Conclusion
+Functional interfaces in Java enable functional programming paradigms by allowing the use of lambda expressions and method references. They provide a concise and expressive way to define behaviors, leading to cleaner and more maintainable code.
+
+## Functional Interface and Lambda Expressions
+Functional Interface and Lambda Expressions are two closely related concepts in Java, introduced in Java 8. They are instrumental in enabling functional programming paradigms within the language.
+### Functional Interface
+A Functional Interface in Java is an interface that contains exactly one abstract method. It may contain any number of default or static methods, but it must have exactly one abstract method. Functional interfaces are also known as Single Abstract Method (SAM) interfaces.
+
+Functional interfaces serve as the foundation for lambda expressions in Java. They provide a way to define the signature for lambda expressions.
+
+### Lambda Expressions
+
+Lambda Expressions, introduced in Java 8, provide a concise syntax for representing anonymous functions. They allow you to express instances of single-method interfaces (functional interfaces) more compactly.
+
+Lambda expressions are essentially a way to pass functionality as an argument to a method. They provide a clear and concise way to represent behavior without the need for verbose anonymous inner classes.
+
+Linking Functional Interfaces and Lambda Expressions
+
+Lambda expressions are intimately linked with functional interfaces in Java. When you use a lambda expression, you are essentially implementing the abstract method of a functional interface in a more concise and expressive way.
+
+Let's take a look at an example:
+
+```java
+// Functional Interface
+@FunctionalInterface
+interface MyFunctionalInterface {
+ void myMethod();
+}
+
+public class Main {
+ public static void main(String[] args) {
+ // Lambda Expression
+ MyFunctionalInterface myLambda = () -> System.out.println("Hello from lambda");
+ myLambda.myMethod();
+ }
+}
+```
+In the example above:
+
+We define a functional interface MyFunctionalInterface with a single abstract method myMethod().
+We then create a lambda expression () -> System.out.println("Hello from lambda"), which represents an instance of MyFunctionalInterface.
+Finally, we invoke the myMethod() using the lambda expression.
+This demonstrates how lambda expressions can be used to implement the abstract method of a functional interface concisely.
+
+### Benefits
+The linking of functional interfaces and lambda expressions in Java provides several benefits:
+
+**Concise Syntax :** Lambda expressions allow for more concise and readable code compared to anonymous inner classes.
+**Functional Programming :** Enables functional programming paradigms in Java by providing a way to pass behavior as an argument to methods.
+**Improved Expressiveness :** Enhances code expressiveness by focusing on what needs to be done rather than how it is done.
+**Flexibility :** Provides flexibility in designing APIs by allowing methods to accept behaviors as parameters.
+### Conclusion
+Functional interfaces and lambda expressions in Java are closely linked concepts that enable functional programming paradigms within the language. By using lambda expressions, you can implement the abstract methods of functional interfaces concisely and expressively, leading to cleaner and more maintainable code.
+
+
+
From 85dc7b174a8fd85576e55dce16f8eadcb7316248 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 10 Apr 2024 19:14:17 +0530
Subject: [PATCH 197/236] Update section24.README.md
---
section24.README.md | 162 +++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 159 insertions(+), 3 deletions(-)
diff --git a/section24.README.md b/section24.README.md
index 3c37e13..400c529 100644
--- a/section24.README.md
+++ b/section24.README.md
@@ -125,7 +125,7 @@ Single Abstract Method (SAM): Functional interfaces must contain exactly one abs
@FunctionalInterface Annotation: While not mandatory, using this annotation helps to ensure that the interface is intended to be used as a functional interface.
Lambda Expressions: Functional interfaces are often used with lambda expressions to provide concise implementations of the abstract method.
Method References: Method references allow you to refer to methods or constructors without invoking them.
-### Examples
+### Examples π‘
Here are some common examples of functional interfaces in Java:
- **Runnable :** Represents a task that can be executed.
@@ -138,7 +138,7 @@ Here are some common examples of functional interfaces in Java:
- **Concise Code :** Functional interfaces combined with lambda expressions allow for more concise and expressive code.
- **Readability :** Lambda expressions can make the code more readable by focusing on what needs to be done rather than how it is done.
- **Flexibility :** Functional interfaces provide flexibility in designing APIs, allowing methods to accept behaviors as parameters.
-### Conclusion
+### Conclusion π
Functional interfaces in Java enable functional programming paradigms by allowing the use of lambda expressions and method references. They provide a concise and expressive way to define behaviors, leading to cleaner and more maintainable code.
## Functional Interface and Lambda Expressions
@@ -189,9 +189,165 @@ The linking of functional interfaces and lambda expressions in Java provides sev
**Functional Programming :** Enables functional programming paradigms in Java by providing a way to pass behavior as an argument to methods.
**Improved Expressiveness :** Enhances code expressiveness by focusing on what needs to be done rather than how it is done.
**Flexibility :** Provides flexibility in designing APIs by allowing methods to accept behaviors as parameters.
-### Conclusion
+### Conclusion π
Functional interfaces and lambda expressions in Java are closely linked concepts that enable functional programming paradigms within the language. By using lambda expressions, you can implement the abstract methods of functional interfaces concisely and expressively, leading to cleaner and more maintainable code.
+## Using Anonymous Inner Class in Place of Lambda Expression in Java
+In Java, lambda expressions provide a concise way to express instances of single-method interfaces (also known as functional interfaces). However, before the introduction of lambda expressions in Java 8, anonymous inner classes were used to achieve similar functionality. This README aims to explain how to use anonymous inner classes in place of lambda expressions.
+
+### Anonymous Inner Class
+An anonymous inner class is a class defined inline without a name. It is typically used when you need to create an instance of a class that will be used only once and don't want to create a separate class for it.
+
+### Lambda Expressions
+Lambda expressions, introduced in Java 8, are used to represent instances of functional interfaces. They provide a concise way to write anonymous functions, making your code more readable and maintainable.
+
+### Using Anonymous Inner Class Instead of Lambda Expression
+To demonstrate using an anonymous inner class instead of a lambda expression, consider the following example where we have a functional interface MathOperation with a single method calculate(int a, int b):
+
+```java
+public interface MathOperation {
+ int calculate(int a, int b);
+}
+Using Lambda Expression
+java
+Copy code
+public class Main {
+ public static void main(String[] args) {
+ MathOperation addition = (a, b) -> a + b;
+ System.out.println("Result: " + addition.calculate(10, 5));
+ }
+}
+```
+In this code, the lambda expression `(a, b) -> a + b` represents the calculate method of the MathOperation interface.
+
+### Using Anonymous Inner Class
+```java
+public class Main {
+ public static void main(String[] args) {
+ MathOperation addition = new MathOperation() {
+ @Override
+ public int calculate(int a, int b) {
+ return a + b;
+ }
+ };
+ System.out.println("Result: " + addition.calculate(10, 5));
+ }
+}
+```
+In this code, we've used an anonymous inner class to implement the MathOperation interface.
+
+### Conclusion π
+While lambda expressions offer a more concise syntax for representing instances of functional interfaces, anonymous inner classes can still be used in Java to achieve the same functionality. Depending on the context and readability concerns, you may choose between lambda expressions and anonymous inner classes.
+
+## Predefined Functional Interfaces in Java Development Kit (JDK)
+Functional interfaces, introduced in Java 8, are interfaces that have only one abstract method. They are a key feature of Java's support for functional programming. The JDK provides several predefined functional interfaces in the java.util.function package to support common functional programming idioms.
+
+### List of Predefined Functional Interfaces
+Here are some of the commonly used predefined functional interfaces in the JDK:
+
+### 1. Predicate
+Represents a predicate (boolean-valued function) of one argument.
+
+### 2. Function
+Represents a function that accepts one argument and produces a result.
+
+### 3. Consumer
+Represents an operation that accepts a single input argument and returns no result.
+
+### 4. Supplier
+Represents a supplier of results.
+
+### 5. UnaryOperator
+Represents an operation on a single operand that produces a result of the same type as its operand.
+
+### 6. BinaryOperator
+Represents an operation upon two operands of the same type, producing a result of the same type as the operands.
+
+### Usage Examples
+Here are some examples demonstrating the usage of these predefined functional interfaces:
+
+### 1. Predicate
+```java
+Predicate isLong = str -> str.length() > 5;
+System.out.println(isLong.test("Hello")); // Output: false
+System.out.println(isLong.test("Hello World")); // Output: true
+```
+### 2. Function
+```java
+Function intToString = num -> "Number: " + num;
+System.out.println(intToString.apply(42)); // Output: Number: 42
+```
+### 3. Consumer
+```java
+Consumer printUpperCase = str -> System.out.println(str.toUpperCase());
+printUpperCase.accept("hello"); // Output: HELLO
+```
+### 4. Supplier
+```java
+Supplier randomDouble = () -> Math.random();
+System.out.println(randomDouble.get()); // Output: Random double value
+```
+### 5. UnaryOperator
+```java
+UnaryOperator square = num -> num * num;
+System.out.println(square.apply(5)); // Output: 25
+```
+### 6. BinaryOperator
+```java
+BinaryOperator sum = (a, b) -> a + b;
+System.out.println(sum.apply(10, 20)); // Output: 30
+```
+### Conclusion π
+Predefined functional interfaces in the JDK provide a convenient way to work with functional programming constructs in Java. By leveraging these interfaces, developers can write more concise and expressive code. Understanding and using these interfaces effectively can lead to more readable and maintainable code.
+
+## Predicate Functional Interface
+Predicates are widely used in Java programming, especially in functional programming paradigms and stream processing.
+
+### What is a Predicate?
+In Java, a Predicate is a functional interface included in the java.util.function package. It represents a boolean-valued function that takes an argument and returns true or false.
+
+### Predicate Interface Signature
+The Predicate interface in Java has a single abstract method called test, which takes one argument and returns a boolean value.
+
+```java
+@FunctionalInterface
+public interface Predicate {
+ boolean test(T t);
+}
+```
+### Usage
+Predicates are commonly used in scenarios where conditional checks need to be performed. They can be used in conjunction with lambda expressions, method references, and stream operations.
+
+### Example 1: Filtering a Collection
+```java
+List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+
+// Using a Predicate to filter even numbers
+List evenNumbers = numbers.stream()
+ .filter(num -> num % 2 == 0)
+ .collect(Collectors.toList());
+```
+### Example 2: Combining Predicates
+```java
+Predicate isEven = num -> num % 2 == 0;
+Predicate isGreaterThan5 = num -> num > 5;
+
+// Combining predicates using 'and' method
+Predicate isEvenAndGreaterThan5 = isEven.and(isGreaterThan5);
+
+List filteredNumbers = numbers.stream()
+ .filter(isEvenAndGreaterThan5)
+ .collect(Collectors.toList());
+```
+### Advantages
+Provides a clean and concise way to perform conditional checks.
+Facilitates functional programming paradigms in Java.
+Promotes code reusability and composability.
+### Conclusion
+The Predicate Functional Interface in Java offers a convenient way to perform boolean-valued checks on data. It is widely used in stream processing, filtering collections, and implementing conditional logic in functional programming styles. Understanding and utilizing predicates can lead to more expressive and maintainable code in Java applications.
+
+
+
From 7b8567c9ce7e4cb805098a440e2d8ea9ff22c59f Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 10 Apr 2024 19:21:02 +0530
Subject: [PATCH 198/236] Update section24.README.md
---
section24.README.md | 63 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 63 insertions(+)
diff --git a/section24.README.md b/section24.README.md
index 400c529..2d1860b 100644
--- a/section24.README.md
+++ b/section24.README.md
@@ -346,6 +346,69 @@ Promotes code reusability and composability.
### Conclusion
The Predicate Functional Interface in Java offers a convenient way to perform boolean-valued checks on data. It is widely used in stream processing, filtering collections, and implementing conditional logic in functional programming styles. Understanding and utilizing predicates can lead to more expressive and maintainable code in Java applications.
+## Function Functional Interface
+The `Function` functional interface in Java is a part of the `java.util.function` package introduced in Java 8. It represents a function that accepts one argument and produces a result. This interface is commonly used in functional programming and provides a convenient way to define and use functions as first-class objects in Java.
+
+## Usage
+
+The `Function` interface consists of a single abstract method `apply(T t)` which accepts an argument of type `T` and returns a result of type `R`. It is commonly used in scenarios where you need to perform a transformation or computation on input data.
+
+Here's a simple example demonstrating the usage of the `Function` interface:
+
+```java
+import java.util.function.Function;
+
+public class Main {
+ public static void main(String[] args) {
+ // Define a function to convert a string to its length
+ Function stringLength = str -> str.length();
+
+ // Apply the function
+ int length = stringLength.apply("Hello, World!");
+ System.out.println("Length of the string: " + length);
+ }
+}
+```
+In this example, we create a Function that takes a String and returns its length.
+
+### Additional Operations
+### Chaining Functions
+You can chain multiple Function instances together using the andThen method. This method returns a composed function that first applies the current function and then applies the specified function.
+
+```java
+Function addOne = x -> x + 1;
+Function multiplyByTwo = x -> x * 2;
+
+
+Function addOneThenMultiplyByTwo = addOne.andThen(multiplyByTwo);
+System.out.println("Result: " + addOneThenMultiplyByTwo.apply(5)); // Output: 12
+```
+In this example, addOneThenMultiplyByTwo first adds one to the input and then multiplies it by two.
+
+### Identity Function
+The `identity()` method returns a function that always returns its input argument. It is useful when you need a function that does nothing but return the input itself.
+
+```java
+Function identityFunction = Function.identity();
+System.out.println("Result: " + identityFunction.apply(10)); // Output: 10
+```
+In this example, identityFunction returns the same value that is passed to it.
+
+### Functional Programming Paradigm
+The Function interface is widely used in functional programming paradigms such as lambda expressions and method references. It allows for concise and expressive code by treating functions as first-class citizens.
+
+Here's an example of using lambda expressions with the Function interface:
+
+```java
+Function square = x -> x * x;
+System.out.println("Square of 5: " + square.apply(5)); // Output: 25
+```
+### Functional Interfaces Hierarchy
+The `Function` interface is part of the Java 8 functional interfaces hierarchy, which includes other interfaces like Predicate, Consumer, Supplier, etc. These interfaces provide common function types used in functional programming.
+
+### Conclusion
+The `Function` functional interface in Java provides a powerful way to represent and use functions as first-class objects. It promotes functional programming paradigms and enables developers to write more concise and expressive code. By leveraging lambda expressions, method references, and additional operations like function chaining and identity functions, you can leverage the full potential of the Function interface in your Java applications.
+
From b6685bb91ee3b9d7b04b46b784b95e1a112cb036 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 15 Apr 2024 16:43:21 +0530
Subject: [PATCH 199/236] Update section24.README.md
---
section24.README.md | 293 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 293 insertions(+)
diff --git a/section24.README.md b/section24.README.md
index 2d1860b..b92abb0 100644
--- a/section24.README.md
+++ b/section24.README.md
@@ -409,11 +409,304 @@ The `Function` interface is part of the Java 8 functional interfaces hierarchy,
### Conclusion
The `Function` functional interface in Java provides a powerful way to represent and use functions as first-class objects. It promotes functional programming paradigms and enables developers to write more concise and expressive code. By leveraging lambda expressions, method references, and additional operations like function chaining and identity functions, you can leverage the full potential of the Function interface in your Java applications.
+## UnaryOperator Interface
+The `UnaryOperator` interface in Java is a functional interface introduced in Java 8. It belongs to the `java.util.function` package and represents an operation on a single operand that produces a result of the same type as its operand. It extends the `Function` interface.
+### Usage
+The `UnaryOperator` interface is commonly used in scenarios where you need to transform or operate on an object of a certain type and return an object of the same type. Here's an example of how you can use `UnaryOperator`:
+
+```java
+import java.util.function.UnaryOperator;
+
+public class Main {
+ public static void main(String[] args) {
+ // Define a UnaryOperator for String concatenation
+ UnaryOperator concatOperator = s -> s + " World";
+
+ // Apply the UnaryOperator to a String
+ String result = concatOperator.apply("Hello");
+
+ System.out.println(result); // Output: Hello World
+ }
+}
+```
+
+
+Certainly! Here's a sample README.md file for the UnaryOperator interface in Java:
+
+markdown
+Copy code
+# UnaryOperator Interface
+
+The `UnaryOperator` interface in Java is a functional interface introduced in Java 8. It belongs to the `java.util.function` package and represents an operation on a single operand that produces a result of the same type as its operand. It extends the `Function` interface.
+
+## Functional Descriptor
+
+```java
+@FunctionalInterface
+public interface UnaryOperator extends Function {
+ // Inherits abstract method from Function interface
+}
+Usage
+The UnaryOperator interface is commonly used in scenarios where you need to transform or operate on an object of a certain type and return an object of the same type. Here's an example of how you can use UnaryOperator:
+
+java
+Copy code
+import java.util.function.UnaryOperator;
+
+public class Main {
+ public static void main(String[] args) {
+ // Define a UnaryOperator for String concatenation
+ UnaryOperator concatOperator = s -> s + " World";
+
+ // Apply the UnaryOperator to a String
+ String result = concatOperator.apply("Hello");
+
+ System.out.println(result); // Output: Hello World
+ }
+}
+```
+In this example, we define a UnaryOperator that concatenates " World" to a given String. Then, we apply this operator to the String "Hello", resulting in "Hello World".
+
+### Functional Method
+The `UnaryOperator` interface inherits the following abstract method from the Function interface:
+
+```java
+T apply(T t);
+```
+This method applies the operation to the given argument and returns the result.
+
+### Functional Interface
+`UnaryOperator` is a functional interface, which means it has exactly one abstract method. It can be used in lambda expressions and method references.
+
+### Related Interfaces
+- **Function :** Represents a function that accepts one argument and produces a result.
+- **BinaryOperator :** Represents an operation upon two operands of the same type, producing a result of the same type as the operands.
+
+## Consumer Interface
+The consumer interface is a functional interface provided by Java's `java.util.function` package. It represents an operation that accepts a single input argument and returns no result.
+
+### Features
+- **Genericity**: The consumer interface is generic, allowing it to accept different types of input arguments.
+- **Flexibility**: Consumers can be used to perform a wide range of operations, such as printing values, adding them to a collection, or applying transformations.
+
+## Example
+```java
+import java.util.function.Consumer;
+
+public class Example {
+ public static void main(String[] args) {
+ // Example 1: Printing elements of an array using a consumer
+ String[] names = {"Alice", "Bob", "Charlie"};
+ Consumer printConsumer = System.out::println;
+ forEach(names, printConsumer);
+
+ // Example 2: Adding elements to a list using a consumer
+ List numbers = new ArrayList<>();
+ Consumer addConsumer = numbers::add;
+ addConsumer.accept(1);
+ addConsumer.accept(2);
+ addConsumer.accept(3);
+ System.out.println("Numbers added to list: " + numbers);
+ }
+
+ // Generic method to iterate over an array and apply a consumer to each element
+ public static void forEach(T[] array, Consumer consumer) {
+ for (T element : array) {
+ consumer.accept(element);
+ }
+ }
+}
+```
+## Supplier Interface in Java
+The `Supplier` interface in Java is a functional interface defined in the `java.util.function` package. It represents a supplier of results. It does not accept any arguments and is expected to generate or supply results when called upon by the functional method `get()`.
+
+### Usage
+The Supplier interface is primarily used when a function needs to generate or supply values without taking any input. It can be useful in scenarios such as lazy initialization, where you want to defer the creation of an object until it's actually needed.
+
+The Supplier interface is commonly used with Java 8's Stream API to generate streams of elements. It can also be used in various functional programming constructs to provide values on demand.
+
+### Example
+```java
+import java.util.function.Supplier;
+
+public class SupplierExample {
+ public static void main(String[] args) {
+ // Example 1: Using a Supplier to lazily initialize an object
+ Supplier lazyStringSupplier = () -> {
+ // Simulating expensive object creation
+ System.out.println("Creating an expensive object...");
+ return "Expensive Object";
+ };
+
+ // Lazy initialization only happens when get() is called
+ System.out.println("First get(): " + lazyStringSupplier.get());
+ System.out.println("Second get(): " + lazyStringSupplier.get());
+
+ // Example 2: Using a Supplier with Stream API
+ Stream.generate(() -> "Hello").limit(5).forEach(System.out::println);
+ }
+}
+```
+
+## BiFunctional Interfaces
+BiFunctional interfaces are functional interfaces that accept two arguments and produce a result. They are useful for scenarios where you need to perform operations on two inputs and return a result.
+
+### Examples
+Example 1: Adding Two Numbers
+```java
+import java.util.function.*;
+
+public class AddTwoNumbers {
+ public static void main(String[] args) {
+ BiFunction add = (a, b) -> a + b;
+ int result = add.apply(10, 20);
+ System.out.println("Sum: " + result); // Output: Sum: 30
+ }
+}
+```
+### Example 2: Concatenating Two Strings
+```java
+import java.util.function.*;
+
+public class ConcatenateStrings {
+ public static void main(String[] args) {
+ BiFunction concat = (str1, str2) -> str1 + " " + str2;
+ String result = concat.apply("Hello", "World");
+ System.out.println("Concatenated String: " + result); // Output: Concatenated String: Hello World
+ }
+}
+```
+### Example 3: Custom Operation on Two Integers
+```java
+import java.util.function.*;
+
+public class CustomOperation {
+ public static void main(String[] args) {
+ BiFunction customOperation = (a, b) -> (a * a) + (b * b);
+ int result = customOperation.apply(3, 4);
+ System.out.println("Result of Custom Operation: " + result); // Output: Result of Custom Operation: 25
+ }
+}
+```
+
+## Primitive Type Functional Interfaces
+This repository contains examples and explanations of primitive type functional interfaces in Java. `Primitive` type functional interfaces are special types of functional interfaces designed to work with primitive data types (int, long, double, etc.) rather than objects. These interfaces are part of the `java.util.function` package introduced in Java 8 and are used extensively in functional programming paradigms.
+
+Primitive type functional interfaces are useful when you need to optimize performance or when you're working with large datasets, as they avoid the overhead of autoboxing and unboxing. By using primitive type functional interfaces, you can write more efficient and concise code.
+
+In this repository, you will find examples and explanations of the following primitive type functional interfaces:
+
+- IntSupplier
+- IntConsumer
+- IntPredicate
+- IntFunction
+- IntUnaryOperator
+- IntBinaryOperator
+- LongSupplier
+- LongConsumer
+- LongPredicate
+- LongFunction
+- LongUnaryOperator
+- LongBinaryOperator
+- DoubleSupplier
+- DoubleConsumer
+- DoublePredicate
+- DoubleFunction
+- DoubleUnaryOperator
+- DoubleBinaryOperator
+
+### Usage
+Each interface is accompanied by examples demonstrating how to use it in various scenarios. These examples are provided as Java code snippets along with explanations to help you understand their usage and behavior.
+
+To use these interfaces in your projects, simply import them from the java.util.function package:
+
+```java
+import java.util.function.IntSupplier;
+import java.util.function.IntConsumer;
+import java.util.function.IntPredicate;
+import java.util.function.IntFunction;
+import java.util.function.IntUnaryOperator;
+import java.util.function.IntBinaryOperator;
+```
+
+## Lexical scoping of Lambda Expressions
+
+Lexical scoping of lambda expressions in Java refers to the ability of a lambda expression to access variables from its surrounding context. In lexical scoping, the variables that are accessible to a lambda expression are determined by the code structure (the lexical scope) where the lambda expression is defined, rather than where it is executed.
+In Java, lambda expressions can access variables from the enclosing scope if those variables are effectively final or effectively final. An effectively final variable is one whose value does not change after it is initialized, even though it might not be explicitly declared as final. Lambda expressions can access such variables without any issues.
+Here's a simple example to illustrate lexical scoping of lambda expressions in Java:
+```java
+public class LexicalScopingExample {
+ public static void main(String[] args) {
+ int x = 10; // Outer variable
+
+ // Lambda expression accessing outer variable
+ Runnable runnable = () -> {
+ System.out.println("Value of x: " + x);
+ };
+
+ runnable.run(); // Output: Value of x: 10
+ }
+}
+```
+In this example, the lambda expression accesses the variable x from its surrounding context. Since x is effectively final (its value doesn't change after initialization), the lambda expression can access it without any issues.
+
+Lexical scoping allows lambda expressions in Java to capture and use variables from their enclosing scope, which enables concise and expressive code in functional programming paradigms.
+
+## this and super keywords inside Lambda expression
+Understanding how `this` and `super` behave within lambda expressions is crucial for writing clean and effective code, especially in object-oriented programming scenarios.
+### Examples
+#### 1. Using `this` Inside Lambda Expression
+
+```java
+public class ThisSuperExample {
+ private String name = "Example";
+
+ public void exampleMethod() {
+ Runnable runnable = () -> {
+ // Accessing instance variable using 'this' inside lambda expression
+ System.out.println("Name using 'this': " + this.name);
+ };
+ runnable.run();
+ }
+
+ public static void main(String[] args) {
+ ThisSuperExample example = new ThisSuperExample();
+ example.exampleMethod(); // Output: Name using 'this': Example
+ }
+}
+```
+#### 2. Using super Inside Lambda Expression
+```java
+class Parent {
+ String name = "Parent";
+
+ public void printName() {
+ System.out.println("Parent class name: " + name);
+ }
+}
+
+public class ThisSuperExample extends Parent {
+ String name = "Child";
+
+ public void exampleMethod() {
+ Runnable runnable = () -> {
+ // Accessing superclass instance variable using 'super' inside lambda expression
+ super.printName(); // Output: Parent class name: Parent
+ };
+ runnable.run();
+ }
+
+ public static void main(String[] args) {
+ ThisSuperExample example = new ThisSuperExample();
+ example.exampleMethod();
+ }
+}
+```
From 37fbe1a58daa618c34b4ccf3b610822f3b274453 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 15 Apr 2024 17:33:01 +0530
Subject: [PATCH 200/236] Update section24.README.md
---
section24.README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/section24.README.md b/section24.README.md
index b92abb0..26cc8fb 100644
--- a/section24.README.md
+++ b/section24.README.md
@@ -711,3 +711,5 @@ public class ThisSuperExample extends Parent {
+
+
From 6aab4f827c0d010c064225e03baabba938b41283 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 15 Apr 2024 17:36:10 +0530
Subject: [PATCH 201/236] Create Section25.README.md
---
Section25.README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 Section25.README.md
diff --git a/Section25.README.md b/Section25.README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/Section25.README.md
@@ -0,0 +1 @@
+
From 8fda11fd673aa5e559f2e929b6282911c373ccbe Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 15 Apr 2024 17:48:57 +0530
Subject: [PATCH 202/236] Update Section25.README.md
---
Section25.README.md | 49 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 49 insertions(+)
diff --git a/Section25.README.md b/Section25.README.md
index 8b13789..abdf3be 100644
--- a/Section25.README.md
+++ b/Section25.README.md
@@ -1 +1,50 @@
+# Method References
+Method references in Java provide a way to refer to methods or constructors without invoking them. They are similar to lambda expressions but provide a more concise syntax when the lambda expression simply calls an existing method. Method references are particularly useful when you want to pass a method as an argument to another method or when you want to use a method as a functional interface implementation.
+## Types of Method References
+There are four main types of method references in Java:
+
+- **Reference to a Static Method :** References a static method of a class.
+- **Reference to an Instance Method of a Particular Object :** References an instance method of a specific object.
+- **Reference to an Instance Method of an Arbitrary Object of a Particular Type :** References an instance method of an object determined at runtime.
+Reference to a Constructor: References a constructor.
+
+### Syntax
+The syntax for method references depends on the type of method being referenced:
+
+- **Reference to a Static Method :** ContainingClass::staticMethodName
+- **Reference to an Instance Method of a Particular Object :** objectReference::instanceMethodName
+- **Reference to an Instance Method of an Arbitrary Object of a Particular Type :** ContainingType::methodName
+- **Reference to a Constructor :** ClassName::new
+
+### Example
+Consider a list of strings that we want to sort using a case-insensitive comparison. We can achieve this using method references.
+
+```java
+import java.util.Arrays;
+import java.util.List;
+
+public class MethodReferenceExample {
+ public static void main(String[] args) {
+ List names = Arrays.asList("John", "Alice", "Bob", "Mary");
+
+ // Using lambda expression
+ names.sort((s1, s2) -> s1.compareToIgnoreCase(s2));
+ System.out.println("Sorted names (lambda): " + names);
+
+ // Using method reference
+ names.sort(String::compareToIgnoreCase);
+ System.out.println("Sorted names (method reference): " + names);
+ }
+}
+```
+In this example, String::compareToIgnoreCase is a method reference that refers to the compareToIgnoreCase method of the String class. It's equivalent to the lambda expression (s1, s2) -> s1.compareToIgnoreCase(s2).
+
+### Benefits
+Method references provide several benefits:
+
+- **Conciseness :** They offer a more concise syntax compared to lambda expressions, especially when simply delegating to an existing method.
+- **Readability :** They make the code more readable by clearly indicating which method is being used.
+- **Reusability :** They promote code reuse by allowing you to reuse existing methods.
+### Conclusion
+Method references are a powerful feature introduced in Java 8 that provide a shorthand syntax for referencing methods or constructors. They offer conciseness, readability, and promote code reuse. Understanding and using method references effectively can lead to cleaner and more expressive Java code.
From 2a2385cc95639bcee22a0b1b33a5a33b9b9053c5 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 15 Apr 2024 17:58:33 +0530
Subject: [PATCH 203/236] Update Section25.README.md
---
Section25.README.md | 97 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 97 insertions(+)
diff --git a/Section25.README.md b/Section25.README.md
index abdf3be..b4484ac 100644
--- a/Section25.README.md
+++ b/Section25.README.md
@@ -48,3 +48,100 @@ Method references provide several benefits:
- **Reusability :** They promote code reuse by allowing you to reuse existing methods.
### Conclusion
Method references are a powerful feature introduced in Java 8 that provide a shorthand syntax for referencing methods or constructors. They offer conciseness, readability, and promote code reuse. Understanding and using method references effectively can lead to cleaner and more expressive Java code.
+
+## Static Method References
+Static method references in Java provide a concise and expressive way to refer to static methods using the `::` operator. This feature was introduced in Java 8 as part of the lambda expressions and method references enhancements.
+
+### Syntax
+
+The syntax for static method references is as follows:
+
+```java
+ContainingClass::staticMethodName
+```
+
+### Example
+Consider a scenario where you have a static method `staticMethod()` in a class `MyClass`. You can refer to this method using static method references as follows:
+
+java
+Copy code
+public class MyClass {
+ public static void staticMethod() {
+ System.out.println("Hello from static method!");
+ }
+}
+
+public class Main {
+ public static void main(String[] args) {
+ // Using static method references
+ Runnable runnable = MyClass::staticMethod;
+ Thread thread = new Thread(runnable);
+ thread.start();
+ }
+}
+In the above example, MyClass::staticMethod refers to the static method staticMethod() of the MyClass class.
+
+### Advantages
+**Conciseness :** Static method references provide a concise alternative to lambda expressions when referring to static methods.
+
+**Readability :** They enhance the readability of code by providing a clear and direct reference to the method being invoked.
+
+**Reusability :** Static method references enable reusing existing static methods without the need for additional code.
+
+### Limitations
+Access to Instance Variables: Static method references cannot access instance variables or instance methods directly. They operate only on the parameters passed to them.
+
+Interface Method Compatibility: The method signature of the static method being referenced must match the functional interface's abstract method signature.
+
+### Conclusion
+Static method references in Java offer a convenient way to refer to static methods, improving code readability and conciseness. By leveraging this feature, developers can write cleaner and more expressive code while promoting code reuse and maintainability.
+
+## Instance Method Reference
+In Java, instance method reference is a feature introduced in Java 8 as part of the lambda expressions and functional interfaces enhancements. It provides a concise way to reference instance methods of objects as functional interfaces, particularly useful when those methods match the signature of the functional interface's abstract method.
+
+Instance method reference is often used in conjunction with functional interfaces like `Function`, `Predicate`, `Consumer`, etc., where you want to refer to an existing method to implement the abstract method of the interface.
+
+### Syntax
+
+The syntax for instance method reference is as follows:
+
+```java
+ClassName::instanceMethodName
+```
+
+Where:
+
+ClassName is the name of the class containing the instance method.
+instanceMethodName is the name of the instance method.
+### Example
+Consider a simple example of sorting strings in alphabetical order using instance method reference:
+
+```java
+import java.util.Arrays;
+import java.util.Comparator;
+
+public class InstanceMethodReferenceExample {
+
+ public static void main(String[] args) {
+ String[] names = {"Alice", "Bob", "Charlie", "David"};
+
+ // Using lambda expression
+ Arrays.sort(names, (s1, s2) -> s1.compareTo(s2));
+ System.out.println("Sorted names: " + Arrays.toString(names));
+
+ // Using instance method reference
+ Arrays.sort(names, String::compareTo);
+ System.out.println("Sorted names: " + Arrays.toString(names));
+ }
+}
+```
+In this example, `String::compareTo` is an instance method reference that refers to the `compareTo` method of the String class. This method is compatible with the Comparator functional interface, which expects a method with the same signature.
+
+### When to Use
+Instance method reference is useful when:
+
+You have an existing method that matches the signature of the abstract method of a functional interface.
+You want to improve code readability by avoiding verbose lambda expressions.
+
+### Conclusion
+Instance method reference in Java provides a concise and readable way to refer to instance methods as functional interface implementations. It enhances code readability and promotes a more functional programming style in Java.
From 1dd03a3be856d95045373c5f2678b661a9cfa3de Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 15 Apr 2024 18:06:21 +0530
Subject: [PATCH 204/236] Update Section25.README.md
---
Section25.README.md | 39 +++++++++++++++++++++++++++++++++++++++
1 file changed, 39 insertions(+)
diff --git a/Section25.README.md b/Section25.README.md
index b4484ac..e63fc0e 100644
--- a/Section25.README.md
+++ b/Section25.README.md
@@ -145,3 +145,42 @@ You want to improve code readability by avoiding verbose lambda expressions.
### Conclusion
Instance method reference in Java provides a concise and readable way to refer to instance methods as functional interface implementations. It enhances code readability and promotes a more functional programming style in Java.
+
+## Instance Method Reference Using Class Type
+Instance method references in Java allow you to reference methods of an object. When using instance method references with a class type, you're essentially referring to a method of an object of that class. This can be useful when you want to pass a method as a functional interface parameter, such as in lambda expressions or streams.
+
+## Example
+
+Suppose we have a class `MyClass` with an instance method `myMethod`:
+
+```java
+class MyClass {
+ void myMethod() {
+ System.out.println("Instance method called");
+ }
+}
+```
+We can use instance method references using Class Type as follows:
+```java
+// Define a functional interface
+interface MyFunctionalInterface {
+ void myMethod();
+}
+
+public class Demo {
+ public static void main(String[] args) {
+ MyClass obj = new MyClass();
+
+ // Using instance method reference with Class Type
+ MyFunctionalInterface functionalInterface = obj::myMethod;
+
+ // Calling the method through functional interface
+ functionalInterface.myMethod();
+ }
+}
+```
+This will output:
+
+```sql
+Instance method called
+```
From f81ae78aad4997b73ae07a4701cc33b205d534d2 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 15 Apr 2024 18:09:11 +0530
Subject: [PATCH 205/236] Update Section25.README.md
---
Section25.README.md | 38 ++++++++++++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
diff --git a/Section25.README.md b/Section25.README.md
index e63fc0e..7cdf254 100644
--- a/Section25.README.md
+++ b/Section25.README.md
@@ -184,3 +184,41 @@ This will output:
```sql
Instance method called
```
+
+## Demo of Constructor Reference
+Constructor reference is a shorthand syntax for creating instances of functional interfaces. It's particularly useful when working with functional interfaces like `Supplier`, `Function`, `Consumer`, etc.
+
+### Usage
+The ConstructorReferenceDemo.java file contains examples of how to use constructor reference. It demonstrates creating instances of functional interfaces using constructor references.
+
+### Example
+```java
+import java.util.function.Supplier;
+
+public class ConstructorReferenceDemo {
+
+ // Define a simple class
+ static class MyClass {
+ private String message;
+
+ MyClass(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+ }
+
+ public static void main(String[] args) {
+ // Using constructor reference to create a new instance of MyClass
+ Supplier supplier = MyClass::new;
+
+ // Getting instance using supplier
+ MyClass instance = supplier.get();
+
+ // Outputting message from MyClass instance
+ System.out.println(instance.getMessage());
+ }
+}
+```
From 1fc8e20937d69be022261d65116ce9052f8cbe86 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 15 Apr 2024 18:13:58 +0530
Subject: [PATCH 206/236] Update Section25.README.md
---
Section25.README.md | 16 ++++++++--------
1 file changed, 8 insertions(+), 8 deletions(-)
diff --git a/Section25.README.md b/Section25.README.md
index 7cdf254..7e7a738 100644
--- a/Section25.README.md
+++ b/Section25.README.md
@@ -1,4 +1,4 @@
-# Method References
+# Method References π
Method references in Java provide a way to refer to methods or constructors without invoking them. They are similar to lambda expressions but provide a more concise syntax when the lambda expression simply calls an existing method. Method references are particularly useful when you want to pass a method as an argument to another method or when you want to use a method as a functional interface implementation.
## Types of Method References
@@ -17,7 +17,7 @@ The syntax for method references depends on the type of method being referenced:
- **Reference to an Instance Method of an Arbitrary Object of a Particular Type :** ContainingType::methodName
- **Reference to a Constructor :** ClassName::new
-### Example
+### Example π‘
Consider a list of strings that we want to sort using a case-insensitive comparison. We can achieve this using method references.
```java
@@ -60,11 +60,10 @@ The syntax for static method references is as follows:
ContainingClass::staticMethodName
```
-### Example
+### Example π‘
Consider a scenario where you have a static method `staticMethod()` in a class `MyClass`. You can refer to this method using static method references as follows:
-java
-Copy code
+```java
public class MyClass {
public static void staticMethod() {
System.out.println("Hello from static method!");
@@ -79,7 +78,8 @@ public class Main {
thread.start();
}
}
-In the above example, MyClass::staticMethod refers to the static method staticMethod() of the MyClass class.
+```
+In the above example, `MyClass::staticMethod` refers to the static method `staticMethod()` of the MyClass class.
### Advantages
**Conciseness :** Static method references provide a concise alternative to lambda expressions when referring to static methods.
@@ -149,7 +149,7 @@ Instance method reference in Java provides a concise and readable way to refer t
## Instance Method Reference Using Class Type
Instance method references in Java allow you to reference methods of an object. When using instance method references with a class type, you're essentially referring to a method of an object of that class. This can be useful when you want to pass a method as a functional interface parameter, such as in lambda expressions or streams.
-## Example
+## Example π‘
Suppose we have a class `MyClass` with an instance method `myMethod`:
@@ -191,7 +191,7 @@ Constructor reference is a shorthand syntax for creating instances of functional
### Usage
The ConstructorReferenceDemo.java file contains examples of how to use constructor reference. It demonstrates creating instances of functional interfaces using constructor references.
-### Example
+### Example π‘
```java
import java.util.function.Supplier;
From 7183566bb56455a8ab6effc7b02fa0943140bdcd Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Mon, 15 Apr 2024 18:14:43 +0530
Subject: [PATCH 207/236] Update Section25.README.md
---
Section25.README.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/Section25.README.md b/Section25.README.md
index 7e7a738..6d21562 100644
--- a/Section25.README.md
+++ b/Section25.README.md
@@ -46,7 +46,7 @@ Method references provide several benefits:
- **Conciseness :** They offer a more concise syntax compared to lambda expressions, especially when simply delegating to an existing method.
- **Readability :** They make the code more readable by clearly indicating which method is being used.
- **Reusability :** They promote code reuse by allowing you to reuse existing methods.
-### Conclusion
+### Conclusion π
Method references are a powerful feature introduced in Java 8 that provide a shorthand syntax for referencing methods or constructors. They offer conciseness, readability, and promote code reuse. Understanding and using method references effectively can lead to cleaner and more expressive Java code.
## Static Method References
@@ -93,7 +93,7 @@ Access to Instance Variables: Static method references cannot access instance va
Interface Method Compatibility: The method signature of the static method being referenced must match the functional interface's abstract method signature.
-### Conclusion
+### Conclusion π
Static method references in Java offer a convenient way to refer to static methods, improving code readability and conciseness. By leveraging this feature, developers can write cleaner and more expressive code while promoting code reuse and maintainability.
## Instance Method Reference
@@ -143,7 +143,7 @@ Instance method reference is useful when:
You have an existing method that matches the signature of the abstract method of a functional interface.
You want to improve code readability by avoiding verbose lambda expressions.
-### Conclusion
+### Conclusion π
Instance method reference in Java provides a concise and readable way to refer to instance methods as functional interface implementations. It enhances code readability and promotes a more functional programming style in Java.
## Instance Method Reference Using Class Type
From d4a2605ecf953dd820c996c4de4fe34f663e537f Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 16 Apr 2024 14:55:13 +0530
Subject: [PATCH 208/236] Create section26.README.md
---
section26.README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section26.README.md
diff --git a/section26.README.md b/section26.README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section26.README.md
@@ -0,0 +1 @@
+
From 70e217b4205c30b7fca263d7088f8b905a96c624 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 16 Apr 2024 15:09:04 +0530
Subject: [PATCH 209/236] Update section26.README.md
---
section26.README.md | 105 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 105 insertions(+)
diff --git a/section26.README.md b/section26.README.md
index 8b13789..b10f201 100644
--- a/section26.README.md
+++ b/section26.README.md
@@ -1 +1,106 @@
+# Streams
+## Introduction to java.util.stream API in Java
+The `java.util.stream` package in Java provides a powerful way to process collections of objects in a functional style. It was introduced in Java 8 as part of the Java Collections Framework.
+### What is a Stream?
+A Stream in Java represents a sequence of elements and supports different operations to perform computations on these elements. Streams allow for functional-style operations to be performed on collections of objects, such as filtering, mapping, reducing, and more.
+### Features
+- **Lazy Evaluation:** Streams perform operations only when necessary. Intermediate operations are typically lazy, meaning they do not compute a result until the result is needed by a terminal operation.
+- **Parallel Processing:** Streams can leverage parallel processing, making it easier to write parallelizable code to take advantage of multi-core processors.
+- **Functional Composition:** Streams provide methods for composing operations in a functional style, making it easy to chain multiple operations together.
+### Basic Operations
+- **Filtering:** Allows filtering elements based on certain criteria.
+- **Mapping:** Allows transforming elements into another form.
+- **Reducing:** Performs a reduction on the elements of the stream.
+- **Sorting:** Sorts the elements of the stream based on a comparator.
+
+### Example
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class Main {
+ public static void main(String[] args) {
+ List names = Arrays.asList("John", "Alice", "Bob", "Charlie", "David");
+
+ // Filter names starting with 'A' and collect them into a new list
+ List filteredNames = names.stream()
+ .filter(name -> name.startsWith("A"))
+ .collect(Collectors.toList());
+
+ System.out.println(filteredNames); // Output: [Alice]
+ }
+}
+```
+
+## Creating Stream from Collections
+Streams provide a modern, functional approach to processing collections of objects in Java, allowing for concise and expressive code.
+
+### Creating a Stream from List
+
+You can easily create a Stream from a List using the `stream()` method introduced in Java 8.
+
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Stream;
+
+public class Main {
+ public static void main(String[] args) {
+ List myList = Arrays.asList("apple", "banana", "orange");
+ Stream stream = myList.stream();
+
+ // Use the stream
+ stream.forEach(System.out::println);
+ }
+}
+```
+### Creating a Stream from Set
+Similarly, you can create a Stream from a Set using the stream() method.
+
+```java
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Stream;
+
+public class Main {
+ public static void main(String[] args) {
+ Set mySet = new HashSet<>();
+ mySet.add("apple");
+ mySet.add("banana");
+ mySet.add("orange");
+
+ Stream stream = mySet.stream();
+
+ // Use the stream
+ stream.forEach(System.out::println);
+ }
+}
+```
+### Creating a Stream from Map
+To create a Stream from a Map, you can use the keySet().stream() or values().stream() methods.
+
+```java
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Stream;
+
+public class Main {
+ public static void main(String[] args) {
+ Map myMap = new HashMap<>();
+ myMap.put(1, "apple");
+ myMap.put(2, "banana");
+ myMap.put(3, "orange");
+
+ Stream keysStream = myMap.keySet().stream();
+ Stream valuesStream = myMap.values().stream();
+
+ // Use the streams
+ keysStream.forEach(System.out::println);
+ valuesStream.forEach(System.out::println);
+ }
+}
+```
+### Conclusion
+Creating Streams from collections in Java is straightforward and allows for concise and expressive code. Streams provide powerful features for processing data in a functional style.
From 4e307e95e9118edbcff7966360e3e461fecb75c0 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 16 Apr 2024 19:20:17 +0530
Subject: [PATCH 210/236] Update section26.README.md
---
section26.README.md | 144 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 144 insertions(+)
diff --git a/section26.README.md b/section26.README.md
index b10f201..a1de918 100644
--- a/section26.README.md
+++ b/section26.README.md
@@ -104,3 +104,147 @@ public class Main {
```
### Conclusion
Creating Streams from collections in Java is straightforward and allows for concise and expressive code. Streams provide powerful features for processing data in a functional style.
+
+## Streams have no Storage
+Streams in Java are not data storage containers; instead, they provide a way to process elements from a source (such as a collection, array, or I/O channel) in a functional and declarative style. Streams operate on data elements in a sequence and allow for various operations to be performed on those elements, such as filtering, mapping, sorting, and reducing.
+
+### Example
+Consider the following example that demonstrates the use of streams to process a list of integers:
+
+```java
+import java.util.Arrays;
+import java.util.List;
+
+public class Main {
+ public static void main(String[] args) {
+ List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+
+ // Example 1: Filtering even numbers
+ numbers.stream()
+ .filter(num -> num % 2 == 0)
+ .forEach(System.out::println);
+
+ // Example 2: Mapping numbers to their squares
+ numbers.stream()
+ .map(num -> num * num)
+ .forEach(System.out::println);
+
+ // Example 3: Reducing numbers to their sum
+ int sum = numbers.stream()
+ .reduce(0, Integer::sum);
+ System.out.println("Sum: " + sum);
+ }
+}
+```
+In this example:
+
+We create a list of integers numbers.
+Example 1 demonstrates filtering even numbers using the filter() operation.
+Example 2 shows mapping each number to its square using the map() operation.
+Example 3 illustrates reducing the numbers to their sum using the reduce() operation.
+### Features
+Provides a comprehensive understanding of streams in Java.
+Clarifies that streams are not storage containers but rather enable efficient processing of data elements.
+Offers examples of common stream operations including filtering, mapping, and reducing.
+
+## Introduction to Streams Pipeline
+Streams Pipeline is a powerful feature introduced in Java 8, allowing developers to perform complex data processing tasks with concise and expressive code.
+
+### What is Streams Pipeline?
+Streams Pipeline is a sequence of aggregate operations (such as filter, map, reduce, etc.) that are applied to a stream of elements to perform a specific task. It enables functional-style operations on collections, making code more readable, concise, and efficient.
+
+### Key Concepts
+Stream: Represents a sequence of elements and supports aggregate operations.
+Intermediate Operations: Operations such as filter, map, sorted, etc., which transform a stream into another stream. These operations are lazy and do not produce any result until a terminal operation is executed.
+Terminal Operations: Operations such as forEach, collect, reduce, etc., which produce a result or side-effect. Terminal operations trigger the execution of the intermediate operations.
+Stateless vs. Stateful Operations: Stateless operations do not rely on the state of other elements in the stream, whereas stateful operations may depend on the state of other elements.
+### Getting Started
+To use Streams Pipeline in your Java project:
+
+Ensure you have Java 8 or later installed on your system.
+Create a new Java project or open an existing one.
+Import the necessary packages:
+```java
+import java.util.stream.Stream;
+```
+Start using Streams Pipeline in your code.
+### Examples
+Filtering elements
+```java
+List names = Arrays.asList("John", "Alice", "Bob", "David");
+// Filter names starting with 'A'
+names.stream()
+ .filter(name -> name.startsWith("A"))
+ .forEach(System.out::println);
+```
+### Mapping elements
+```java
+List numbers = Arrays.asList(1, 2, 3, 4, 5);
+
+// Square each number
+numbers.stream()
+ .map(n -> n * n)
+ .forEach(System.out::println);
+```
+### Reducing elements
+```java
+List numbers = Arrays.asList(1, 2, 3, 4, 5);
+
+// Sum of all numbers
+int sum = numbers.stream()
+ .reduce(0, Integer::sum);
+System.out.println("Sum: " + sum);
+```
+
+## Java Streams `map()` Function
+In Java, Streams provide a convenient and efficient way to work with sequences of elements. The `map()` function is one of the most frequently used functions in Streams. It transforms each element of the stream using the provided function and returns a new stream consisting of the transformed elements.
+
+### Syntax
+
+The syntax of the `map()` function in Java Streams is as follows:
+
+```java
+ Stream map(Function super T,? extends R> mapper);
+```
+
+Here,
+
+`Function super T,? extends R> mapper`: A functional interface that represents a function that accepts one argument of type T and produces a result of type R. This function is applied to each element of the stream.
+### Parameters
+- **mapper :** The function to apply to each element of the stream.
+### Return Value
+- The `map()` function returns a new Stream consisting of the results of applying the given function to the elements of this stream.
+
+### Example
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+
+public class Main {
+ public static void main(String[] args) {
+ List names = Arrays.asList("John", "Alice", "Bob", "Eve");
+
+ // Convert each name to uppercase
+ List upperCaseNames = names.stream()
+ .map(String::toUpperCase)
+ .collect(Collectors.toList());
+
+ System.out.println(upperCaseNames); // Output: [JOHN, ALICE, BOB, EVE]
+ }
+}
+```
+In this example, the map() function is used to convert each name in the names list to uppercase.
+
+### Common Use Cases
+- **Transformation :** Transforming elements of a stream from one type to another.
+- **Data Manipulation :** Applying a function to each element to derive a new value or perform some operation.
+### Advantages
+- **Concise :** Allows concise and readable code for transforming elements of a stream.
+- **Pipeline Friendly :** Fits well into stream pipelines, enabling powerful data processing operations.
+### Conclusion
+The `map()` function in Java Streams is a powerful tool for transforming elements of a stream according to a specified function. It promotes functional programming practices and enables elegant and efficient data processing operations.
+
+
+
From 74462f7eddfc1b4c09f1de578df2bb1433b0d456 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 16 Apr 2024 19:24:47 +0530
Subject: [PATCH 211/236] Update section26.README.md
---
section26.README.md | 54 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 54 insertions(+)
diff --git a/section26.README.md b/section26.README.md
index a1de918..439672d 100644
--- a/section26.README.md
+++ b/section26.README.md
@@ -246,5 +246,59 @@ In this example, the map() function is used to convert each name in the names li
### Conclusion
The `map()` function in Java Streams is a powerful tool for transforming elements of a stream according to a specified function. It promotes functional programming practices and enables elegant and efficient data processing operations.
+## Java Streams `flatMap()` Function
+In Java, Streams provide a powerful way to work with sequences of elements. The `flatMap()` function is a versatile tool that allows flattening of nested collections or streams within a stream, resulting in a single stream of elements.
+
+### Syntax
+
+The syntax of the `flatMap()` function in Java Streams is as follows:
+
+```java
+ Stream flatMap(Function super T,? extends Stream extends R>> mapper);
+```
+
+Here,
+
+`Function super T,? extends Stream extends R>> mapper`: A functional interface that represents a function that accepts one argument of type T and produces a stream of elements of type R. This function is applied to each element of the stream.
+### Parameters
+**mapper :** The function to apply to each element of the stream, which returns a stream of elements.
+### Return Value
+ -The `flatMap()` function returns a new Stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
+
+### Example
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class Main {
+ public static void main(String[] args) {
+ List> nestedLists = Arrays.asList(
+ Arrays.asList(1, 2, 3),
+ Arrays.asList(4, 5, 6),
+ Arrays.asList(7, 8, 9)
+ );
+
+ // Flatten the nested lists into a single list
+ List flattenedList = nestedLists.stream()
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+
+ System.out.println(flattenedList); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ }
+}
+```
+In this example, the `flatMap()` function is used to flatten a list of lists into a single list.
+
+### Common Use Cases
+- **Flattening :** Flattening a stream of collections or streams into a single stream.
+- **Removing Empty Elements :** Filtering out empty or null elements from a stream.
+ -**Converting :** Converting a complex structure into a simpler one.
+### Advantages
+- **Streamlining Data Processing :** Simplifies data processing by flattening nested structures.
+- **Versatility :** Offers a wide range of applications, from flattening collections to filtering out empty elements.
+### Conclusion
+The `flatMap()` function in Java Streams is a powerful tool for flattening nested collections or streams within a stream, allowing for streamlined data processing and transformation. It promotes concise and readable code and enables efficient manipulation of complex data structures.
+
From b00ebd8a98303678934e608ea29298e3dbd96749 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 16 Apr 2024 19:33:37 +0530
Subject: [PATCH 212/236] Update section26.README.md
---
section26.README.md | 95 ++++++++++++++++++++++++++++++++++-----------
1 file changed, 73 insertions(+), 22 deletions(-)
diff --git a/section26.README.md b/section26.README.md
index 439672d..0136545 100644
--- a/section26.README.md
+++ b/section26.README.md
@@ -1,4 +1,4 @@
-# Streams
+# Streams π
## Introduction to java.util.stream API in Java
The `java.util.stream` package in Java provides a powerful way to process collections of objects in a functional style. It was introduced in Java 8 as part of the Java Collections Framework.
### What is a Stream?
@@ -14,7 +14,7 @@ A Stream in Java represents a sequence of elements and supports different operat
- **Reducing:** Performs a reduction on the elements of the stream.
- **Sorting:** Sorts the elements of the stream based on a comparator.
-### Example
+### Example π‘
```java
import java.util.Arrays;
import java.util.List;
@@ -102,13 +102,13 @@ public class Main {
}
}
```
-### Conclusion
+### Conclusion π
Creating Streams from collections in Java is straightforward and allows for concise and expressive code. Streams provide powerful features for processing data in a functional style.
## Streams have no Storage
Streams in Java are not data storage containers; instead, they provide a way to process elements from a source (such as a collection, array, or I/O channel) in a functional and declarative style. Streams operate on data elements in a sequence and allow for various operations to be performed on those elements, such as filtering, mapping, sorting, and reducing.
-### Example
+### Example π‘
Consider the following example that demonstrates the use of streams to process a list of integers:
```java
@@ -138,14 +138,14 @@ public class Main {
```
In this example:
-We create a list of integers numbers.
-Example 1 demonstrates filtering even numbers using the filter() operation.
-Example 2 shows mapping each number to its square using the map() operation.
-Example 3 illustrates reducing the numbers to their sum using the reduce() operation.
-### Features
-Provides a comprehensive understanding of streams in Java.
-Clarifies that streams are not storage containers but rather enable efficient processing of data elements.
-Offers examples of common stream operations including filtering, mapping, and reducing.
+- We create a list of integers numbers.
+- Example 1 demonstrates filtering even numbers using the filter() operation.
+- Example 2 shows mapping each number to its square using the map() operation.
+- Example 3 illustrates reducing the numbers to their sum using the reduce() operation.
+### Features π
+- Provides a comprehensive understanding of streams in Java.
+- Clarifies that streams are not storage containers but rather enable efficient processing of data elements.
+- Offers examples of common stream operations including filtering, mapping, and reducing.
## Introduction to Streams Pipeline
Streams Pipeline is a powerful feature introduced in Java 8, allowing developers to perform complex data processing tasks with concise and expressive code.
@@ -153,11 +153,11 @@ Streams Pipeline is a powerful feature introduced in Java 8, allowing developers
### What is Streams Pipeline?
Streams Pipeline is a sequence of aggregate operations (such as filter, map, reduce, etc.) that are applied to a stream of elements to perform a specific task. It enables functional-style operations on collections, making code more readable, concise, and efficient.
-### Key Concepts
-Stream: Represents a sequence of elements and supports aggregate operations.
-Intermediate Operations: Operations such as filter, map, sorted, etc., which transform a stream into another stream. These operations are lazy and do not produce any result until a terminal operation is executed.
-Terminal Operations: Operations such as forEach, collect, reduce, etc., which produce a result or side-effect. Terminal operations trigger the execution of the intermediate operations.
-Stateless vs. Stateful Operations: Stateless operations do not rely on the state of other elements in the stream, whereas stateful operations may depend on the state of other elements.
+### Key Concepts π
+- **Stream :** Represents a sequence of elements and supports aggregate operations.
+- **Intermediate Operations :** Operations such as filter, map, sorted, etc., which transform a stream into another stream. These operations are lazy and do not produce any result until a terminal operation is executed.
+- **Terminal Operations :** Operations such as forEach, collect, reduce, etc., which produce a result or side-effect. Terminal operations trigger the execution of the intermediate operations.
+- **Stateless vs. Stateful Operations :** Stateless operations do not rely on the state of other elements in the stream, whereas stateful operations may depend on the state of other elements.
### Getting Started
To use Streams Pipeline in your Java project:
@@ -168,7 +168,7 @@ Import the necessary packages:
import java.util.stream.Stream;
```
Start using Streams Pipeline in your code.
-### Examples
+### Examples π‘
Filtering elements
```java
List names = Arrays.asList("John", "Alice", "Bob", "David");
@@ -215,7 +215,7 @@ Here,
### Return Value
- The `map()` function returns a new Stream consisting of the results of applying the given function to the elements of this stream.
-### Example
+### Example π‘
```java
import java.util.Arrays;
import java.util.List;
@@ -243,7 +243,7 @@ In this example, the map() function is used to convert each name in the names li
### Advantages
- **Concise :** Allows concise and readable code for transforming elements of a stream.
- **Pipeline Friendly :** Fits well into stream pipelines, enabling powerful data processing operations.
-### Conclusion
+### Conclusion π
The `map()` function in Java Streams is a powerful tool for transforming elements of a stream according to a specified function. It promotes functional programming practices and enables elegant and efficient data processing operations.
## Java Streams `flatMap()` Function
@@ -265,7 +265,7 @@ Here,
### Return Value
-The `flatMap()` function returns a new Stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
-### Example
+### Example π‘
```java
import java.util.Arrays;
import java.util.List;
@@ -297,8 +297,59 @@ In this example, the `flatMap()` function is used to flatten a list of lists int
### Advantages
- **Streamlining Data Processing :** Simplifies data processing by flattening nested structures.
- **Versatility :** Offers a wide range of applications, from flattening collections to filtering out empty elements.
-### Conclusion
+### Conclusion π
The `flatMap()` function in Java Streams is a powerful tool for flattening nested collections or streams within a stream, allowing for streamlined data processing and transformation. It promotes concise and readable code and enables efficient manipulation of complex data structures.
+## Java Streams `filter()` Function
+
+In Java, Streams provide a convenient way to work with sequences of elements. The `filter()` function is used to select elements from a stream based on a specified condition.
+
+### Syntax
+
+The syntax of the `filter()` function in Java Streams is as follows:
+
+```java
+Stream filter(Predicate super T> predicate)
+```
+Here,
+
+- ** Predicate super T> predicate :** A functional interface that represents a predicate (boolean-valued function) of one argument. The function returns true if the input argument matches the condition, otherwise false.
+### Parameters
+- **predicate :** The predicate to apply to each element of the stream. Only elements that satisfy the predicate will be included in the resulting stream.
+Return Value
+The `filter()` function returns a new Stream consisting of the elements that match the given predicate.
+
+### Example π‘
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class Main {
+ public static void main(String[] args) {
+ List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+
+ // Filter even numbers
+ List evenNumbers = numbers.stream()
+ .filter(n -> n % 2 == 0)
+ .collect(Collectors.toList());
+
+ System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]
+ }
+}
+```
+In this example, the `filter()` function is used to select only the even numbers from the numbers list.
+
+### Common Use Cases π
+- **Data Filtering :** Filtering elements based on specified criteria.
+- **Condition-based Selection :** Selecting elements that meet certain conditions.
+- **Data Cleaning :** Removing unwanted elements or outliers from a stream.
+### Advantages π
+- **Flexible Filtering :** Provides a flexible way to filter elements based on arbitrary conditions.
+- **Readability :** Improves code readability by clearly expressing the filtering criteria.
+- Performance :** Can lead to performance improvements by reducing the number of elements to process.
+### Conclusion π
+The `filter()` function in Java Streams is a powerful tool for selecting elements from a stream based on specified criteria. It promotes clean and expressive code and enables efficient data filtering and selection operations.
+
From 3865857815b61323b91206336bfea890f775e95d Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 16 Apr 2024 19:41:17 +0530
Subject: [PATCH 213/236] Update section26.README.md
---
section26.README.md | 54 +++++++++++++++++++++++++++++++++++++++++++--
1 file changed, 52 insertions(+), 2 deletions(-)
diff --git a/section26.README.md b/section26.README.md
index 0136545..1679973 100644
--- a/section26.README.md
+++ b/section26.README.md
@@ -316,8 +316,8 @@ Here,
- ** Predicate super T> predicate :** A functional interface that represents a predicate (boolean-valued function) of one argument. The function returns true if the input argument matches the condition, otherwise false.
### Parameters
- **predicate :** The predicate to apply to each element of the stream. Only elements that satisfy the predicate will be included in the resulting stream.
-Return Value
-The `filter()` function returns a new Stream consisting of the elements that match the given predicate.
+### Return Value
+- The `filter()` function returns a new Stream consisting of the elements that match the given predicate.
### Example π‘
```java
@@ -351,5 +351,55 @@ In this example, the `filter()` function is used to select only the even numbers
### Conclusion π
The `filter()` function in Java Streams is a powerful tool for selecting elements from a stream based on specified criteria. It promotes clean and expressive code and enables efficient data filtering and selection operations.
+## Java Streams `limit()` Function
+In Java, Streams provide a convenient way to work with sequences of elements. The `limit()` function is used to reduce the size of a stream to a specified maximum number of elements.
+
+### Syntax
+
+The syntax of the `limit()` function in Java Streams is as follows:
+
+```java
+Stream limit(long maxSize);
+```
+
+Here,
+- **maxSize :** The maximum number of elements the resulting stream should contain.
+### Parameters
+- **maxSize :** The maximum number of elements to be present in the resulting stream.
+### Return Value
+- The `limit() function returns a new Stream consisting of the first maxSize elements of the original stream.
+
+### Example
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class Main {
+ public static void main(String[] args) {
+ List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+
+ // Limit to first 5 elements
+ List limitedNumbers = numbers.stream()
+ .limit(5)
+ .collect(Collectors.toList());
+
+ System.out.println(limitedNumbers); // Output: [1, 2, 3, 4, 5]
+ }
+}
+```
+In this example, the limit() function is used to restrict the stream to the first 5 elements of the numbers list.
+
+### Common Use Cases
+- **Pagination :** Limiting the number of elements displayed on a page.
+- **Performance Optimization :** Reducing processing time by limiting the number of elements processed.
+- **Sampling :** Extracting a subset of elements for analysis or testing.
+### Advantages
+**Control :** Provides control over the size of the stream, allowing for efficient memory usage.
+**Performance Optimization :** Can lead to performance improvements by reducing the number of elements processed.
+**Tailoring Output :** Allows tailoring the output to specific requirements, such as display limitations.
+### Conclusion
+The `limit()` function in Java Streams is a useful tool for restricting the size of a stream to a specified maximum number of elements. It promotes efficient data processing and enables tailored output based on specific requirements.
+
From b497a160fed688ed4bef6f27f0d765224e816ef8 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 16 Apr 2024 19:46:19 +0530
Subject: [PATCH 214/236] Update section26.README.md
---
section26.README.md | 57 ++++++++++++++++++++++++++++++++++++++++++---
1 file changed, 54 insertions(+), 3 deletions(-)
diff --git a/section26.README.md b/section26.README.md
index 1679973..2fe2048 100644
--- a/section26.README.md
+++ b/section26.README.md
@@ -369,7 +369,7 @@ Here,
### Return Value
- The `limit() function returns a new Stream consisting of the first maxSize elements of the original stream.
-### Example
+### Example π‘
```java
import java.util.Arrays;
import java.util.List;
@@ -394,12 +394,63 @@ In this example, the limit() function is used to restrict the stream to the firs
- **Pagination :** Limiting the number of elements displayed on a page.
- **Performance Optimization :** Reducing processing time by limiting the number of elements processed.
- **Sampling :** Extracting a subset of elements for analysis or testing.
-### Advantages
+### Advantages π
**Control :** Provides control over the size of the stream, allowing for efficient memory usage.
**Performance Optimization :** Can lead to performance improvements by reducing the number of elements processed.
**Tailoring Output :** Allows tailoring the output to specific requirements, such as display limitations.
-### Conclusion
+### Conclusion π
The `limit()` function in Java Streams is a useful tool for restricting the size of a stream to a specified maximum number of elements. It promotes efficient data processing and enables tailored output based on specific requirements.
+## Java Streams `skip()` Function
+In Java, Streams provide a convenient way to work with sequences of elements. The `skip()` function is used to bypass a specified number of elements in a stream, returning a new stream without those elements.
+
+### Syntax
+
+The syntax of the `skip()` function in Java Streams is as follows:
+
+```java
+Stream skip(long n);
+```
+
+Here,
+
+- `n `: The number of elements to skip.
+### Parameters
+- `n `: The number of elements to bypass in the stream.
+### Return Value
+The `skip()` function returns a new Stream consisting of the remaining elements of the original stream after skipping the specified number of elements.
+
+### Example π‘
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class Main {
+ public static void main(String[] args) {
+ List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+
+ // Skip the first 5 elements
+ List remainingNumbers = numbers.stream()
+ .skip(5)
+ .collect(Collectors.toList());
+
+ System.out.println(remainingNumbers); // Output: [6, 7, 8, 9, 10]
+ }
+}
+```
+In this example, the `skip()` function is used to skip the first 5 elements of the numbers list and return the remaining elements.
+
+### Common Use Cases
+- **Pagination :** Skipping elements for displaying results on subsequent pages.
+- **Data Skimming :** Bypassing irrelevant or unwanted elements from the beginning of a stream.
+- **Data Transformation :** Pre-processing data by skipping initial records or headers.
+### Advantages π
+**Flexibility :** Provides flexibility in skipping a specific number of elements from the beginning of a stream.
+**Efficient Data Processing :** Enables efficient processing of large datasets by skipping unnecessary initial elements.
+**Tailoring Output :** Allows tailoring the output to specific requirements by excluding irrelevant data.
+### Conclusion π
+The `skip()` function in Java Streams is a valuable tool for bypassing a specified number of elements in a stream, enabling efficient data processing and tailored output based on specific requirements.
+
From fbfa5a55caf0abf90263ce87595bb94ab0b361d2 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 16 Apr 2024 20:10:55 +0530
Subject: [PATCH 215/236] Update section26.README.md
---
section26.README.md | 62 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 62 insertions(+)
diff --git a/section26.README.md b/section26.README.md
index 2fe2048..d575fc9 100644
--- a/section26.README.md
+++ b/section26.README.md
@@ -452,5 +452,67 @@ In this example, the `skip()` function is used to skip the first 5 elements of t
### Conclusion π
The `skip()` function in Java Streams is a valuable tool for bypassing a specified number of elements in a stream, enabling efficient data processing and tailored output based on specific requirements.
+## Java Streams `reduce()` Function
+n Java, Streams provide a powerful way to work with sequences of elements. The `reduce()` function is used to combine the elements of a stream into a single result by applying a binary operator.
+### Syntax
+
+The syntax of the `reduce()` function in Java Streams is as follows:
+
+```java
+Optional reduce(BinaryOperator accumulator);
+```
+or
+
+```java
+T reduce(T identity, BinaryOperator accumulator);
+```
+
+Here,
+
+- **accumulator **: A BinaryOperator that combines two values into a single value.
+Parameters
+- **accumulator :** The binary operator used to accumulate the elements of the stream.
+
+- **identity :** The initial value of the accumulation.
+
+### Return Value
+- The `reduce()` function returns an Optional or the accumulated result of applying the binary operator to the elements of the stream.
+
+### Example
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
+public class Main {
+ public static void main(String[] args) {
+ List numbers = Arrays.asList(1, 2, 3, 4, 5);
+
+ // Example 1: Reduce to sum of elements
+ Optional sum = numbers.stream()
+ .reduce(Integer::sum);
+
+ System.out.println("Sum: " + sum.orElse(0)); // Output: Sum: 15
+
+ // Example 2: Reduce with initial value (10) to find the product
+ Integer product = numbers.stream()
+ .reduce(10, (a, b) -> a * b);
+
+ System.out.println("Product: " + product); // Output: Product: 1200
+ }
+}
+```
+In Example 1, the `reduce()` function is used to calculate the sum of all elements in the numbers list. In Example 2, the `reduce()` function with an initial value is used to find the product of all elements in the list.
+
+### Common Use Cases
+- **Aggregation :** Combining elements of a stream into a single result, such as summing or multiplying.
+- **Custom Reduction :** Performing custom reduction operations on stream elements.
+- **Data Analysis :** Calculating statistical measures or aggregating data.
+### Advantages
+- **Powerful Aggregation :** Enables powerful aggregation operations on stream elements.
+- **Flexibility :** Provides flexibility in defining custom reduction operations.
+- **Error Handling :** Returns an Optional to handle scenarios where the stream is empty.
+### Conclusion
+The `reduce()` function in Java Streams is a versatile tool for aggregating the elements of a stream into a single result. It supports various aggregation operations and provides flexibility in defining custom reduction logic, making it a fundamental building block for stream processing tasks.
From d60d75574c3bb88b3b2da54402423fcf0f0e2f49 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 16 Apr 2024 20:13:54 +0530
Subject: [PATCH 216/236] Update section26.README.md
---
section26.README.md | 56 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 56 insertions(+)
diff --git a/section26.README.md b/section26.README.md
index d575fc9..f72f178 100644
--- a/section26.README.md
+++ b/section26.README.md
@@ -516,3 +516,59 @@ In Example 1, the `reduce()` function is used to calculate the sum of all elemen
### Conclusion
The `reduce()` function in Java Streams is a versatile tool for aggregating the elements of a stream into a single result. It supports various aggregation operations and provides flexibility in defining custom reduction logic, making it a fundamental building block for stream processing tasks.
+## Java Streams `collect()` Function
+In Java, Streams provide a powerful way to work with sequences of elements. The `collect()` function is used to accumulate the elements of a stream into a collection or a single value.
+
+### Syntax
+
+The syntax of the `collect()` function in Java Streams is as follows:
+
+```java
+ R collect(Collector super T,A,R> collector);
+```
+
+Here,
+
+- **collector :** A Collector that describes how to accumulate elements into a result container.
+Parameters
+- **collector :** The collector that specifies the way elements are collected into the result.
+### Return Value
+- The `collect()` function returns the result of the accumulation, which can be of any type specified by the collector.
+
+### Example
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class Main {
+ public static void main(String[] args) {
+ List words = Arrays.asList("apple", "banana", "cherry");
+
+ // Example 1: Collect elements into a List
+ List collectedList = words.stream()
+ .collect(Collectors.toList());
+
+ System.out.println("Collected List: " + collectedList); // Output: Collected List: [apple, banana, cherry]
+
+ // Example 2: Concatenate elements into a single String
+ String concatenatedString = words.stream()
+ .collect(Collectors.joining(", "));
+
+ System.out.println("Concatenated String: " + concatenatedString); // Output: Concatenated String: apple, banana, cherry
+ }
+}
+```
+In Example 1, the `collect()` function is used to accumulate elements into a List. In Example 2, it's used to concatenate elements into a single String separated by commas.
+
+### Common Use Cases
+- **Collection Creation :** Accumulating elements into collections such as List, Set, or Map.
+- **String Concatenation :** Joining elements into a single String with a specified delimiter.
+ -**Custom Accumulation :** Performing custom accumulation operations based on specific requirements.
+### Advantages
+- **Flexible Collection :** Provides flexibility in accumulating elements into various types of collections.
+- **Concise Code :** Allows concise and readable code for collecting and processing stream elements.
+- **Efficient Data Handling :** Offers efficient handling of large datasets by accumulating elements in a single operation.
+### Conclusion
+The `collect()` function in Java Streams is a versatile tool for accumulating elements of a stream into a collection or a single value. It supports various collection types and customization options, making it a fundamental operation for stream processing tasks.
+
From 1fe28134700c54054d7f9bce39495db511b0a868 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 16 Apr 2024 20:18:09 +0530
Subject: [PATCH 217/236] Update section26.README.md
---
section26.README.md | 55 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 55 insertions(+)
diff --git a/section26.README.md b/section26.README.md
index f72f178..2800407 100644
--- a/section26.README.md
+++ b/section26.README.md
@@ -572,3 +572,58 @@ In Example 1, the `collect()` function is used to accumulate elements into a Lis
### Conclusion
The `collect()` function in Java Streams is a versatile tool for accumulating elements of a stream into a collection or a single value. It supports various collection types and customization options, making it a fundamental operation for stream processing tasks.
+## Java Streams `collectingAndThen()` Function
+In Java, Streams provide a powerful way to work with sequences of elements. The `collectingAndThen()` function is used to perform an additional operation on the result of the `collect()` function.
+
+## Syntax
+
+The syntax of the `collectingAndThen()` function in Java Streams is as follows:
+
+```java
+ R collectingAndThen(Collector super T,A,R> downstream, Function finisher);
+```
+
+Here,
+
+- **downstream :** A Collector that describes how to accumulate elements into a result container.
+- **finisher :** A function to be applied to the result of the collection operation.
+Parameters
+- **downstream :** The collector that specifies the way elements are collected into the result.
+- **finisher :** The function to be applied to the result of the collection operation.
+### Return Value
+The `collectingAndThen()` function returns the result of applying the finisher function to the result of the collection operation.
+
+### Example
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class Main {
+ public static void main(String[] args) {
+ List words = Arrays.asList("apple", "banana", "cherry");
+
+ // Example: Collect elements into a List and then find the size
+ int sizeOfList = words.stream()
+ .collect(Collectors.collectingAndThen(
+ Collectors.toList(),
+ List::size
+ ));
+
+ System.out.println("Size of List: " + sizeOfList); // Output: Size of List: 3
+ }
+}
+```
+In this example, the `collectingAndThen()` function is used to first collect elements into a List and then apply the `size()` function to determine the size of the list.
+
+### Common Use Cases
+- **Post-Processing :** Performing additional operations on the result of a collection operation.
+- **Transformation :** Transforming the result of collection into a different type or format.
+- **Validation :** Applying validation checks or assertions on the collected result.
+### Advantages
+- **Enhanced Functionality :** Extends the capabilities of the collect() function by enabling post-processing operations.
+- **Streamlining Operations :** Allows chaining multiple operations in a concise and readable manner.
+- **Customization :** Provides flexibility in defining custom finishing operations based on specific requirements.
+### Conclusion
+The `collectingAndThen()` function in Java Streams enhances the functionality of the `collect()` operation by enabling additional post-processing operations on the collected result. It supports various use cases such as transformation, validation, and custom finishing operations, making it a valuable tool for stream processing tasks.
+
From 4fccb3e7bcfbecf7501af50257201725d6ce058c Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 16 Apr 2024 20:25:12 +0530
Subject: [PATCH 218/236] Update section26.README.md
---
section26.README.md | 104 +++++++++++++++++++++++++++++++++++++++++---
1 file changed, 97 insertions(+), 7 deletions(-)
diff --git a/section26.README.md b/section26.README.md
index 2800407..a53ccb3 100644
--- a/section26.README.md
+++ b/section26.README.md
@@ -479,7 +479,7 @@ Parameters
### Return Value
- The `reduce()` function returns an Optional or the accumulated result of applying the binary operator to the elements of the stream.
-### Example
+### Example π‘
```java
import java.util.Arrays;
import java.util.List;
@@ -513,7 +513,7 @@ In Example 1, the `reduce()` function is used to calculate the sum of all elemen
- **Powerful Aggregation :** Enables powerful aggregation operations on stream elements.
- **Flexibility :** Provides flexibility in defining custom reduction operations.
- **Error Handling :** Returns an Optional to handle scenarios where the stream is empty.
-### Conclusion
+### Conclusion π
The `reduce()` function in Java Streams is a versatile tool for aggregating the elements of a stream into a single result. It supports various aggregation operations and provides flexibility in defining custom reduction logic, making it a fundamental building block for stream processing tasks.
## Java Streams `collect()` Function
@@ -535,7 +535,7 @@ Parameters
### Return Value
- The `collect()` function returns the result of the accumulation, which can be of any type specified by the collector.
-### Example
+### Example π‘
```java
import java.util.Arrays;
import java.util.List;
@@ -569,13 +569,13 @@ In Example 1, the `collect()` function is used to accumulate elements into a Lis
- **Flexible Collection :** Provides flexibility in accumulating elements into various types of collections.
- **Concise Code :** Allows concise and readable code for collecting and processing stream elements.
- **Efficient Data Handling :** Offers efficient handling of large datasets by accumulating elements in a single operation.
-### Conclusion
+### Conclusion π
The `collect()` function in Java Streams is a versatile tool for accumulating elements of a stream into a collection or a single value. It supports various collection types and customization options, making it a fundamental operation for stream processing tasks.
## Java Streams `collectingAndThen()` Function
In Java, Streams provide a powerful way to work with sequences of elements. The `collectingAndThen()` function is used to perform an additional operation on the result of the `collect()` function.
-## Syntax
+### Syntax
The syntax of the `collectingAndThen()` function in Java Streams is as follows:
@@ -593,7 +593,7 @@ Parameters
### Return Value
The `collectingAndThen()` function returns the result of applying the finisher function to the result of the collection operation.
-### Example
+### Example π‘
```java
import java.util.Arrays;
import java.util.List;
@@ -624,6 +624,96 @@ In this example, the `collectingAndThen()` function is used to first collect ele
- **Enhanced Functionality :** Extends the capabilities of the collect() function by enabling post-processing operations.
- **Streamlining Operations :** Allows chaining multiple operations in a concise and readable manner.
- **Customization :** Provides flexibility in defining custom finishing operations based on specific requirements.
-### Conclusion
+### Conclusion π
The `collectingAndThen()` function in Java Streams enhances the functionality of the `collect()` operation by enabling additional post-processing operations on the collected result. It supports various use cases such as transformation, validation, and custom finishing operations, making it a valuable tool for stream processing tasks.
+## Java Streams `groupingBy()` and `partitioningBy()` Functions
+In Java, Streams provide powerful operations for grouping and partitioning elements based on specific criteria. The `groupingBy()` function is used to group elements of a stream by a classification function, while the `partitioningBy()` function is used to partition elements into two groups based on a predicate.
+
+### `groupingBy()` Function
+
+The `groupingBy()` function in Java Streams is used to group elements of a stream by a classification function.
+
+### Syntax
+
+The syntax of the `groupingBy()` function is as follows:
+
+```java
+groupingBy(Function super T, ? extends K> classifier);
+```
+
+Here,
+
+- **classifier :** A function that classifies stream elements into groups based on certain criteria.
+### Parameters
+- **classifier :** The classification function used to group elements.
+### Return Value
+- The `groupingBy()` function returns a Collector that categorizes elements of the stream into groups.
+
+### Example π‘
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class Main {
+ public static void main(String[] args) {
+ List words = Arrays.asList("apple", "banana", "cherry", "blueberry", "avocado");
+
+ Map> groupedByFirstLetter = words.stream()
+ .collect(Collectors.groupingBy(word -> word.charAt(0)));
+
+ System.out.println("Grouped by first letter: " + groupedByFirstLetter);
+ }
+}
+```
+In this example, the `groupingBy()` function is used to group words by their first letter.
+
+### partitioningBy() Function
+The `partitioningBy()` function in Java Streams is used to partition elements into two groups based on a predicate.
+
+### Syntax
+The syntax of the` partitioningBy()` function is as follows:
+
+```java
+partitioningBy(Predicate super T> predicate);
+```
+Here,
+
+- **predicate :** A predicate function that determines the partitioning criteria.
+Parameters
+- **predicate :** The predicate used to partition elements.
+### Return Value
+The `partitioningBy()` function returns a Collector that partitions elements into two groups based on the given predicate.
+
+### Example π‘
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class Main {
+ public static void main(String[] args) {
+ List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+
+ Map> partitionedEvenOdd = numbers.stream()
+ .collect(Collectors.partitioningBy(num -> num % 2 == 0));
+
+ System.out.println("Partitioned into even and odd: " + partitionedEvenOdd);
+ }
+}
+```
+In this example, the partitioningBy() function is used to partition numbers into even and odd.
+
+### Common Use Cases
+- **groupingBy() :** Grouping elements by a specific attribute or key.
+- **partitioningBy() :** Partitioning elements based on a binary condition (e.g., true or false).
+### Advantages
+- **Data Organization :** Helps organize data into meaningful groups or partitions.
+- **Efficient Data Processing :** Enables efficient processing of large datasets by grouping or partitioning elements based on specific criteria.
+- **Streamlining Operations :** Provides a concise and readable way to perform grouping and partitioning operations.
+### Conclusion π
+The `groupingBy()` and `partitioningBy()` functions in Java Streams are powerful tools for organizing and categorizing elements based on specific criteria. They support various use cases such as data grouping, partitioning, and analysis, making them essential for stream processing tasks.
+
From 5557cf1ba976cce7e87f821c37b6f3ff38c1e633 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 16 Apr 2024 20:29:43 +0530
Subject: [PATCH 219/236] Update section26.README.md
---
section26.README.md | 84 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 84 insertions(+)
diff --git a/section26.README.md b/section26.README.md
index a53ccb3..6e7191d 100644
--- a/section26.README.md
+++ b/section26.README.md
@@ -717,3 +717,87 @@ In this example, the partitioningBy() function is used to partition numbers into
### Conclusion π
The `groupingBy()` and `partitioningBy()` functions in Java Streams are powerful tools for organizing and categorizing elements based on specific criteria. They support various use cases such as data grouping, partitioning, and analysis, making them essential for stream processing tasks.
+## Java Streams `finding()` and `matching()` Functions
+In Java, Streams provide convenient operations for finding and matching elements based on specific conditions. The `finding()` function is used to find elements in a stream, while the `matching()` function is used to check if all, any, or none of the elements match a given predicate.
+
+### `finding()` Function
+
+- The `finding()` function in Java Streams is used to find elements in a stream based on specific criteria.
+
+### Syntax
+
+- The syntax of the `finding()` function depends on the specific operation being performed, such as `findFirst()`, `findAny()`, and `max()`, `min()`.
+
+### Parameters
+
+- The parameters vary depending on the specific operation being performed.
+
+### Return Value
+
+ -The return value also varies depending on the specific operation being performed.
+
+### Example π‘
+
+```java
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
+public class Main {
+ public static void main(String[] args) {
+ List numbers = Arrays.asList(1, 2, 3, 4, 5);
+
+ // Find the first element in the stream
+ Optional firstElement = numbers.stream().findFirst();
+
+ System.out.println("First Element: " + firstElement.orElse(null));
+ }
+}
+```
+In this example, the `findFirst()` function is used to find the first element in the stream.
+
+### matching() Function
+The `matching()` function in Java Streams is used to check if all, any, or none of the elements in a stream match a given predicate.
+
+### Syntax
+The syntax of the `matching()` function is as follows:
+
+```java
+boolean allMatch(Predicate super T> predicate)
+boolean anyMatch(Predicate super T> predicate)
+boolean noneMatch(Predicate super T> predicate)
+```
+### Parameters
+- **predicate :** The predicate function used to check elements.
+### Return Value
+- **allMatch() :** Returns true if all elements match the given predicate, otherwise false.
+- **anyMatch() :** Returns true if any element matches the given predicate, otherwise false.
+- **noneMatch() :** Returns true if none of the elements match the given predicate, otherwise false.
+### Example π‘
+```java
+import java.util.Arrays;
+import java.util.List;
+
+public class Main {
+ public static void main(String[] args) {
+ List numbers = Arrays.asList(1, 2, 3, 4, 5);
+
+ // Check if all elements are even
+ boolean allEven = numbers.stream().allMatch(n -> n % 2 == 0);
+
+ System.out.println("All elements are even: " + allEven);
+ }
+}
+```
+In this example, the `allMatch()` function is used to check if all elements in the stream are even.
+
+### Common Use Cases
+- **finding() :** Finding specific elements in a stream, such as the first, last, maximum, or minimum element.
+- **matching() :** Checking if elements in a stream satisfy certain conditions, such as all, any, or none matching a given predicate.
+### Advantages
+- **Efficiency :** Provides efficient operations for finding elements and checking conditions in streams.
+- **Conciseness :** Enables concise and readable code for performing element search and matching operations.
+- **Flexibility :** Supports various operations for finding and matching elements, catering to diverse requirements.
+### Conclusion π
+The `finding()` and `matching()` functions in Java Streams are essential tools for searching for elements and checking conditions within streams. They offer efficient and concise operations for performing these tasks, making them valuable for stream processing tasks.
+
From 591df1b0eecbd8a2225eceeb822db41cac184b4c Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 17 Apr 2024 15:03:14 +0530
Subject: [PATCH 220/236] Update section26.README.md
---
section26.README.md | 88 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 88 insertions(+)
diff --git a/section26.README.md b/section26.README.md
index 6e7191d..1d6b5ba 100644
--- a/section26.README.md
+++ b/section26.README.md
@@ -801,3 +801,91 @@ In this example, the `allMatch()` function is used to check if all elements in t
### Conclusion π
The `finding()` and `matching()` functions in Java Streams are essential tools for searching for elements and checking conditions within streams. They offer efficient and concise operations for performing these tasks, making them valuable for stream processing tasks.
+### Streams in Java: Traversable Only Once
+Streams are an integral part of Java since the introduction of Java 8. They provide a powerful and efficient way to process collections of objects. However, one crucial characteristic of streams is that they are **traversable only once**.
+
+### What Does "Traversable Only Once" Mean?
+
+When you create a stream and perform operations on it, such as filtering, mapping, or reducing, the stream processes the elements in a pipeline fashion. Once you have consumed or processed the elements of the stream, the stream cannot be reused. Attempting to iterate over the stream again or perform any terminal operation on it will result in an `IllegalStateException`.
+
+### Why Are Streams Traversable Only Once?
+
+This characteristic is designed to promote efficiency and simplicity in stream processing. By limiting streams to a single traversal, Java can optimize various aspects of stream operations, such as lazy evaluation and reduced memory consumption.
+
+### Best Practices
+
+To avoid unexpected behavior and exceptions when working with streams, it's essential to keep in mind that streams are traversable only once. Here are some best practices:
+
+- **Create streams when needed:** Avoid storing streams in variables if you plan to traverse them multiple times. Instead, recreate the stream when necessary.
+- **Perform terminal operations judiciously:** Once you perform a terminal operation (e.g., `forEach`, `collect`, `reduce`), the stream is consumed. Make sure you have processed all necessary operations before calling a terminal operation.
+- **Consider intermediate operations:** Intermediate operations (e.g., `filter`, `map`, `flatMap`) do not trigger traversal of the stream. You can chain multiple intermediate operations before invoking a terminal operation.
+
+### Example π‘
+
+```java
+import java.util.stream.Stream;
+
+public class Main {
+ public static void main(String[] args) {
+ // Creating a stream
+ Stream stream = Stream.of("A", "B", "C");
+
+ // Performing intermediate operations
+ stream = stream.filter(s -> !s.equals("B")); // Filtering out "B"
+ stream = stream.map(String::toLowerCase); // Converting elements to lowercase
+
+ // Performing terminal operation
+ stream.forEach(System.out::println); // Prints "a" and "c"
+
+ // Attempting to reuse the stream will result in an IllegalStateException
+ // stream.forEach(System.out::println); // Throws IllegalStateException
+ }
+}
+```
+### Conclusion π
+Understanding that streams are traversable only once is crucial for effective and efficient stream processing in Java. By adhering to best practices and being mindful of this characteristic, you can leverage the full power of streams while avoiding common pitfalls.
+
+## Parallel Streams in Java
+Parallel streams are a feature introduced in Java 8 that allow for concurrent execution of stream operations. They provide an easy way to parallelize bulk operations on collections, potentially improving performance for computationally intensive tasks.
+
+### What Are Parallel Streams?
+
+In Java, streams are sequences of elements that support various operations to perform computations. Parallel streams leverage the multi-core architecture of modern CPUs by splitting the stream into multiple segments and processing each segment concurrently.
+
+Parallel streams can offer significant performance improvements for certain types of operations, especially when dealing with large datasets and computationally intensive tasks. However, they also come with some considerations and potential pitfalls, such as increased memory consumption and the need for proper synchronization in certain scenarios.
+
+### Example π‘
+
+- Let's demonstrate the usage of parallel streams with a simple example:
+
+ -Suppose we have a list of integers and we want to calculate the sum of squares of each element in parallel.
+
+```java
+import java.util.Arrays;
+
+public class ParallelStreamDemo {
+ public static void main(String[] args) {
+ // Create a list of integers
+ int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
+
+ // Calculate the sum of squares using parallel stream
+ long sum = Arrays.stream(numbers)
+ .parallel() // Convert stream to parallel stream
+ .mapToLong(x -> x * x) // Calculate square of each element
+ .sum(); // Sum up the squares
+
+ System.out.println("Sum of squares (parallel): " + sum);
+ }
+}
+```
+In this example, we convert the array of numbers into a parallel stream using the `parallel()` method. Then, we use the `mapToLong()` operation to calculate the square of each element and `sum()` operation to compute the total sum of squares. The parallel processing capability of the stream allows the computation to be distributed across multiple threads, potentially leading to improved performance.
+
+### Considerations
+While parallel streams can offer performance benefits, they are not always the best choice. Here are some considerations to keep in mind:
+
+- **Performance overhead :** Parallelizing stream operations incurs overhead due to thread management and synchronization, which may not always lead to performance gains, especially for small datasets or operations with low computational complexity.
+- **Concurrency issues :** Parallel streams introduce concurrency, which can lead to race conditions and other synchronization issues if not used correctly. Proper synchronization mechanisms should be employed when dealing with shared mutable state.
+- **Memory consumption :** Parallel streams may consume more memory than sequential streams due to the need to split the stream into segments and maintain intermediate results. This increased memory consumption can impact the performance of the application, especially in memory-constrained environments.
+### Conclusion π
+Parallel streams in Java provide a convenient way to parallelize stream operations and leverage multi-core processors for improved performance. However, they come with considerations such as performance overhead, concurrency issues, and increased memory consumption. By understanding when and how to use parallel streams effectively, developers can harness their power to optimize performance for computationally intensive tasks.
+
From bfeb675fcb91239cd0c5a0912c9e204784d3a208 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 17 Apr 2024 18:01:20 +0530
Subject: [PATCH 221/236] Create section27.README.md
---
section27.README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section27.README.md
diff --git a/section27.README.md b/section27.README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section27.README.md
@@ -0,0 +1 @@
+
From d1ad8ea22d221ff1232802905a22b4814db55f88 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 17 Apr 2024 18:45:16 +0530
Subject: [PATCH 222/236] Update section27.README.md
---
section27.README.md | 119 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 119 insertions(+)
diff --git a/section27.README.md b/section27.README.md
index 8b13789..f22b46a 100644
--- a/section27.README.md
+++ b/section27.README.md
@@ -1 +1,120 @@
+# Optional class
+The `Optional` class was introduced in Java 8 to address the problem of null references. It provides a container object that may or may not contain a non-null value. This can be useful for methods that may or may not return a value or when dealing with potentially null values returned from external sources.
+## Introduction
+
+The `Optional` class is part of the `java.util` package and provides methods for working with potentially null values without encountering NullPointerExceptions.
+
+## Usage
+
+### Creating Optional Objects
+
+You can create an `Optional` object using the static `of()` method, which requires a non-null value. Alternatively, you can use `ofNullable()` if the value might be null.
+
+```java
+import java.util.Optional;
+
+Optional nonEmpty = Optional.of("Hello");
+Optional empty = Optional.empty();
+Optional nullable = Optional.ofNullable(null);
+```
+### Accessing Values
+You can retrieve the contained value using the get() method, but it's recommended to use methods like orElse() or orElseGet() to provide a default value if the optional is empty.
+
+```java
+String value = nonEmpty.get(); // "Hello"
+String defaultVal = empty.orElse("Default Value");
+String defaultValSupplier = empty.orElseGet(() -> "Default Value from Supplier");
+```
+### Handling Absent Values
+To perform an action only if a value is present, you can use the ifPresent() method.
+
+```java
+nonEmpty.ifPresent(val -> System.out.println("Value is present: " + val));
+```
+### Best Practices
+Avoid using `get()` method directly, prefer `orElse()` or `orElseGet()` to handle absent values safely.
+Use `isPresent()` or `isEmpty()` to check if a value is present or absent.
+Be cautious when using `orElseThrow()` as it may introduce unnecessary complexity.
+### Examples
+Here's a simple example demonstrating the usage of Optional:
+
+```java
+import java.util.Optional;
+
+public class OptionalExample {
+ public static void main(String[] args) {
+ Optional optional = Optional.of("Hello");
+
+ // Printing value if present
+ optional.ifPresent(val -> System.out.println("Value is present: " + val));
+
+ // Using orElse to provide default value
+ String value = optional.orElse("Default Value");
+ System.out.println("Value: " + value);
+
+ // Using orElseThrow to throw exception if value is absent
+ String val = optional.orElseThrow(() -> new IllegalArgumentException("Value is absent"));
+ System.out.println("Value: " + val);
+ }
+}
+```
+### Conclusion
+The Optional class provides a concise and safe way to handle potentially null values in Java, reducing the risk of `NullPointerExceptions` and making code more readable and robust.
+
+### ifPresent() Method
+The `ifPresent()` method takes a consumer function as an argument and executes it if a value is present.
+
+```java
+optional.ifPresent(val -> System.out.println("Value is present: " + val));
+```
+### ifPresentOrElse() Method
+Introduced in Java 9, the `ifPresentOrElse()` method executes one of two given actions, depending on whether a value is present or not.
+
+```java
+optional.ifPresentOrElse(
+ val -> System.out.println("Value is present: " + val),
+ () -> System.out.println("Value is absent")
+);
+```
+### orElse() Method
+The `orElse()` method returns the value if present, otherwise returns the specified default value.
+
+```java
+String value = optional.orElse("Default Value");
+```
+### orElseGet() Method
+The `orElseGet()` method is similar to orElse(), but instead of a default value, it accepts a Supplier that provides the default value.
+
+```java
+String defaultValSupplier = empty.orElseGet(() -> "Default Value from Supplier");
+```
+### Best Practices
+- Avoid using `get()` method directly, prefer `orElse()` or `orElseGet()` to handle absent values safely.
+- Use `isPresent()` or `isEmpty()` to check if a value is present or absent.
+- Be cautious when using `orElseThrow()` as it may introduce unnecessary complexity.
+### Examples
+Here's a simple example demonstrating the usage of Optional:
+
+```java
+import java.util.Optional;
+
+public class OptionalExample {
+ public static void main(String[] args) {
+ Optional optional = Optional.of("Hello");
+
+ // Printing value if present
+ optional.ifPresent(val -> System.out.println("Value is present: " + val));
+
+ // Using orElse to provide default value
+ String value = optional.orElse("Default Value");
+ System.out.println("Value: " + value);
+
+ // Using orElseThrow to throw exception if value is absent
+ String val = optional.orElseThrow(() -> new IllegalArgumentException("Value is absent"));
+ System.out.println("Value: " + val);
+ }
+}
+```
+### Conclusion
+The Optional class provides a concise and safe way to handle potentially null values in Java, reducing the risk of `NullPointerExceptions` and making code more readable and robust.
From 9d3d98049ae8725abb72e693a3cfa734a5cb41e4 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 17 Apr 2024 18:58:18 +0530
Subject: [PATCH 223/236] Update section27.README.md
---
section27.README.md | 56 +++++++++++++++++++++++++++++++++++++++++----
1 file changed, 52 insertions(+), 4 deletions(-)
diff --git a/section27.README.md b/section27.README.md
index f22b46a..95f7ca3 100644
--- a/section27.README.md
+++ b/section27.README.md
@@ -1,4 +1,4 @@
-# Optional class
+# Optional class π
The `Optional` class was introduced in Java 8 to address the problem of null references. It provides a container object that may or may not contain a non-null value. This can be useful for methods that may or may not return a value or when dealing with potentially null values returned from external sources.
## Introduction
@@ -36,7 +36,7 @@ nonEmpty.ifPresent(val -> System.out.println("Value is present: " + val));
Avoid using `get()` method directly, prefer `orElse()` or `orElseGet()` to handle absent values safely.
Use `isPresent()` or `isEmpty()` to check if a value is present or absent.
Be cautious when using `orElseThrow()` as it may introduce unnecessary complexity.
-### Examples
+### Examples π‘
Here's a simple example demonstrating the usage of Optional:
```java
@@ -59,7 +59,7 @@ public class OptionalExample {
}
}
```
-### Conclusion
+### Conclusion π
The Optional class provides a concise and safe way to handle potentially null values in Java, reducing the risk of `NullPointerExceptions` and making code more readable and robust.
### ifPresent() Method
@@ -93,6 +93,54 @@ String defaultValSupplier = empty.orElseGet(() -> "Default Value from Supplier")
- Avoid using `get()` method directly, prefer `orElse()` or `orElseGet()` to handle absent values safely.
- Use `isPresent()` or `isEmpty()` to check if a value is present or absent.
- Be cautious when using `orElseThrow()` as it may introduce unnecessary complexity.
+### Examples π‘
+Here's a simple example demonstrating the usage of Optional:
+
+```java
+import java.util.Optional;
+
+public class OptionalExample {
+ public static void main(String[] args) {
+ Optional optional = Optional.of("Hello");
+
+ // Printing value if present
+ optional.ifPresent(val -> System.out.println("Value is present: " + val));
+
+ // Using orElse to provide default value
+ String value = optional.orElse("Default Value");
+ System.out.println("Value: " + value);
+
+ // Using orElseThrow to throw exception if value is absent
+ String val = optional.orElseThrow(() -> new IllegalArgumentException("Value is absent"));
+ System.out.println("Value: " + val);
+ }
+}
+```
+### Conclusion π
+The Optional class provides a concise and safe way to handle potentially null values in Java, reducing the risk of `NullPointerExceptions` and making code more readable and robust.
+
+### orElseThrow() Method
+The `orElseThrow()` method returns the value if present, otherwise throws an exception provided by the Supplier.
+
+```java
+String value = optional.orElseThrow(() -> new NoSuchElementException("Value is absent"));
+```
+### map() Method
+The `map()` method applies a given function to the value if present and returns an Optional describing the result, or an empty Optional if the value is absent.
+
+```java
+Optional lengthOptional = optional.map(String::length);
+```
+### filter() Method
+The `filter()` method returns an Optional describing the value if a predicate is true, otherwise returns an empty Optional.
+
+```java
+Optional filteredOptional = optional.filter(val -> val.startsWith("H"));
+```
+### Best Practices
+- Avoid using `get()` method directly, prefer `orElse() or orElseGet() to handle absent values safely.
+- Use `isPresent()` or `isEmpty()` to check if a value is present or absent.
+- Be cautious when using orElseThrow() as it may introduce unnecessary complexity.
### Examples
Here's a simple example demonstrating the usage of Optional:
@@ -117,4 +165,4 @@ public class OptionalExample {
}
```
### Conclusion
-The Optional class provides a concise and safe way to handle potentially null values in Java, reducing the risk of `NullPointerExceptions` and making code more readable and robust.
+The Optional class provides a concise and safe way to handle potentially null values in Java, reducing the risk of NullPointerExceptions and making code more readable and robust.
From 45d142c1adc307851abb6afb52388cb9406c9e34 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 17 Apr 2024 19:05:39 +0530
Subject: [PATCH 224/236] Update section27.README.md
---
section27.README.md | 33 +++++++++++++++++++++++++++++++--
1 file changed, 31 insertions(+), 2 deletions(-)
diff --git a/section27.README.md b/section27.README.md
index 95f7ca3..e320b5d 100644
--- a/section27.README.md
+++ b/section27.README.md
@@ -141,7 +141,7 @@ Optional filteredOptional = optional.filter(val -> val.startsWith("H"));
- Avoid using `get()` method directly, prefer `orElse() or orElseGet() to handle absent values safely.
- Use `isPresent()` or `isEmpty()` to check if a value is present or absent.
- Be cautious when using orElseThrow() as it may introduce unnecessary complexity.
-### Examples
+### Examples π‘
Here's a simple example demonstrating the usage of Optional:
```java
@@ -164,5 +164,34 @@ public class OptionalExample {
}
}
```
-### Conclusion
+### Conclusion π
The Optional class provides a concise and safe way to handle potentially null values in Java, reducing the risk of NullPointerExceptions and making code more readable and robust.
+### Quick tip to filter Null elements with Stream API
+You can filter out null elements from a Stream using the `filter()` method along with a null-check condition. Here's a quick tip using the Stream API:
+
+```java
+import java.util.stream.Stream;
+import java.util.List;
+import java.util.Objects;
+
+public class Main {
+ public static void main(String[] args) {
+ List listWithNulls = List.of("a", null, "b", null, "c");
+
+ // Filter out null elements using Stream API
+ List listWithoutNulls = listWithNulls.stream()
+ .filter(Objects::nonNull)
+ .toList();
+
+ // Print the list without null elements
+ System.out.println("List without nulls: " + listWithoutNulls);
+ }
+}
+```
+In this example:
+
+- We have a list `listWithNulls` containing some elements along with null values.
+- We use the `stream()` method to convert the list into a Stream.
+- We apply the `filter()` method with a predicate Objects::nonNull to exclude null elements.
+- Finally, we collect the filtered elements into a new list using the `toList()` method introduced in Java 16.
+- This results in a new list `listWithoutNulls` containing only non-null elements.
From 84461933174e6804f8fb7c7e4d21e6f109335569 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 17 Apr 2024 19:06:53 +0530
Subject: [PATCH 225/236] Create section28.README.md
---
section28.README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section28.README.md
diff --git a/section28.README.md b/section28.README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section28.README.md
@@ -0,0 +1 @@
+
From b3e2df95a76e6aa864be35fbd34a206fcf988719 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Wed, 17 Apr 2024 19:33:42 +0530
Subject: [PATCH 226/236] Update section28.README.md
---
section28.README.md | 203 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 203 insertions(+)
diff --git a/section28.README.md b/section28.README.md
index 8b13789..1fd7618 100644
--- a/section28.README.md
+++ b/section28.README.md
@@ -1 +1,204 @@
+# Multithreading in Java
+Multithreading in Java refers to the ability of a Java program to execute multiple threads concurrently. A thread in Java represents an independent path of execution within a program. Multithreading allows a program to perform multiple tasks simultaneously, enhancing performance and responsiveness.
+
+In Java, multithreading is achieved primarily by using two mechanisms:
+
+Extending the Thread class: You can create a new class that extends the Thread class and override its `run()` method to define the code that will run concurrently. Then, you instantiate objects of this class and call their `start()` method to begin execution.
+
+```java
+class MyThread extends Thread {
+ public void run() {
+ // Code to be executed concurrently
+ }
+}
+```
+Implementing the Runnable interface: Alternatively, you can implement the Runnable interface, which defines a single method run(), and pass an instance of your class to a Thread object. This method is often preferred because Java doesn't support multiple inheritance, and implementing interfaces is more flexible than extending classes.
+
+```java
+class MyRunnable implements Runnable {
+ public void run() {
+ // Code to be executed concurrently
+ }
+}
+```
+Then, you create a Thread object and pass an instance of MyRunnable to it:
+
+```java
+MyRunnable myRunnable = new MyRunnable();
+Thread thread = new Thread(myRunnable);
+thread.start();
+```
+Multithreading allows different parts of a program to execute simultaneously, thus making the program more responsive, efficient, and capable of handling multiple tasks concurrently. However, it also introduces challenges such as synchronization and coordination between threads to avoid issues like race conditions and deadlocks. Java provides various mechanisms and classes, such as locks, mutexes, and synchronized blocks, to address these challenges and ensure safe concurrent execution.
+
+## How Multiple Threads Improve Performance
+In Java programming, threading allows you to execute multiple tasks concurrently, thus improving performance by leveraging the computational resources more effectively. This README provides an overview of how multiple threads improve performance in Java.
+
+### Benefits of Multithreading
+- **1. Concurrency :**
+Multithreading enables concurrent execution of tasks, allowing different parts of a program to run simultaneously. This concurrency leads to better resource utilization and faster execution of tasks.
+- **2. Parallelism:**
+With multithreading, tasks can be executed in parallel on multicore processors. This parallelism leads to significant performance improvements, especially for CPU-bound tasks.
+- **3. Responsiveness :**
+By offloading time-consuming tasks to separate threads, multithreading ensures that the application remains responsive to user input. This is crucial for creating interactive and user-friendly applications.
+- **4. Scalability :**
+Multithreading facilitates scalability by enabling the distribution of tasks across multiple threads. As the workload increases, more threads can be created to handle the additional load, resulting in better scalability.
+- **5. Resource Utilization :**
+Multithreading allows better utilization of system resources such as CPU and memory. By keeping the CPU busy with multiple threads, idle time is reduced, leading to improved overall performance.
+- **6. Asynchronous Execution :**
+Multithreading enables asynchronous execution of tasks, where a thread can continue executing other tasks while waiting for I/O operations or other blocking tasks to complete. This improves overall throughput and responsiveness.
+### How to Implement Multithreading in Java
+In Java, multithreading can be implemented using the Thread class or the Runnable interface. Here's a basic example using the Thread class:
+
+```java
+public class MyThread extends Thread {
+ public void run() {
+ // Code to be executed concurrently
+ }
+}
+
+public class Main {
+ public static void main(String[] args) {
+ MyThread thread1 = new MyThread();
+ MyThread thread2 = new MyThread();
+
+ thread1.start();
+ thread2.start();
+ }
+}
+```
+Alternatively, you can use the Runnable interface:
+
+```java
+public class MyRunnable implements Runnable {
+ public void run() {
+ // Code to be executed concurrently
+ }
+}
+
+public class Main {
+ public static void main(String[] args) {
+ Thread thread1 = new Thread(new MyRunnable());
+ Thread thread2 = new Thread(new MyRunnable());
+
+ thread1.start();
+ thread2.start();
+ }
+}
+```
+### Conclusion
+Multithreading is a powerful technique in Java programming for improving performance and scalability. By allowing concurrent execution of tasks, multithreading maximizes CPU utilization, enhances responsiveness, and enables efficient resource utilization. When used effectively, multithreading can significantly boost the performance of Java applications.
+
+## Creating Threads in Java
+Threads in Java allow you to execute multiple tasks concurrently, improving the efficiency of your programs by leveraging the available resources. Here's a guide on how to create threads in Java:
+
+### 1. Extending the Thread Class
+You can create a thread in Java by extending the Thread class and overriding its `run()` method.
+
+```java
+public class MyThread extends Thread {
+ public void run() {
+ // Code to be executed in the thread
+ System.out.println("Thread is running");
+ }
+
+ public static void main(String[] args) {
+ MyThread thread = new MyThread();
+ thread.start(); // Start the thread
+ }
+}
+```
+### 2. Implementing the Runnable Interface
+Alternatively, you can implement the Runnable interface and pass it to a Thread object.
+
+```java
+public class MyRunnable implements Runnable {
+ public void run() {
+ // Code to be executed in the thread
+ System.out.println("Thread is running");
+ }
+
+ public static void main(String[] args) {
+ MyRunnable myRunnable = new MyRunnable();
+ Thread thread = new Thread(myRunnable);
+ thread.start(); // Start the thread
+ }
+}
+```
+### 3. Using Lambda Expressions
+With Java 8 and later versions, you can use lambda expressions to define the `run()` method directly.
+
+```java
+public class Main {
+ public static void main(String[] args) {
+ Thread thread = new Thread(() -> {
+ // Code to be executed in the thread
+ System.out.println("Thread is running");
+ });
+ thread.start(); // Start the thread
+ }
+}
+```
+### Thread Lifecycle
+Understanding the lifecycle of a thread is essential for effective thread management. The main states of a thread are:
+
+- **New :** When a thread is instantiated.
+- **Runnable :** When a thread is ready to run but waiting for CPU time.
+- **Running :** When the thread is executing its task.
+- **Blocked/Waiting :** When a thread is waiting for some resource.
+- **Terminated :** When the thread has completed its task or terminated abruptly.
+### Thread Synchronization
+When multiple threads access shared resources, synchronization is essential to prevent data corruption. Java provides synchronization mechanisms like synchronized blocks and `volatile` keyword to ensure thread safety.
+## Multithreading Program in Java
+This Java program demonstrates a simple multithreading example where multiple threads are created to perform tasks concurrently. It illustrates basic multithreading concepts such as thread creation, synchronization, and joining threads.
+
+### Example
+Suppose we have a task of printing numbers from 1 to 10,000. We'll create multiple threads, each responsible for printing a portion of these numbers concurrently.
+
+```java
+public class Main {
+ public static void main(String[] args) {
+ // Create multiple threads
+ Thread thread1 = new Thread(new Task(1, 2500));
+ Thread thread2 = new Thread(new Task(2501, 5000));
+ Thread thread3 = new Thread(new Task(5001, 7500));
+ Thread thread4 = new Thread(new Task(7501, 10000));
+
+ // Start the threads
+ thread1.start();
+ thread2.start();
+ thread3.start();
+ thread4.start();
+
+ // Wait for all threads to finish
+ try {
+ thread1.join();
+ thread2.join();
+ thread3.join();
+ thread4.join();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+}
+```
+The Task class represents the task to print numbers within a specified range.
+
+```java
+public class Task implements Runnable {
+ private int start;
+ private int end;
+
+ public Task(int start, int end) {
+ this.start = start;
+ this.end = end;
+ }
+
+ @Override
+ public void run() {
+ for (int i = start; i <= end; i++) {
+ System.out.println(Thread.currentThread().getName() + ": " + i);
+ }
+ }
+}
+```
From fad4d047c5c0c535b806bbe5ce030099d6c877c7 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 18 Apr 2024 16:58:06 +0530
Subject: [PATCH 227/236] Update section28.README.md
---
section28.README.md | 86 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 86 insertions(+)
diff --git a/section28.README.md b/section28.README.md
index 1fd7618..83e3c63 100644
--- a/section28.README.md
+++ b/section28.README.md
@@ -201,4 +201,90 @@ public class Task implements Runnable {
}
}
```
+## Thread Methods in Java
+### `getId()`
+
+- **Description:** Returns the identifier of this Thread. The thread ID is a unique long value assigned to each new thread when it is created.
+- **Syntax:** `public long getId()`
+- **Return Type:** `long`
+- **Example:**
+ ```java
+ Thread thread = new Thread();
+ long id = thread.getId();
+ System.out.println("Thread ID: " + id);
+ ```
+### getName()
+- **Description :** Returns the name of this Thread.
+- **Syntax :** public String getName()
+- **Return Type :** String
+### Example:
+```java
+Thread thread = new Thread();
+String name = thread.getName();
+System.out.println("Thread Name: " + name);
+```
+### setName()
+- **Description :** Sets the name of this Thread.
+- **Syntax :** public final void setName(String name)
+### Parameters:
+- **name :** The new name for this Thread.
+### Example:
+```java
+Thread thread = new Thread();
+thread.setName("MyThread");
+currentThread();
+```
+- **Description :** Returns a reference to the currently executing Thread object.
+- **Syntax :** public static native Thread currentThread()
+- **Return Type :** Thread
+### Example:
+```java
+Thread currentThread = Thread.currentThread();
+System.out.println("Current Thread: " + currentThread.getName());
+```
+### sleep()
+- **Description :** Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
+- **Syntax :** public static void sleep(long millis) throws InterruptedException
+### Parameters:
+- **millis :** The length of time to sleep in milliseconds.
+- **Throws :** InterruptedException - if any thread has interrupted the current thread.
+### Example:
+```java
+try {
+ Thread.sleep(1000); // Sleep for 1 second
+} catch (InterruptedException e) {
+ e.printStackTrace();
+}
+```
+
+### join()
+- **Description :** Waits for this thread to die.
+- **Syntax :** public final void join() throws InterruptedException
+- **Throws :** InterruptedException - if any thread has interrupted the current thread.
+### Example:
+```java
+Thread thread = new Thread();
+thread.start();
+thread.join(); // Wait for the thread to finish execution
+```
+### setPriority()
+- **Description :** Sets the priority of this thread.
+- **Syntax :** public final void setPriority(int newPriority)
+### Parameters:
+- **newPriority :** The new priority for this thread. The value should be in the range 1-10.
+### Example:
+```java
+Thread thread = new Thread();
+thread.setPriority(Thread.MAX_PRIORITY); // Set priority to maximum
+```
+### getPriority()
+- **Description :** Returns the priority of this thread.
+- **Syntax :** public final int getPriority()
+- **Return Type :** int
+### Example:
+```java
+Thread thread = new Thread();
+int priority = thread.getPriority();
+System.out.println("Thread Priority: " + priority);
+```
From 9c4cf9dd3f66f6ffe2bec8d53780ef68dc4ad933 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 18 Apr 2024 17:46:01 +0530
Subject: [PATCH 228/236] Update section28.README.md
---
section28.README.md | 95 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 95 insertions(+)
diff --git a/section28.README.md b/section28.README.md
index 83e3c63..81945db 100644
--- a/section28.README.md
+++ b/section28.README.md
@@ -287,4 +287,99 @@ Thread thread = new Thread();
int priority = thread.getPriority();
System.out.println("Thread Priority: " + priority);
```
+### wait()
+- **Description :** Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
+- **Syntax :** public final void wait() throws InterruptedException
+- **Throws :** InterruptedException - if any thread interrupted the current thread before or while the current thread was waiting for a notification.
+#### Example:
+```java
+synchronized (sharedObject) {
+ sharedObject.wait(); // Wait for notification
+}
+```
+### notify()
+- **Description :** Wakes up a single thread that is waiting on this object's monitor.
+- **Syntax :** public final void notify()
+#### Example:
+```java
+synchronized (sharedObject) {
+ sharedObject.notify(); // Notify a single waiting thread
+}
+```
+### notifyAll()
+- **Description :** Wakes up all threads that are waiting on this object's monitor.
+- **Syntax :** public final void notifyAll()
+#### Example:
+```java
+synchronized (sharedObject) {
+ sharedObject.notifyAll(); // Notify all waiting threads
+}
+```
+
+### Race Condition:
+A race condition occurs in concurrent programming when the outcome of a program depends on the relative timing or interleaving of multiple threads or processes. It happens when two or more threads or processes attempt to modify shared data at the same time. The result of the program becomes unpredictable and may lead to erroneous behavior.
+
+#### Example:
+Consider a scenario where two threads, Thread A and Thread B, increment a shared counter variable:
+
+```java
+// Shared Counter
+int counter = 0;
+
+// Thread A
+Thread threadA = new Thread(() -> {
+ for (int i = 0; i < 1000; i++) {
+ counter++;
+ }
+});
+
+// Thread B
+Thread threadB = new Thread(() -> {
+ for (int i = 0; i < 1000; i++) {
+ counter++;
+ }
+});
+
+// Start both threads
+threadA.start();
+threadB.start();
+
+// Wait for both threads to finish
+threadA.join();
+threadB.join();
+
+// Print the final value of the counter
+System.out.println("Counter: " + counter);
+```
+In this example, the expected final value of the counter should be 2000 (1000 increments from Thread A and 1000 increments from Thread B). However, due to the race condition, the actual final value may vary, and the program may produce unexpected results.
+
+### Synchronization Keywords:
+Java provides synchronization mechanisms to prevent race conditions and ensure thread-safe access to shared resources. Two main synchronization keywords are used: synchronized keyword and volatile keyword.
+
+### synchronized Keyword:
+The synchronized keyword is used to create synchronized blocks of code or methods.
+It ensures that only one thread can execute a synchronized block or method at a time, preventing concurrent access to shared resources.
+It can be applied to instance methods, static methods, and blocks of code.
+### Example of synchronized method:
+```java
+public synchronized void incrementCounter() {
+ counter++;
+}
+Example of synchronized block:
+java
+Copy code
+synchronized (sharedObject) {
+ // Critical section of code
+}
+```
+### volatile Keyword:
+The volatile keyword is used to indicate that a variable's value will be modified by different threads.
+It ensures that changes to the variable made by one thread are immediately visible to other threads.
+It does not provide atomicity like synchronized, but it ensures visibility of changes across threads.
+#### Example:
+```java
+private volatile int sharedVariable;
+```
+### Conclusion:
+Race conditions can lead to unpredictable behavior in concurrent programs. To avoid race conditions, synchronization mechanisms such as synchronized and volatile are used in Java to ensure thread safety and proper coordination among threads accessing shared resources. Understanding and correctly applying these synchronization keywords are essential for writing reliable and efficient concurrent programs.
From 5c7a132abd55add321b34082a98918cf84987eb0 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 18 Apr 2024 18:14:33 +0530
Subject: [PATCH 229/236] Update section28.README.md
---
section28.README.md | 53 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 53 insertions(+)
diff --git a/section28.README.md b/section28.README.md
index 81945db..cbe2534 100644
--- a/section28.README.md
+++ b/section28.README.md
@@ -383,3 +383,56 @@ private volatile int sharedVariable;
### Conclusion:
Race conditions can lead to unpredictable behavior in concurrent programs. To avoid race conditions, synchronization mechanisms such as synchronized and volatile are used in Java to ensure thread safety and proper coordination among threads accessing shared resources. Understanding and correctly applying these synchronization keywords are essential for writing reliable and efficient concurrent programs.
+## Demo of volatile keyword
+
+```java
+public class VolatileDemo {
+ // Shared variable accessed by multiple threads
+ private volatile boolean flag = false;
+
+ public static void main(String[] args) {
+ VolatileDemo demo = new VolatileDemo();
+
+ // Thread to modify the flag
+ Thread modifierThread = new Thread(() -> {
+ try {
+ Thread.sleep(1000); // Sleep for 1 second to simulate some work
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ demo.setFlag(true);
+ System.out.println("Flag has been set to true");
+ });
+
+ // Thread to read the flag
+ Thread readerThread = new Thread(() -> {
+ while (!demo.isFlag()) {
+ // Spin-wait until flag becomes true
+ }
+ System.out.println("Flag is now true");
+ });
+
+ // Start both threads
+ modifierThread.start();
+ readerThread.start();
+ }
+
+ public boolean isFlag() {
+ return flag;
+ }
+
+ public void setFlag(boolean flag) {
+ this.flag = flag;
+ }
+}
+```
+In this demo:
+
+- We have a `VolatileDemo` class with a private `volatile` boolean variable `flag`.
+- There are two threads: `modifierThread` and `readerThread`.
+- `modifierThread` sets the flag to true after 1 second of sleep.
+- readerThread continuously checks the value of the flag in a loop until it becomes true.
+Without the `volatile` keyword, the `readerThread` might cache the value of the flag and never see it change, leading to an infinite loop. However, with the `volatile` keyword, changes made to the flag by one thread are immediately visible to other threads, ensuring that the `readerThread` sees the updated value and exits the loop when the flag becomes true.
+
+This demonstrates how the volatile keyword ensures visibility of changes across threads without providing atomicity.
+
From 1846b5bfe7bc1dcf9fab924d4eb1227cef2339e3 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 18 Apr 2024 20:12:33 +0530
Subject: [PATCH 230/236] Update section28.README.md
---
section28.README.md | 288 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 288 insertions(+)
diff --git a/section28.README.md b/section28.README.md
index cbe2534..66ed9b1 100644
--- a/section28.README.md
+++ b/section28.README.md
@@ -436,3 +436,291 @@ Without the `volatile` keyword, the `readerThread` might cache the value of the
This demonstrates how the volatile keyword ensures visibility of changes across threads without providing atomicity.
+## Demo of Synchronized methods and blocks
+```java
+public class SynchronizationDemo {
+ private int counter = 0;
+
+ // Synchronized method
+ public synchronized void synchronizedMethod() {
+ for (int i = 0; i < 1000; i++) {
+ counter++;
+ }
+ }
+
+ // Non-synchronized method
+ public void nonSynchronizedMethod() {
+ for (int i = 0; i < 1000; i++) {
+ counter++;
+ }
+ }
+
+ public static void main(String[] args) throws InterruptedException {
+ SynchronizationDemo demo = new SynchronizationDemo();
+
+ // Create multiple threads to call synchronized method
+ Thread thread1 = new Thread(() -> {
+ demo.synchronizedMethod();
+ });
+
+ Thread thread2 = new Thread(() -> {
+ demo.synchronizedMethod();
+ });
+
+ // Create multiple threads to call non-synchronized method
+ Thread thread3 = new Thread(() -> {
+ demo.nonSynchronizedMethod();
+ });
+
+ Thread thread4 = new Thread(() -> {
+ demo.nonSynchronizedMethod();
+ });
+
+ // Start threads
+ thread1.start();
+ thread2.start();
+ thread3.start();
+ thread4.start();
+
+ // Wait for threads to finish
+ thread1.join();
+ thread2.join();
+ thread3.join();
+ thread4.join();
+
+ // Print counter value
+ System.out.println("Counter value with synchronized method: " + demo.counter);
+
+ // Reset counter
+ demo.counter = 0;
+
+ // Create threads to call synchronized block
+ Thread thread5 = new Thread(() -> {
+ synchronized (demo) {
+ for (int i = 0; i < 1000; i++) {
+ demo.counter++;
+ }
+ }
+ });
+
+ Thread thread6 = new Thread(() -> {
+ synchronized (demo) {
+ for (int i = 0; i < 1000; i++) {
+ demo.counter++;
+ }
+ }
+ });
+
+ // Start threads
+ thread5.start();
+ thread6.start();
+
+ // Wait for threads to finish
+ thread5.join();
+ thread6.join();
+
+ // Print counter value
+ System.out.println("Counter value with synchronized block: " + demo.counter);
+ }
+}
+```
+
+In this demo:
+
+- `SynchronizationDemo` class contains a shared counter variable counter.
+- It has two methods: `synchronizedMethod()` and `nonSynchronizedMethod()`.
+- `synchronizedMethod()` is synchronized, while `nonSynchronizedMethod()` is not.
+- We create multiple threads to call these methods simultaneously.
+- In the second part of the demo, we use synchronized blocks to ensure thread safety while accessing the shared variable `counter`.
+- After executing the threads, we print the final value of the counter to observe the difference between synchronized and `non-synchronized` access.
+
+## Dead lock
+
+Deadlock is a situation in concurrent programming where two or more threads are blocked forever, waiting for each other to release resources. It typically occurs in a multi-threaded environment when two or more threads hold resources and wait for other resources held by different threads, causing a cyclic dependency. As a result, none of the threads can proceed further, leading to a deadlock.
+
+Characteristics of Deadlock:
+**Mutual Exclusion :**
+Threads hold exclusive access to resources, and only one thread can use a resource at a time.
+**Hold and Wait :**
+Threads hold resources while waiting for other resources. A thread may hold one resource while waiting for another, leading to potential deadlock.
+**No Preemption :**
+Resources cannot be forcibly taken from a thread. They can only be released voluntarily.
+**Circular Wait :**
+There exists a circular chain of two or more threads, each waiting for a resource held by the next thread in the chain.
+**Example of Deadlock :**
+Consider a scenario with two threads, Thread A and Thread B, and two resources, Resource 1 and Resource 2:
+
+- Thread A holds Resource 1 and requests Resource 2.
+- Thread B holds Resource 2 and requests Resource 1.
+If both threads acquire their first resource and then attempt to acquire the second resource, a deadlock may occur. Thread A is waiting for Resource 2 to be released by Thread B, while Thread B is waiting for Resource 1 to be released by Thread A. Both threads are blocked indefinitely, waiting for each other to release resources.
+
+### Prevention and Handling of Deadlock:
+Deadlock can be prevented or resolved using various techniques:
+
+### Avoidance:
+Design the system in such a way that the conditions necessary for deadlock are not possible.
+ **Detection and Recovery :**
+Implement algorithms to detect deadlock and take corrective actions, such as killing processes or rolling back transactions.
+**Preemption :**
+Allow resources to be preempted from threads when necessary to break potential deadlocks.
+**Resource Ordering :**
+Establish a global order in which resources must be acquired to avoid circular waits.
+**Timeouts :**
+Implement timeouts for resource acquisition to prevent threads from waiting indefinitely.
+### Conclusion :
+Deadlock is a critical issue in multi-threaded programming that can lead to application failure and system instability. Understanding the characteristics of deadlock and adopting appropriate prevention and handling strategies are essential for writing robust and reliable concurrent programs.
+
+## Demo of Dead lock and possible fixes
+```java
+public class DeadlockDemo {
+ // Resources
+ private static final Object resource1 = new Object();
+ private static final Object resource2 = new Object();
+
+ public static void main(String[] args) {
+ // Thread 1
+ Thread thread1 = new Thread(() -> {
+ synchronized (resource1) {
+ System.out.println("Thread 1: Holding resource 1...");
+ try {
+ Thread.sleep(100); // Adding delay to increase the chance of deadlock
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ System.out.println("Thread 1: Waiting for resource 2...");
+ synchronized (resource2) {
+ System.out.println("Thread 1: Holding resource 1 and resource 2...");
+ }
+ }
+ });
+
+ // Thread 2
+ Thread thread2 = new Thread(() -> {
+ synchronized (resource2) {
+ System.out.println("Thread 2: Holding resource 2...");
+ try {
+ Thread.sleep(100); // Adding delay to increase the chance of deadlock
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ System.out.println("Thread 2: Waiting for resource 1...");
+ synchronized (resource1) {
+ System.out.println("Thread 2: Holding resource 1 and resource 2...");
+ }
+ }
+ });
+
+ // Start both threads
+ thread1.start();
+ thread2.start();
+ }
+}
+```
+In this code:
+
+We have two threads, thread1 and thread2, each trying to acquire two resources resource1 and resource2 in a different order.
+Both threads acquire one resource and then wait for the other resource to be released, creating a potential deadlock scenario.
+Now, let's explore some possible fixes for the deadlock:
+
+### Resource Ordering:
+Ensure that threads acquire resources in a consistent global order to prevent circular waits. In this case, we can make both threads acquire resources in the same order:
+```java
+Copy code
+// Thread 1
+synchronized (resource1) {
+ System.out.println("Thread 1: Holding resource 1...");
+ try {
+ Thread.sleep(100); // Adding delay to increase the chance of deadlock
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ System.out.println("Thread 1: Waiting for resource 2...");
+ synchronized (resource2) {
+ System.out.println("Thread 1: Holding resource 1 and resource 2...");
+ }
+}
+
+// Thread 2
+synchronized (resource1) { // Acquire resource1 first
+ System.out.println("Thread 2: Holding resource 1...");
+ try {
+ Thread.sleep(100); // Adding delay to increase the chance of deadlock
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ System.out.println("Thread 2: Waiting for resource 2...");
+ synchronized (resource2) {
+ System.out.println("Thread 2: Holding resource 1 and resource 2...");
+ }
+}
+```
+### Timeouts:
+Implement timeouts for resource acquisition to prevent threads from waiting indefinitely. If a thread cannot acquire a resource within a certain time limit, it can release the acquired resources and retry later.
+### Preemption:
+Allow resources to be preempted from threads when necessary to break potential deadlocks. In Java, this can be achieved by using methods like `Thread.interrupt()` to interrupt waiting threads or using ReentrantLock with `tryLock()` method to attempt non-blocking acquisition of resources.
+Applying one or more of these fixes can help prevent or resolve deadlock situations in multi-threaded applications.
+
+## Introduction to virtual Threads
+Virtual threads, introduced in Java 17 as part of Project Loom, are lightweight threads managed by the Java Virtual Machine (JVM) rather than the operating system. They provide a more efficient and scalable alternative to traditional OS threads, allowing developers to create thousands or even millions of threads without incurring the overhead associated with OS threads.
+
+### Key Features of Virtual Threads:
+### Lightweight:
+Virtual threads are significantly lighter than OS threads, consuming minimal memory and resources. This lightweight nature allows the creation of a large number of threads without the performance overhead associated with traditional threads.
+### Efficient Scheduling:
+Virtual threads are scheduled by the JVM's thread scheduler, which can optimize thread execution based on available CPU resources and thread priorities. This enables more efficient resource utilization and better performance compared to OS thread scheduling.
+### Simplified Programming Model:
+Virtual threads follow the same programming model as traditional threads, making it easy for developers to migrate existing thread-based code to use virtual threads. They support standard thread operations such as starting, joining, and interrupting.
+### Scoped Concurrency:
+Virtual threads support scoped concurrency, where groups of related threads can be managed together. This allows for better organization and control of concurrent tasks within an application.
+### Integration with Existing APIs:
+Virtual threads seamlessly integrate with existing Java APIs, such as CompletableFuture and ExecutorService, allowing developers to leverage the benefits of virtual threads without significant code changes.
+### Use Cases for Virtual Threads:
+### High-Concurrency Applications:
+Virtual threads are ideal for applications requiring high concurrency, such as web servers, network services, and reactive applications. They enable efficient handling of a large number of concurrent tasks without overwhelming system resources.
+### Asynchronous Programming:
+Virtual threads simplify asynchronous programming by allowing developers to write code that appears synchronous while executing asynchronously in the background. This enhances code readability and maintainability.
+### Task Parallelism:
+Virtual threads support task parallelism, where multiple tasks can execute concurrently to improve overall application performance. Developers can parallelize independent tasks without worrying about thread management overhead.
+### Scalable Workloads:
+Applications with dynamic workloads that require scaling up or down based on demand can benefit from virtual threads. The lightweight nature of virtual threads makes it easier to scale resources dynamically to meet changing workload requirements.
+### Conclusion
+Virtual threads represent a significant advancement in Java's concurrency model, offering lightweight, scalable, and efficient threading capabilities. By providing a more efficient alternative to traditional OS threads, virtual threads enable developers to build highly concurrent and responsive applications with improved performance and resource utilization. As Java continues to evolve, virtual threads are expected to play a crucial role in the development of modern, scalable, and resilient Java applications.
+
+To create a virtual thread in Java, you can use the Thread.startVirtualThread() method introduced in Java 17. Here's a conceptual example:
+
+```java
+Copy code
+public class VirtualThreadDemo {
+
+ public static void main(String[] args) {
+ // Creating and starting a virtual thread
+ Thread virtualThread = Thread.startVirtualThread(() -> {
+ System.out.println("Virtual thread is running");
+ });
+
+ // Wait for the virtual thread to complete
+ try {
+ virtualThread.join();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ System.out.println("Main thread exiting");
+ }
+}
+```
+In this example:
+
+We create a virtual thread using the `Thread.startVirtualThread()` method, passing a `Runnable` lambda expression that prints a message indicating that the virtual thread is running.
+We then use `join()` to wait for the virtual thread to complete before printing a message indicating that the main thread is exiting.
+Remember that in order to run this code, you need to have Java 17 or later installed on your system, as virtual threads are a feature introduced in Java 17.
+
+Please note that this is a conceptual demonstration, and you may need to adapt the code based on your specific requirements and the version of Java you are using. Additionally, virtual threads are designed to integrate seamlessly with existing Java concurrency APIs, so you can also explore their usage with classes like CompletableFuture and `ExecutorService`.
+
+
+
+
+
+
+
+
From 751df469f7355a32a4fe486655fa702f93c15ed6 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 18 Apr 2024 20:15:48 +0530
Subject: [PATCH 231/236] Update section28.README.md
---
section28.README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/section28.README.md b/section28.README.md
index 66ed9b1..1f0257a 100644
--- a/section28.README.md
+++ b/section28.README.md
@@ -715,7 +715,7 @@ We create a virtual thread using the `Thread.startVirtualThread()` method, passi
We then use `join()` to wait for the virtual thread to complete before printing a message indicating that the main thread is exiting.
Remember that in order to run this code, you need to have Java 17 or later installed on your system, as virtual threads are a feature introduced in Java 17.
-Please note that this is a conceptual demonstration, and you may need to adapt the code based on your specific requirements and the version of Java you are using. Additionally, virtual threads are designed to integrate seamlessly with existing Java concurrency APIs, so you can also explore their usage with classes like CompletableFuture and `ExecutorService`.
+Please note that this is a conceptual demonstration, and you may need to adapt the code based on your specific requirements and the version of Java you are using. Additionally, virtual threads are designed to integrate seamlessly with existing Java concurrency APIs, so you can also explore their usage with classes like `CompletableFuture` and `ExecutorService`.
From e5a99f3ec117701b9f74baf69ead4241fc6e8ba1 Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 18 Apr 2024 22:09:56 +0530
Subject: [PATCH 232/236] Create section29.README.md
---
section29.README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 section29.README.md
diff --git a/section29.README.md b/section29.README.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/section29.README.md
@@ -0,0 +1 @@
+
From e1844e25e8dc8abfacea57fdd70df33735e73fef Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Thu, 18 Apr 2024 22:24:55 +0530
Subject: [PATCH 233/236] Update section29.README.md
---
section29.README.md | 181 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 181 insertions(+)
diff --git a/section29.README.md b/section29.README.md
index 8b13789..dbc20d7 100644
--- a/section29.README.md
+++ b/section29.README.md
@@ -1 +1,182 @@
+# New Features of java 22
+## Multi-file source code programs
+A "multiple source code program" in Java typically refers to a Java program that consists of multiple source code files. In Java, a program can be divided into multiple source files, each containing a class or a group of related classes. These source files are then compiled separately and combined into a single executable or library.
+Here's a brief explanation of how a multiple source code program works in Java:
+
+- **Organizing Code :** In larger Java projects, it's common to organize code into multiple files for better maintainability and readability. Each file typically contains one or more related classes.
+- **Compilation :** Each source code file (.java file) is compiled into a corresponding bytecode file (.class file) using the Java compiler (javac). For example, if you have Main.java, Class1.java, and Class2.java, each will be compiled into Main.class, Class1.class, and Class2.class, respectively.
+- **Dependencies :** If one class depends on another, you import it using the import statement at the beginning of your source file. This allows you to use classes and interfaces defined in other source files.
+- **Execution :** When you run the program, you typically specify the main class that contains the `main()` method. Java runtime (java) loads the necessary classes and executes the program.
+
+## Unnamed variables and patterns
+
+Unnamed variables are variables that can be initialized but not used. Unnamed patterns can appear in a pattern list of a record pattern, and always match the corresponding record component. You can use them instead of a type pattern. They remove the burden of having to write a type and name of a pattern variable that's not needed in subsequent code. You denote both with the underscore character (_).
+
+For background information about unnamed variables and patterns, see JEP 456.
+
+### Unnamed Variables
+
+You can use the underscore keyword `(_)` as the name of a local variable, exception, or lambda parameter in a declaration when the value of the declaration isn't needed. This is called an unnamed variable, which represents a variable thatβs being declared but it has no usable name.
+
+Unnamed variables are useful when the side effect of a statement is more important than its result.
+
+#### Example
+
+```java
+package com.eazybytes.java22;
+
+import java.io.BufferedReader;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class UnnamedVariables {
+
+ public static void main(String[] args) {
+ // Scenario 1
+ List wordList = Arrays.asList("apple", "banana", "orange", "grape", "kiwi");
+ int totalWords = countWords(wordList);
+ System.out.println(totalWords);
+
+ // Scenario 2
+ List fruits = Arrays.asList("apple", "banana", "orange");
+ Map fruitMap = fruits.stream()
+ .collect(Collectors.toMap(f -> f, _ -> "Fruit"));
+ System.out.println(fruitMap);
+
+ // Scenario 3
+ boolean isValid = convertAndDisplay("45");
+
+ // Scenario 4
+ executeIfFilePresent();
+
+ // Scenario 5
+ Point point = new Point(7, 3);
+ if (point instanceof Point(int x, _)) {
+ // Only use the 'x' property from the Point record
+ System.out.printf("Point object with value of x: %d%n", x);
+ }
+ }
+
+ public static int countWords(Iterable words) {
+ int totalWords = 0;
+ for (String _ : words) {
+ totalWords++;
+ }
+ return totalWords;
+ }
+
+ public static boolean convertAndDisplay(String input) {
+ boolean isValid;
+ try{
+ int _ = Integer.parseInt(input);
+ isValid = true;
+ }catch (NumberFormatException _) {
+ System.out.println("NumberFormatException due to invalid input: " + input);
+ isValid = false;
+ }catch (Exception _) {
+ System.out.println("Exception due to invalid input: " + input);
+ isValid = false;
+ }
+ return isValid;
+ }
+
+ public static void executeIfFilePresent() {
+ String filePath = "example.txt";
+ try(BufferedReader _ = new BufferedReader(new FileReader(filePath));){
+ System.out.println("Executing some logic");
+ } catch (FileNotFoundException _) {
+ System.out.println("FileNotFoundException");
+ } catch (IOException _) {
+ System.out.println("IOException");
+ }
+ }
+
+}
+
+record Point(int x, int y) { }
+
+```
+```java
+package com.eazybytes.java22;
+
+public class UnnamedPatterns {
+
+ public static void main(String[] args) {
+ Vehicle vehicle = new Truck("Toyota");
+
+ switch (vehicle) {
+ case Car _ -> processCar(vehicle);
+ case Bike _ -> processBike(vehicle);
+ case Truck _ -> processTruck(vehicle);
+ }
+ }
+
+ public static void processCar(Vehicle vehicle) {
+ if(vehicle instanceof Car car) {
+ System.out.println("Processing car model: " + car.getModel());
+ }
+ }
+
+ public static void processBike(Vehicle vehicle) {
+ if(vehicle instanceof Bike bike) {
+ System.out.println("Processing bike brand: " + bike.getBrand());
+ }
+ }
+
+ public static void processTruck(Vehicle vehicle) {
+ if(vehicle instanceof Truck truck) {
+ System.out.println("Processing truck manufacturer: " + truck.getManufacturer());
+ }
+ }
+
+}
+```
+```java
+package com.eazybytes.java22;
+
+public sealed interface Vehicle permits Car, Bike, Truck {
+
+}
+
+final class Bike implements Vehicle {
+ private final String brand;
+
+ public Bike(String brand) {
+ this.brand = brand;
+ }
+
+ public String getBrand() {
+ return brand;
+ }
+}
+
+final class Car implements Vehicle {
+ private final String model;
+
+ public Car(String model) {
+ this.model = model;
+ }
+
+ public String getModel() {
+ return model;
+ }
+}
+
+final class Truck implements Vehicle {
+ private final String manufacturer;
+
+ public Truck(String manufacturer) {
+ this.manufacturer = manufacturer;
+ }
+
+ public String getManufacturer() {
+ return manufacturer;
+ }
+}
+```
From c4823f96c44a269b5be7eeedab7a29dc27506c1a Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 May 2025 19:19:59 +0530
Subject: [PATCH 234/236] Update section29.README.md
Java 23, 24 Features up to Parallel Gathers
---
section29.README.md | 270 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 270 insertions(+)
diff --git a/section29.README.md b/section29.README.md
index dbc20d7..9dcc845 100644
--- a/section29.README.md
+++ b/section29.README.md
@@ -180,3 +180,273 @@ final class Truck implements Vehicle {
}
}
```
+# π Java 23 Feature: Markdown Documentation Comments (Preview)
+Java 23 introduces support for Markdown syntax inside Javadoc comments using the @-style JavaDoc tool, making documentation easier to write and more readable.
+
+β
This feature is available as a preview and must be enabled using the --enable-preview compiler option.
+
+β
Key Points
+Markdown syntax can now be used in Javadoc comments (e.g., **bold**, _italic_, lists, code blocks).
+
+This improves readability and integrates well with modern documentation tools.
+
+It allows a better developer experience and enhances API documentation quality.
+## βοΈ Example
+```java
+ /** Markdown in Javadoc
+
+ This method adds two integers.
+
+ Parameters
+ - `a`: First number
+ - `b`: Second number
+
+ Returns
+ The sum of `a` and `b`.
+
+ Example **/
+
+
+int result = add(10, 20);
+public class Calculator {
+ public int add(int a, int b) {
+ return a + b;
+ }
+}
+```
+
+## π How to Compile with Preview Features
+```java
+javac --enable-preview --release 23 Calculator.java
+```
+## π Output in Javadoc
+```java
+javadoc --enable-preview --release 23 Calculator.java
+```
+The output will render your Javadoc with Markdown formatting like:
+
+- Headers (e.g., #, ##)
+
+- Code blocks
+
+- Lists and inline formatting
+
+ ## π Java 24 Features: Stream Gatherers API
+
+Java 24 introduces the **Stream Gatherers API**, expanding the Java Stream capabilities with powerful intermediate operations that allow custom data grouping and transformation.
+
+
+
+## π 1. Introduction to Stream Gatherers API
+
+The **Gatherers API** in Java 24 enhances the Stream pipeline by enabling more expressive and stateful transformations in the middle of a stream.
+Think of it as a customizable version of `map()` or `flatMap()`βbut with more power!
+
+> β
This feature is part of the Java 24 preview and requires `--enable-preview`.
+
+
+
+## π§© 2. Getting to Know the Basic Syntax of `Gatherer` Interface
+
+The `Gatherer` interface allows you to define:
+- `T`: Input element type
+- `A`: Accumulation state type
+- `R`: Result type emitted to the downstream
+
+### π§ͺ Example:
+
+```java
+Gatherer toUpper = Gatherer.ofSequential(
+ () -> Gatherer.Sink.ofConsumer(s -> s.toUpperCase())
+);
+```
+- π This basic Gatherer will convert each string to uppercase.
+
+### π οΈ 3. Using Gatherer.of() to Create an Intermediate Operation
+The `Gatherer.of()` and `Gatherer.ofSequential()` methods are used to define custom intermediate operations. These can act similarly to map() or batch-wise transformation using `flatMap()`.
+
+### π§ͺ Example: Custom Batch Gatherer
+```java
+import java.util.stream.*;
+import java.util.stream.Gatherers;
+import java.util.List;
+
+public class GathererDemo {
+ public static void main(String[] args) {
+ List result = Stream.of("a", "b", "c", "d", "e")
+ .gather(Gatherers.windowFixed(2))
+ .map(window -> String.join("-", window))
+ .toList();
+
+ System.out.println(result); // Output: [a-b, c-d, e]
+ }
+}
+
+```
+### π Output:
+```java
+[a-b, c-d, e]
+```
+### π Explanation:
+- `Gatherers.windowFixed(2)` splits elements into windows of size 2.
+
+- `map()` combines them with a dash `(-)` separator.
+
+- The output shows string batches combined.
+
+### π Notes
+- Gatherers provide fine-grained control over intermediate stream processing.
+
+- Use this feature in preview mode:
+
+```java
+javac --enable-preview --release 24 GathererDemo.java
+java --enable-preview GathererDemo
+```
+
+
+## π§ 1. Gatherers with Mutable State & Initializer
+
+Gatherers allow the use of a **mutable container** (like `StringBuilder`, `List`, or `Map`) to accumulate state across elements.
+
+### π§ͺ Example: Group characters into 3-letter words
+
+```java
+import java.util.stream.*;
+import java.util.stream.Gatherers;
+import java.util.*;
+
+public class GathererStateDemo {
+ public static void main(String[] args) {
+ List result = Stream.of("a", "b", "c", "d", "e", "f", "g")
+ .gather(Gatherer.of(
+ () -> new StringBuilder(), // Initializer (creates mutable state)
+ (sb, s, downstream) -> {
+ sb.append(s);
+ if (sb.length() == 3) {
+ downstream.push(sb.toString()); // Send result downstream
+ sb.setLength(0); // Reset state
+ }
+ },
+ (sb, downstream) -> {
+ if (sb.length() > 0) {
+ downstream.push(sb.toString()); // Finish remaining chars
+ }
+ }
+ ))
+ .toList();
+
+ System.out.println(result); // Output: [abc, def, g]
+ }
+}
+```
+
+### π§Ύ Explanation
+
+| Part | What It Does |
+| --------------------------------- | ------------------------------------------ |
+| `() -> new StringBuilder()` | **Initializer**: Sets up the mutable state |
+| Accumulator `(sb, s, downstream)` | Adds characters and pushes when ready |
+| Finisher `(sb, downstream)` | Pushes any leftover data at the end |
+
+## π― 2. Finisher in a Stream Gatherer
+The finisher is optional but crucial when the remaining state may contain useful data at the end of the stream. It ensures that no data is lost during stream processing.
+
+ π Without a finisher, any "incomplete" batches (like a group of 1 or 2 characters in a 3-char gatherer) would be discarded.
+
+### π οΈ Compile and Run
+Make sure to enable preview features when compiling:
+```java
+javac --enable-preview --release 24 GathererStateDemo.java
+java --enable-preview GathererStateDemo
+```
+### π Summary
+| Concept | Description |
+| ----------- | ----------------------------------------------- |
+| Initializer | Prepares mutable state (e.g., a buffer or list) |
+| Accumulator | Handles element-by-element logic |
+| Finisher | Final cleanup or output of remaining state |
+
+#### π‘ Use Cases:
+
+- Batching data
+- Grouping elements
+- Stateful filtering
+- Windowed aggregations
+
+
+## π 1. Parallel Gatherers
+
+Parallel Gatherers enable **stateful intermediate operations** to be executed in parallel without violating the ordering and correctness of the stream.
+
+### π Key Concepts
+
+- **Thread-safety**: Each parallel task uses its own mutable state.
+- **Split behavior**: The `Gatherer` is designed to operate correctly when the stream is split across threads.
+- **Finisher**: Ensures that residual state from each parallel thread is passed downstream.
+
+> β οΈ Parallel gatherers must **not** share mutable state unless it is properly synchronized.
+
+## π¬ When to Use
+
+- Large-scale stream processing
+- Custom parallel batching or windowing
+- Parallel grouping of elements (e.g., words, logs, events)
+
+### π§ Example Code
+
+```java
+import java.util.stream.*;
+import java.util.stream.Gatherers;
+import java.util.*;
+
+public class ParallelGathererDemo {
+ public static void main(String[] args) {
+ List result = Stream.of("a", "b", "c", "d", "e", "f")
+ .parallel() // Run the stream in parallel
+ .gather(Gatherer.of(
+ () -> new ArrayList(), // initializer
+ (list, item, downstream) -> {
+ list.add(item);
+ if (list.size() == 2) {
+ downstream.push(String.join("-", list));
+ list.clear();
+ }
+ },
+ (list, downstream) -> {
+ if (!list.isEmpty()) {
+ downstream.push(String.join("-", list));
+ }
+ }
+ ))
+ .toList();
+
+ System.out.println(result);
+ }
+}
+```
+- π‘ Note: The order may vary due to parallel processing!
+
+### π§Ύ Explanation
+
+| Component | Purpose |
+| ------------------ | ----------------------------------------------------- |
+| `parallel()` | Enables parallel stream processing |
+| `Gatherer.of(...)` | Defines how to group in batches |
+| `Finisher` | Handles any leftover elements in each parallel thread |
+
+### βοΈ Compile and Run
+```java
+javac --enable-preview --release 24 ParallelGathererDemo.java
+java --enable-preview ParallelGathererDemo
+```
+- β
Ensure your system has multiple cores to take advantage of parallelism.
+
+### π Summary
+| Concept | Description |
+| -------------------- | --------------------------------------------- |
+| Parallel Gatherers | Allows gatherers to work on parallel streams |
+| Independent State | Each task maintains its own buffer/state |
+| Final Finisher Phase | Combines leftover results per parallel thread |
+
+π₯ Java 24 is pushing boundaries in Stream API performance and flexibility. Parallel Gatherers are especially useful when working with large data pipelines!
From a668a1243b9c7ad55da3bef6f362ea0db137428f Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 May 2025 19:49:16 +0530
Subject: [PATCH 235/236] Update section29.README.md
End of section29
---
section29.README.md | 100 +++++++++++++++++++++++++++++++++++++++++---
1 file changed, 94 insertions(+), 6 deletions(-)
diff --git a/section29.README.md b/section29.README.md
index 9dcc845..4949157 100644
--- a/section29.README.md
+++ b/section29.README.md
@@ -237,7 +237,7 @@ Java 24 introduces the **Stream Gatherers API**, expanding the Java Stream capab
-## π 1. Introduction to Stream Gatherers API
+## π Introduction to Stream Gatherers API
The **Gatherers API** in Java 24 enhances the Stream pipeline by enabling more expressive and stateful transformations in the middle of a stream.
Think of it as a customizable version of `map()` or `flatMap()`βbut with more power!
@@ -246,7 +246,7 @@ Think of it as a customizable version of `map()` or `flatMap()`βbut with more
-## π§© 2. Getting to Know the Basic Syntax of `Gatherer` Interface
+## π§© Getting to Know the Basic Syntax of `Gatherer` Interface
The `Gatherer` interface allows you to define:
- `T`: Input element type
@@ -262,7 +262,7 @@ Gatherer toUpper = Gatherer.ofSequential(
```
- π This basic Gatherer will convert each string to uppercase.
-### π οΈ 3. Using Gatherer.of() to Create an Intermediate Operation
+### π οΈ Using Gatherer.of() to Create an Intermediate Operation
The `Gatherer.of()` and `Gatherer.ofSequential()` methods are used to define custom intermediate operations. These can act similarly to map() or batch-wise transformation using `flatMap()`.
### π§ͺ Example: Custom Batch Gatherer
@@ -305,7 +305,7 @@ java --enable-preview GathererDemo
```
-## π§ 1. Gatherers with Mutable State & Initializer
+## π§ Gatherers with Mutable State & Initializer
Gatherers allow the use of a **mutable container** (like `StringBuilder`, `List`, or `Map`) to accumulate state across elements.
@@ -349,7 +349,7 @@ public class GathererStateDemo {
| Accumulator `(sb, s, downstream)` | Adds characters and pushes when ready |
| Finisher `(sb, downstream)` | Pushes any leftover data at the end |
-## π― 2. Finisher in a Stream Gatherer
+## π― Finisher in a Stream Gatherer
The finisher is optional but crucial when the remaining state may contain useful data at the end of the stream. It ensures that no data is lost during stream processing.
π Without a finisher, any "incomplete" batches (like a group of 1 or 2 characters in a 3-char gatherer) would be discarded.
@@ -375,7 +375,7 @@ java --enable-preview GathererStateDemo
- Windowed aggregations
-## π 1. Parallel Gatherers
+## π Parallel Gatherers
Parallel Gatherers enable **stateful intermediate operations** to be executed in parallel without violating the ordering and correctness of the stream.
@@ -450,3 +450,91 @@ java --enable-preview ParallelGathererDemo
| Final Finisher Phase | Combines leftover results per parallel thread |
π₯ Java 24 is pushing boundaries in Stream API performance and flexibility. Parallel Gatherers are especially useful when working with large data pipelines!
+
+
+## β‘ Interrupting & Chaining Gatherers
+
+You can **interrupt** a Gatherer chain using custom logic (e.g., break on a condition), and you can also **chain multiple Gatherers** together to build layered processing flows.
+
+### π§ Example: Interrupt stream when an element equals "STOP"
+
+```java
+import java.util.stream.*;
+import java.util.stream.Gatherers;
+import java.util.*;
+
+public class InterruptAndChainDemo {
+ public static void main(String[] args) {
+ List result = Stream.of("one", "two", "STOP", "three")
+ .gather(Gatherers.filtering(s -> !s.equals("STOP")))
+ .gather(Gatherers.mapping(String::toUpperCase))
+ .toList();
+
+ System.out.println(result); // Output: [ONE, TWO, THREE]
+ }
+}
+```
+- π‘ Use filtering and mapping to chain logic like a pipeline.
+
+### π `fold()`, `scan()`, `mapConcurrent()` Methods
+πΉ `fold(identity, accumulator)`
+Accumulates all items like reduce, but emits only the final result.
+
+πΉ `scan(identity, accumulator)`
+Like fold, but emits the intermediate result after every element.
+
+πΉ `mapConcurrent(fn)`
+Maps elements in parallel, useful for heavy transformation tasks.
+
+### π§ͺ Example: Using scan() to track running total
+```java
+import java.util.stream.*;
+import java.util.stream.Gatherers;
+import java.util.*;
+
+public class ScanDemo {
+ public static void main(String[] args) {
+ List result = Stream.of(1, 2, 3, 4)
+ .gather(Gatherers.scan(0, Integer::sum))
+ .toList();
+
+ System.out.println(result); // Output: [1, 3, 6, 10]
+ }
+}
+```
+### πͺ `windowFixed()` and `windowSliding()`
+These gatherers help group elements into fixed-size or sliding windows, just like in time-series processing or real-time analytics.
+
+### π¦ `windowFixed(size)` β Non-overlapping chunks
+```java
+Stream.of("A", "B", "C", "D", "E")
+ .gather(Gatherers.windowFixed(2))
+ .toList();
+// Output: [[A, B], [C, D], [E]]
+```
+### π windowSliding(size, step) β Overlapping windows
+```java
+Stream.of(1, 2, 3, 4, 5)
+ .gather(Gatherers.windowSliding(3, 1))
+ .toList();
+// Output: [[1,2,3], [2,3,4], [3,4,5]]
+```
+
+### βοΈ Compile and Run
+```java
+javac --enable-preview --release 24 *.java
+java --enable-preview InterruptAndChainDemo
+java --enable-preview ScanDemo
+```
+### π Summary
+
+| Feature | Description |
+| ---------------------- | --------------------------------- |
+| `filtering`, `mapping` | Interrupting & chaining gatherers |
+| `fold()` | Single result after reduction |
+| `scan()` | Running total or accumulation |
+| `mapConcurrent()` | High-performance parallel mapping |
+| `windowFixed()` | Non-overlapping groupings |
+| `windowSliding()` | Overlapping groupings |
+
+
From b332bd722ce2453c5c6275f1855ac5b41b9eb83b Mon Sep 17 00:00:00 2001
From: GODA PRABHAKARA RAO <128283295+PrabhaKar-Rao@users.noreply.github.com>
Date: Tue, 20 May 2025 19:54:29 +0530
Subject: [PATCH 236/236] Update section29.README.md
---
section29.README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/section29.README.md b/section29.README.md
index 4949157..79c62ed 100644
--- a/section29.README.md
+++ b/section29.README.md
@@ -537,4 +537,6 @@ java --enable-preview ScanDemo
| `windowFixed()` | Non-overlapping groupings |
| `windowSliding()` | Overlapping groupings |
+### π Congratulations on Completing the Journey!
+### π Thank You for Being a Part of This Java Evolution