├── 00_Introduction
└── introduction.md
├── 01_Hello_world
└── hello_world.md
├── 02_Variables
└── variables.md
├── 03_Operators
└── operators.md
├── 04_Control_structures
└── control_structures.md
├── 05_Loops
└── loops.md
├── 06_Arrays
├── 2D_Arrays
└── arrays.md
├── 07_Lists
└── lists.md
├── 08_Strings
├── PalindromeChecker.java
└── strings.md
├── 09_Functions
└── functions.md
├── 10_Inheritance
└── inheritance.md
├── 11_Polymorphism
└── polymorphism.md
├── 12_Exceptions
└── exceptions.md
├── 13_File_io
└── file_io.md
├── 14_GUI_programming
├── gui_prime_for_beginners
└── gui_programming.md
├── 15_Frameworks
└── frameworks.md
├── 16_FirstContribution
├── Algorithms
│ └── FloydWarshall.java
├── BuzzNumberChecker.java
├── Calculator.java
├── Data Structures
│ ├── CustomBinaryTree.java
│ ├── CustomCircularQueue.java
│ ├── CustomDeque.java
│ ├── CustomLinearQueue.java
│ ├── CustomLinkedList.java
│ ├── CustomMap.java
│ ├── CustomSet.java
│ └── CustomStack.java
├── Dijkstra's algorithm
│ ├── Dijkstra.java
│ ├── DijkstraTest.java
│ └── Explanation.md
├── FibonacciSequenceGenerator.java
├── FizzBuzz.java
├── GUI Programs
│ ├── DigitalClock.java
│ ├── SwingCalculator.java
│ └── TemperatureConverter.java
├── Games
│ └── SnakeLadder
│ │ ├── Game.java
│ │ ├── Ladder.java
│ │ ├── Player.java
│ │ └── Snake.java
├── HelloWorld.java
├── NeonNumbers.java
├── NumberToWordsConverter.java
├── Numbers
│ ├── ArmstrongNumber.java
│ ├── AutomorphicNumber.java
│ ├── HappyNumber.java
│ ├── KaprekarNumber.java
│ ├── KrishnamurthyNumber.java
│ ├── PalindromeNumber.java
│ ├── PerfectNumber.java
│ ├── PrimeNumber.java
│ ├── PronicNumber.java
│ ├── TriangularNumber
│ └── UniqueNumber.java
├── PasswordGenerator.java
├── Patterns
│ └── ButterflyPattern.java
├── PlaySnakeNLadder.java
├── SORTING
│ ├── BubbleSort.java
│ ├── InsertionSort
│ ├── MergeSort.java
│ └── SelectionSort.java
├── StonePaperScissors
├── TowerOfHanoi.java
├── WashingMachine.java
└── minMax.java
├── 17_Stream_API
└── stream_api.md
├── 18_Multithreading
└── multithreading.md
├── CONTRIBUTING.md
├── Insertionsort.java
├── LICENSE
└── README.md
/00_Introduction/introduction.md:
--------------------------------------------------------------------------------
1 | [Previous](../README.md) LearnJava
2 |
3 | [Next](../01_Hello_world/hello_world.md) Hello-World
4 |
5 |
6 | * [Introduction](./introduction.md#introduction)
7 | * [Requirements](./introduction.md#requirement)
8 | * [Setup](./introduction.md#setup)
9 | * [Coding Style (Betty)](./introduction.md#coding-style-betty)
10 | * [Keywords](./introduction.md#keywords)
11 |
12 |
13 |
14 | # Introduction
15 |
16 | Java is a class-based, object-oriented programming language and is designed to have as few implementation dependencies as possible. A general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is similar to c/c++
17 |
18 | ## Requirement
19 |
20 | You should aware of control flow statements like , if else, for loop, while loop ,do while loop ,operators
21 | This is the bare minimum requirement to start with any programming language.
22 |
23 | You could also use an IDE, which most times come with a text editor and compiler.
24 |
25 | Other Requirement-
26 |
27 |
28 | 1)Install Java 8 above version
29 |
30 |
31 | 2)Eclipse IDE(any other Java code editor)
32 |
33 | ## Setup
34 |
35 | Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture. The latest version is Java 19.
36 |
37 | Few things must be clear before setting up the environment
38 |
39 | 1)JDK(Java Development Kit): JDK is intended for software developers and includes development tools such as the Java compiler, Javadoc, Jar, and a debugger.
40 |
41 | 2)JRE(Java Runtime Environment): JRE contains the parts of the Java libraries required to run Java programs and is intended for end-users. JRE can be viewed as a subset of JDK.
42 |
43 | 3)JVM: JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides a runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms.
44 |
45 | Steps for setting the environment in Windows operating system are as follows:
46 |
47 | 1)Step 1: Java8 JDK is available at Download Java 8. Click the second last link for Windows(32 bit) and the last link for Windows(64 bit) as highlighted below.
48 |
49 | 2)Step 2: After download, run the .exe file and follow the instructions to install Java on your machine. Once you install Java on your machine, you have to set up the environment variable.
50 |
51 | Step 3: Go to Control Panel -> System and Security -> System. Under the Advanced System Setting option click on Environment Variables as highlighted below.
52 |
53 | Step 4: Now, you have to alter the “Path” variable under System variables so that it also contains the path to the Java environment. Select the “Path” variable and click on the Edit button as highlighted below.
54 |
55 | Step 5: You will see a list of different paths, click on the New button, and then add the path where java is installed. By default, java is installed in “C:\Program Files\Java\jdk\bin” folder OR “C:\Program Files(x86)\Java\jdk\bin”. In case, you have installed java at any other location, then add that path.
56 |
57 | Step 6: Click on OK, Save the settings, and you are done !! Now to check whether the installation is done correctly, open the command prompt and type javac -version. You will see that java is running on your machine.
58 |
59 | Note: To make sure whether the compiler is set up, type javac in the command prompt. You will see a list related to javac.
60 |
61 |
62 | ## Coding Style (Betty)
63 | In this tutorial, we are going to be using the Betty Coding Style. To read more about the rules of this style, checkout [Betty Repository](https://github.com/holbertonschool/Betty/wiki).
64 |
65 | And also a Video on how to install Betty in your Linux Based Computer [here](https://youtu.be/wDDKOOEPED0).
66 | ## KeyWords
67 |
68 |
69 | Java keywords are also known as reserved words. Keywords are particular words that act as a key to a code. These are predefined words by Java so they cannot be used as a variable or object name or class name.
70 |
71 | Keywords in Java are as follows
72 |
73 | |KeyWords | | | |
74 | |:-------:|:-------:|:-------:|:-------:|
75 | | abstract|boolean |break| byte|
76 | |case| catch |char |class|
77 | | continue | default| do| double|
78 | |float| for| goto| if|
79 | |else |enum |extends| final|
80 | |finally| float |for |if|
81 | |implements |import |instanceof |int|
82 | |interface |long| native| new|
83 | | null|package |private| protected|
84 | |public| return |short |static|
85 | | stripfp | super| switch| synchronized|
86 | |this| throw| throws| transient|
87 | |try |void |volatile|while|
88 |
89 | Enough of the introduction
90 |
91 |
92 |
93 |
94 |
95 |
96 | In the Next Section, we are going to write some crazy codes.
97 |
98 | [Previous](../README.md) LearnJava
99 |
100 | [Next](../01_Hello_world/hello_world.md) Hello-World
101 |
102 |
103 |
--------------------------------------------------------------------------------
/01_Hello_world/hello_world.md:
--------------------------------------------------------------------------------
1 | [Previous](../00_introduction/introduction.md) Introduction
2 |
3 | [Next](../02_Variables/variables.md) Variables
4 |
5 | * [Hello World](./hello_world.md#hello-world)
6 | * [Comments](./hello_world.md#comments)
7 |
8 | # Hello World
9 |
10 | The process of Java programming can be simplified in three steps:
11 |
12 | 1)Create the program by typing it into a text editor and saving it to a file – HelloWorld.java.
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | 2)Compile it by typing “javac HelloWorld.java” in the terminal window.
22 |
23 |
24 |
25 |
26 |
27 |
28 | 3)Execute (or run) it by typing “java HelloWorld” in the terminal window.
29 |
30 |
31 | Now, we are going to break down the Java syntax
32 |
33 | Look at the following code:
34 |
35 | ```C
36 | // This is a simple Java program.
37 | // FileName : "HelloWorld.java".
38 |
39 | class HelloWorld
40 | {
41 | // Your program begins with a call to main().
42 | // Prints "Hello, World" to the terminal window.
43 | public static void main(String args[])
44 | {
45 | System.out.println("Hello, World");
46 | }
47 | }
48 |
49 | ```
50 | ### Syntax Explained:
51 |
52 | ```
53 | Note: you don't have to understand everything now, it'll all come to you.
54 | ```
55 |
56 | Line 1: 1. Class definition
57 | This line uses the keyword class to declare that a new class is being defined.
58 | ```c
59 | class HelloWorld {
60 | //
61 | //Statements
62 | }
63 | ```
64 |
65 |
66 | Line 2: ``Hello world``
67 | It is an identifier that is the name of the class. The entire class definition, including all of its members, will be between the opening curly brace “{” and the closing curly brace “}“.
68 |
69 | Line 3: main method:
70 | In the Java programming language, every application must contain a main method. The main function(method) is the entry point of your Java application, and it’s mandatory in a Java program. whose signature in Java is:
71 | ```c
72 | public static void main(String[] args)
73 | ```
74 |
75 | 1) public: So that JVM can execute the method from anywhere.
76 |
77 |
78 |
79 |
80 | 2) static: The main method is to be called without an object. The modifiers public and static can be written in either order.
81 |
82 |
83 |
84 | 3) void: The main method doesn’t return anything.
85 |
86 |
87 |
88 |
89 | 4) main(): Name configured in the JVM. The main method must be inside the class definition. The compiler executes the codes starting always from the main function.
90 |
91 |
92 |
93 |
94 | 5) String[]: The main method accepts a single argument, i.e., an array of elements of type String.
95 | Line 4:
96 | Like in C/C++, the main method is the entry point for your application and will subsequently invoke all the other methods required by your program.
97 |
98 | The next line of code is shown here. Notice that it occurs inside the main() method.
99 | ```
100 | System.out.println("Hello, World");
101 | ```
102 | This line outputs the string “Hello, World” followed by a new line on the screen.
103 |
104 | Output is accomplished by the built-in println( ) method.
105 |
106 | The System is a predefined class that provides access to the system, and out is the variable of type output stream connected to the console.
107 |
108 | ## Comments
109 | In a program, comments are like indents one makes, they are used so that it is easier for someone who isn’t familiar with the language to be able to understand the code. It will also make the job easier for you, as a coder, to find errors in the code since you will be easily able to find the location of the bug. Comments are ignored by the compiler while compiling a code, which makes the job more complex in the long run when they have to go through so much code to find one line.
110 |
111 |
112 |
113 | ### Types of Comments in Java
114 |
115 | 1. Single-line comments.
116 | 2. Multi-line comments.
117 | 3. Documentation comments.
118 |
119 | A. Single-line comments
120 | A beginner-level programmer uses mostly single-line comments for describing the code functionality. It’s the easiest typed comments.
121 |
122 | Syntax:
123 | ```
124 | //Comments here( Text in this line only is considered as comment )
125 | ```
126 | Illustration:
127 |
128 | 
129 |
130 |
131 | Example:
132 |
133 | ```c
134 | // Java program to show single line comments
135 |
136 | class Scomment
137 | {
138 | public static void main(String args[])
139 | {
140 | // Single line comment here
141 | System.out.println("Single line comment above");
142 | }
143 | }
144 | ```
145 | Output:
146 |
147 | ```
148 | Single line comment above
149 | ```
150 |
151 | B. Multi-line Comments:
152 | To describe a full method in a code or a complex snippet single line comments can be tedious to write since we have to give ‘//’ at every line. So to overcome this multi-line comments can be used.
153 |
154 | Syntax:
155 |
156 | ```C
157 | /*Comment starts
158 | continues
159 | continues
160 | .
161 | .
162 | .
163 | Comment ends*/
164 | ```
165 | Example:
166 |
167 | ```C
168 | //Java program to show multi line comments
169 | class Scomment
170 | {
171 | public static void main(String args[])
172 | {
173 | System.out.println("Multi line comments below");
174 | /*Comment line 1
175 | Comment line 2
176 | Comment line 3*/
177 | }
178 | }
179 | ```
180 | Output:
181 | ```
182 | Multi line comments below
183 | ```
184 | We can also accomplish single line comments by using the above syntax as shown below:
185 |
186 | /*Comment line 1*/
187 |
188 | C. Documentation Comments:
189 | This type of comment is used generally when writing code for a project/software package, since it helps to generate a documentation page for reference, which can be used for getting information about methods present, its parameters, etc. For example, http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html is an auto-generated documentation page that is generated by using documentation comments and a javadoc tool for processing the comments.
190 |
191 | Syntax:
192 |
193 | ```C
194 | /**Comment start
195 | *
196 | *tags are used in order to specify a parameter
197 | *or method or heading
198 | *HTML tags can also be used
199 | *such as
200 | *
201 | *comment ends*/
202 |
203 | /*package whatever //do not write package name here */
204 |
205 | import java.io.*;
206 |
207 | class GFG {
208 | public static void main (String[] args) {
209 | /**
210 | comment line 1
211 | comment line 2
212 | */
213 | }
214 | }
215 | ```
216 |
217 |
218 |
219 |
220 |
221 | ## Compile and Run
222 |
223 |
224 | After successfully setting up the environment, we can open a terminal in both Windows/Unix and go to the directory where the file – HelloWorld.java is present.
225 | Now, to compile the HelloWorld program, execute the compiler – javac, to specify the name of the source file on the command line, as shown:
226 |
227 | ```c
228 | javac HelloWorld.java
229 | ```
230 |
231 | The compiler creates a HelloWorld.class (in the current working directory) that contains the bytecode version of the program. Now, to execute our program, JVM(Java Virtual Machine) needs to be called using java, specifying the name of the class file on the command line, as shown:
232 | And that's it.
233 |
234 | ```c
235 | java HelloWorld
236 | ```
237 | This will print ``` “Hello World” ``` to the terminal screen.
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 | [Previous](../00_introduction/introduction.md) Introduction
246 |
247 | [Next](../02_Variables/variables.md) Variables
248 |
--------------------------------------------------------------------------------
/02_Variables/variables.md:
--------------------------------------------------------------------------------
1 |
2 | [Previous](../01_Hello_world/hello_world.md) Hello World
3 |
4 | [Next](../03_Operators/operators.md) Operators
5 | #
6 | * [Variables](./variables.md#variables)
7 | * [Declaring Variables](./variables.md#declaring-variables)
8 | * [Types of Variables](./variables.md#types-of-variables)
9 | * [Difference](./variables.md#difference)
10 |
11 |
12 | # Variables
13 | Variables are containers for storing data values.
14 |
15 | Different variables used in Java are as-:
16 |
17 | 1)```String``` - stores text, such as "Hello".
18 |
19 | String values are surrounded by double quotes
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | 2)```int``` - stores integers (whole numbers), without decimals, such as 123 or -123
28 |
29 |
30 |
31 |
32 |
33 | 3)```float``` - stores floating point numbers, with decimals, such as 19.99 or -19.99
34 |
35 |
36 |
37 |
38 |
39 | 4)```char``` - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
40 |
41 |
42 |
43 |
44 |
45 | 5)```boolean``` - stores values with two states: true or false
46 |
47 |
48 |
49 |
50 |
51 | ## Declaring Variables
52 |
53 | Syntax
54 |
55 | ```type variableName = value;```
56 |
57 | Where type is one of Java's types (such as ```int``` or ```String```)
58 |
59 |
60 | *variableName* is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.
61 |
62 | ***To create a variable that should store text, look at the following example:***
63 |
64 | a variable called name of type String and assign it the value "XYZ":
65 | ```c
66 |
67 | String name = "XYZ";
68 | System.out.println(name);
69 |
70 | ````
71 |
72 | ***To create a variable that should store a number, look at the following example:***
73 |
74 | a variable called myNum of type int and assign it the value 5:
75 |
76 | ```c
77 | int myNum = 5;
78 | System.out.println(myNum);
79 |
80 | ```
81 |
82 | ***Note-that if you assign a new value to an existing variable, it will overwrite the previous value:***
83 |
84 | Change the value of myNum from 5 to 20:
85 |
86 |
87 | ```c
88 | int myNum = 5;
89 | myNum = 20; // myNum is now 20
90 | System.out.println(myNum);
91 | ```
92 | **Final Variables**
93 |
94 | If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will declare the variable as "final" or "constant", which means unchangeable and read-only):
95 |
96 | ```c
97 | final int myNum = 5;
98 | myNum = 20; // will generate an error: cannot assign a value to a final variable
99 | ```
100 | **Other Types**
101 |
102 | ```c
103 | int myNum = 5;
104 | ```
105 |
106 | ```c
107 | float myFloatNum = 5.99f;
108 | ```
109 |
110 | ```c
111 | char myLetter = 'D';
112 | ```
113 |
114 | ```c
115 | boolean myBool = true;
116 | ```
117 |
118 |
119 | ```c
120 | String myText = "Hello";
121 | ```
122 |
123 | ## Types of variables
124 |
125 |
126 | *1)Local variables*
127 |
128 |
129 | *2)Instance variables*
130 |
131 |
132 | *3)Static variables*
133 |
134 |
135 |
136 | **1)Local Variables**
137 |
138 |
139 | i)A variable defined within a block or method or constructor is called a local variable.
140 |
141 | ii)These variables are created when the block is entered, or the function is called and destroyed after exiting from the block or when the call returns from the function.
142 |
143 | iii)The scope of these variables exists only within the block in which the variables are declared, i.e., we can access these variables only within that block.
144 | ```
145 | Initialization of the local variable is mandatory before using it in the defined scope.
146 | ```
147 |
148 | ```c
149 |
150 | class GFG {
151 | public static void main(String[] args)
152 | {
153 | int var = 10; // Declared a Local Variable
154 | // This variable is local to this main method only
155 | System.out.println("Local Variable: " + var);
156 | }
157 | }
158 | ```
159 |
160 | *Output*
161 | ```
162 | Local Variable: 10
163 | ```
164 | **2)Instance Variables**
165 |
166 | i)Instance variables are non-static variables and are declared in a class outside of any method, constructor, or block.
167 |
168 | ii)As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
169 |
170 |
171 | iii)Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier, then the default access specifier will be used.
172 |
173 |
174 | iv)Initialization of an instance variable is not mandatory. Its default value is 0.
175 |
176 |
177 | v)Instance variables can be accessed only by creating objects.
178 |
179 | ```c
180 |
181 | /*package whatever //do not write package name here */
182 |
183 | import java.io.*;
184 |
185 | class GFG {
186 |
187 | public String geek; // Declared Instance Variable
188 |
189 | public GFG()
190 | { // Default Constructor
191 |
192 | this.geek = "XYZ"; // initializing Instance Variable
193 | }
194 | //Main Method
195 | public static void main(String[] args)
196 | {
197 |
198 | // Object Creation
199 | GFG name = new GFG();
200 | // Displaying O/P
201 | System.out.println("Geek name is: " + name.geek);
202 | }
203 | }
204 |
205 | ```
206 |
207 | *Output*
208 |
209 | ```
210 | Geek name is: XYZ
211 | ```
212 |
213 | **3)Static Variables**
214 |
215 | Static variables are also known as ```class variables.```
216 |
217 | i)These variables are declared similarly as instance variables. The difference is that static variables are declared using the static keyword within a class outside of any method, constructor or block.
218 |
219 |
220 |
221 | ii)Unlike instance variables, we can only have one copy of a static variable per class, irrespective of how many objects we create.
222 |
223 | iii)Static variables are created at the start of program execution and destroyed automatically when execution ends.
224 |
225 |
226 | iv)Initialization of a static variable is not mandatory. Its default value is 0.
227 |
228 |
229 | v)If we access a static variable like an instance variable (through an object), the compiler will show a warning message, which won’t halt the program. The compiler will replace the object name with the class name automatically.
230 |
231 |
232 | vi)If we access a static variable without the class name, the compiler will automatically append the class name.
233 |
234 | ```c
235 |
236 | /*package whatever //do not write package name here */
237 |
238 | import java.io.*;
239 |
240 | class GFG {
241 |
242 | public static String geek = "XYZ"; //Declared static variable
243 |
244 | public static void main (String[] args) {
245 |
246 | //geek variable can be accessed without object creation
247 | //Displaying O/P
248 | //GFG.geek --> using the static variable
249 | System.out.println("Geek Name is : "+GFG.geek);
250 | }
251 | }
252 |
253 | ```
254 |
255 |
256 |
257 | *Output*
258 | ```
259 | Geek Name is : XYZ
260 | ```
261 |
262 | ## Difference
263 |
264 | ```
265 | We can access instance variables through object references, and static variables can be accessed directly using the class name.
266 | ```
267 |
268 |
269 |
270 | *Instance Variables*
271 |
272 | * Any variable that is defined in class body and outside bodies of methods; and it should not be declared static, abstract, stricftp, synchronized, and native modifier.
273 | * An instance variable cannot live without its object, and it is a part of the object.
274 | * Every object has their own copies of instance variables.
275 |
276 | *Static Variables (class variables)*
277 |
278 | * Use static modifier
279 |
280 | * Belong to the class (not to an object of the class)
281 |
282 | * One copy of a static variable
283 |
284 | * Initialize only once at the start of the execution.
285 |
286 | * Enjoy the program’s lifetime
287 |
288 | Consider a class MyClass, having one static and one non-static member:
289 |
290 | ```c
291 | public class MyClass {
292 | public static int STATICVARIABLE = 0;
293 | public int nonStaticVariable = 0;
294 | }
295 | ```
296 |
297 | Now, let's create a main() to create a couple of instances:
298 |
299 | ```c
300 | public class AnotherClass{
301 | public static void main(String[] args) {
302 | // Create two instances of MyClass
303 | MyClass obj1 = new MyClass();
304 | MyClass obj2 = new MyClass();
305 | obj1.nonStaticVariable = 30; // Setting value for nonstatic varibale
306 | obj1.STATICVARIABLE = 40; //Setting value for static variable
307 | obj2.nonStaticVariable = 50;
308 | obj2.STATICVARIABLE = 60;
309 |
310 | // Print the values actually set for static and non-static variables.
311 | System.out.println(obj1.STATICVARIABLE);
312 | System.out.println(obj1.nonStaticVariable);
313 | System.out.println(obj2.STATICVARIABLE);
314 | System.out.println(obj2.nonStaticVariable);
315 | }
316 | }
317 | ```
318 | Result:
319 | ```
320 | 60
321 | 30
322 | 60
323 | 50
324 | ```
325 |
326 | Now you can see value of the static variable printed 60 both the times, as both obj1 and obj2 were referring to the same variable. With the non-static variable, the outputs differ, as each object when created keeps its own copy of non-static variable; changes made to them do not impact on the other copy of the variable created by another object.
327 |
328 |
329 |
330 |
331 |
332 | ##
333 | # Operators
334 | [Previous](../01_Hello_world/hello_world.md) Hello World
335 |
336 | [Next](../03_Operators/operators.md) Operators
337 |
--------------------------------------------------------------------------------
/04_Control_structures/control_structures.md:
--------------------------------------------------------------------------------
1 | [Previous](../03_Operators/operators.md) Operators
2 |
3 | [Next](../05_Loops/loops.md) Loops
4 |
5 |
6 |
7 | * [Control Structures](./control_structures.md)
8 | * [Conditions](./control_structures.md#conditions)
9 | * [if Statement](./control_structures.md#if-statement)
10 | * [If-Else Statement](./control_structures.md#if-else-statement)
11 | * [Nested-if](./control_structures.md#nested-if-statement)
12 | * [if-else-if ladder](./control_structures.md#if-else-if-ladder)
13 | * [Switch Case](./control_structures.md#switch-case)
14 | * [Jump](./control_structures.md#jump)
15 | * [Continue](./control_structures.md#continue)
16 | * [Break](./control_structures.md#break)
17 | * [Return](./control_structures.md#return)
18 |
19 |
20 |
21 | # Control Flow in Java
22 |
23 | In a program, we modify and repeat the data several times. We need some tools for these modifications that will control the flow of the program, and to perform this type of tasks Java Provides control statements.
24 |
25 |
26 | ## Conditions
27 |
28 | Java’s Selection statements:
29 |
30 | * if
31 | * if-else
32 | * nested-if
33 | * if-else-if
34 | * switch-case
35 | * jump – break, continue, return
36 |
37 | ## if Statement
38 | The **If** statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not .
39 |
40 | i.e if a certain condition is true then a block of statements is executed otherwise not.
41 |
42 |
43 | ```C
44 | if(condition)
45 | {
46 | // Statements to execute if
47 | // condition is true
48 | }
49 | ```
50 | Example:
51 | ```C
52 | // Java program to illustrate If statement without curly block
53 | import java.util.*;
54 |
55 | class IfDemo {
56 | public static void main(String args[])
57 | {
58 | int i = 10;
59 |
60 | if (i < 15)
61 | System.out.println("Inside If block"); // part of if block(immediate one statement after if condition)
62 | System.out.println("10 is less than 15"); //always executes as it is outside of if block
63 | // This statement will be executed
64 | // as if considers one statement by default again below statement is outside of if block
65 | System.out.println("I am Not in if");
66 | }
67 | }
68 |
69 | ```
70 | Output:
71 | ```
72 | Inside If block
73 | 10 is less than 15
74 | I am Not in if
75 | ```
76 | ## If-Else Statement
77 |
78 | The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false? Here comes the else statement. We can use the else statement with the if statement to execute a block of code when the condition is false.
79 |
80 |
81 | ```C
82 | if (condition)
83 | {
84 | // Executes this block if
85 | // condition is true
86 | }
87 | else
88 | {
89 | // Executes this block if
90 | // condition is false
91 | }
92 | ```
93 | Example:
94 | ```C
95 | // Java program to illustrate if-else statement
96 | import java.util.*;
97 |
98 | class IfElseDemo {
99 | public static void main(String args[])
100 | {
101 | int i = 10;
102 |
103 | if (i < 15)
104 | System.out.println("i is smaller than 15");
105 | else
106 | System.out.println("i is greater than 15");
107 | }
108 | }
109 |
110 | ```
111 | Output:
112 | ```
113 | i is smaller than 15
114 | ```
115 | # Nested-if Statement
116 |
117 | A nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside an if statement. Yes, java allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
118 |
119 |
120 | Syntax of the Nested-If statement:
121 | ```C
122 | if (condition1)
123 | {
124 | // Executes when condition1 is true
125 | if (condition2)
126 | {
127 | // Executes when condition2 is true
128 | }
129 | }
130 | ```
131 | Example:
132 | ```C
133 | // Java program to illustrate nested-if statement
134 | import java.util.*;
135 |
136 | class NestedIfDemo {
137 | public static void main(String args[])
138 | {
139 | int i = 10;
140 |
141 | if (i == 10 || i<15) {
142 | // First if statement
143 | if (i < 15)
144 | System.out.println("i is smaller than 15");
145 |
146 | // Nested - if statement
147 | // Will only be executed if statement above
148 | // it is true
149 | if (i < 12)
150 | System.out.println(
151 | "i is smaller than 12 too");
152 | } else{
153 | System.out.println("i is greater than 15");
154 | }
155 | }
156 | }
157 |
158 | ```
159 | Output:
160 | ```
161 | i is smaller than 15
162 | i is smaller than 12 too
163 | ```
164 | # if-else-if ladder
165 |
166 | Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that ‘if’ is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. There can be as many as ‘else if’ blocks associated with one ‘if’ block but only one ‘else’ block is allowed with one ‘if’ block.
167 |
168 |
169 | Syntax:
170 | ```C
171 | if (condition)
172 | statement;
173 | else if (condition)
174 | statement;
175 | .
176 | .
177 | else
178 | statement;
179 | ```
180 | Example:
181 |
182 | ```C
183 | // Java program to illustrate if-else-if ladder
184 | import java.util.*;
185 |
186 | class ifelseifDemo {
187 | public static void main(String args[])
188 | {
189 | int i = 20;
190 |
191 | if (i == 10)
192 | System.out.println("i is 10");
193 | else if (i == 15)
194 | System.out.println("i is 15");
195 | else if (i == 20)
196 | System.out.println("i is 20");
197 | else
198 | System.out.println("i is not present");
199 | }
200 | }
201 |
202 | ```
203 | Output:
204 |
205 | ```
206 | i is 20
207 |
208 | ```
209 |
210 | # Switch case
211 |
212 | The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
213 |
214 |
215 | Syntax of Switches:
216 | ```C
217 | switch (expression)
218 | {
219 | case value1:
220 | statement1;
221 | break;
222 | case value2:
223 | statement2;
224 | break;
225 | .
226 | .
227 | case valueN:
228 | statementN;
229 | break;
230 | default:
231 | statementDefault;
232 | }
233 | ```
234 |
235 | Example:
236 | ```C
237 | /*package whatever //do not write package name here */
238 |
239 | import java.io.*;
240 |
241 | class GFG {
242 | public static void main (String[] args) {
243 | int num=20;
244 | switch(num){
245 | case 5 : System.out.println("It is 5");
246 | break;
247 | case 10 : System.out.println("It is 10");
248 | break;
249 | case 15 : System.out.println("It is 15");
250 | break;
251 | case 20 : System.out.println("It is 20");
252 | break;
253 | default: System.out.println("Not present");
254 |
255 | }
256 | }
257 | }
258 |
259 | ```
260 | Output
261 | ```
262 | It is 20
263 | ```
264 |
265 | # Jump
266 |
267 | Java supports three jump statements: ```break```, ```continue``` and ```return```.
268 |
269 | These three statements transfer control to another part of the program.
270 |
271 |
272 | ## Break
273 |
274 |
275 | Terminate a sequence in a switch statement (discussed above).
276 |
277 |
278 |
279 | To exit a loop.
280 |
281 |
282 |
283 | Used as a “civilized” form of goto.
284 |
285 | ## Continue
286 |
287 | Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such an action.
288 |
289 |
290 | Example:
291 |
292 | ```c
293 | // Java program to illustrate using
294 | // continue in an if statement
295 | import java.util.*;
296 |
297 | class ContinueDemo {
298 | public static void main(String args[])
299 | {
300 | for (int i = 0; i < 10; i++) {
301 | // If the number is even
302 | // skip and continue
303 | if (i % 2 == 0)
304 | continue;
305 |
306 | // If number is odd, print it
307 | System.out.print(i + " ");
308 | }
309 | }
310 | }
311 |
312 | ```
313 | Output
314 |
315 | ```
316 | 1 3 5 7 9
317 |
318 | ```
319 | ## Return
320 |
321 | The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method.
322 |
323 | Example
324 |
325 | ```c
326 | // Java program to illustrate using return
327 | import java.util.*;
328 |
329 | public class Return {
330 | public static void main(String args[])
331 | {
332 | boolean t = true;
333 | System.out.println("Before the return.");
334 |
335 | if (t)
336 | return;
337 |
338 | // Compiler will bypass every statement
339 | // after return
340 | System.out.println("This won't execute.");
341 | }
342 | }
343 |
344 | ```
345 |
346 | Output
347 |
348 | ```
349 | Before the return.
350 | ```
351 |
352 | [Previous](../03_Operators/operators.md) Operators
353 |
354 | [Next](../05_Loops/loops.md) Loops
355 |
--------------------------------------------------------------------------------
/05_Loops/loops.md:
--------------------------------------------------------------------------------
1 | [Previous](../04_Control_structure/control_structure.md) Control Flow
2 |
3 | [Next](../06_Arrays/arrays.md) Arrays
4 |
5 | * [Loops](./loops.md#loops)
6 | * [While Loop](./loops.md#While-loop)
7 | * [For Loop](./loops.md#For-loop)
8 | * [Do while Loop](./loops.md#Do-while)
9 | * [Nested Loop](./loops.md#Nested-loop)
10 | * [Nested while Loop ](./loops.md#Nested-while)
11 |
12 |
13 |
14 | # Loops
15 |
16 | Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.
17 |
18 |
19 |
20 | Here are the types of loops in C:
21 | * While loop
22 | * For loop
23 | * Do while loop
24 | Nested loop
25 | * Nested while
26 | * Nested do while
27 | * Nested while and for loop
28 |
29 |
30 | ## While loop
31 |
32 | A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
33 |
34 |
35 | basic syntax of a while loop:
36 |
37 | ```C
38 | while (boolean condition)
39 | {
40 | loop statements...
41 | }
42 | ```
43 |
44 | Example:
45 |
46 | ```C
47 | /*package whatever //do not write package name here */
48 |
49 | import java.io.*;
50 |
51 | class GFG {
52 | public static void main (String[] args) {
53 | int i=0;
54 | while (i<=10)
55 | {
56 | System.out.println(i);
57 | i++;
58 | }
59 | }
60 | }
61 |
62 | ```
63 | Output
64 | ```
65 | 0
66 | 1
67 | 2
68 | 3
69 | 4
70 | 5
71 | 6
72 | 7
73 | 8
74 | 9
75 | 10
76 |
77 | ```
78 |
79 | ## for loop
80 |
81 | for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
82 |
83 | Syntax:
84 | ```C
85 | for (initialization condition; testing condition;increment/decrement)
86 | {
87 | statement(s)
88 | }
89 | ```
90 |
91 | Example:
92 |
93 | ```c
94 | /*package whatever //do not write package name here */
95 |
96 | import java.io.*;
97 |
98 | class GFG {
99 | public static void main (String[] args) {
100 | for (int i=0;i<=10;i++)
101 | {
102 | System.out.println(i);
103 | }
104 | }
105 | }
106 |
107 | ```
108 | Output
109 | ```
110 | 0
111 | 1
112 | 2
113 | 3
114 | 4
115 | 5
116 | 6
117 | 7
118 | 8
119 | 9
120 | 10
121 | ```
122 |
123 | ## Do while
124 |
125 | do while loop is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop.
126 |
127 | Syntax:
128 | ```C
129 | do
130 | {
131 | statements..
132 | }
133 | while (condition);
134 | ```
135 | Example:
136 |
137 | ```c
138 | /*package whatever //do not write package name here */
139 |
140 | import java.io.*;
141 |
142 | class GFG {
143 | public static void main (String[] args) {
144 | int i=0;
145 | do
146 | {
147 | System.out.println(i);
148 | i++;
149 | }while(i<=10);
150 | }
151 | }
152 |
153 | ```
154 | Output
155 | ```
156 | 0
157 | 1
158 | 2
159 | 3
160 | 4
161 | 5
162 | 6
163 | 7
164 | 8
165 | 9
166 | 10
167 | ```
168 |
169 | # Nested Loop
170 |
171 | Nested loop means a loop statement inside another loop statement.
172 |
173 | There are different combinations of loop using ```for loop```, ```while loop,``` ```do-while loop.```
174 |
175 | ## Nested for loop
176 |
177 | ```c
178 |
179 | /*package whatever //do not write package name here */
180 |
181 | import java.io.*;
182 |
183 | class GFG {
184 | public static void main (String[] args) {
185 | for(int i = 0; i < 3; i++){
186 | for(int j = 0; j < 2; j++){
187 | System.out.println(i);
188 | }
189 | System.out.println();
190 | }
191 | }
192 | }
193 |
194 | ```
195 |
196 | Output
197 | ```
198 | 0
199 | 0
200 |
201 | 1
202 | 1
203 |
204 | 2
205 | 2
206 | ```
207 |
208 | ## Nested while loop
209 |
210 | ```c
211 | import java.io.*;
212 |
213 | class GFG {
214 | public static void main(String[] args)
215 | {
216 | int i = 1, j = 1;
217 | while (i <= 3) {
218 | while (j <= 3) {
219 | System.out.print(j);
220 | j++;
221 | }
222 | i++;
223 | System.out.println("");
224 | j = 1;
225 | }
226 | }
227 | }
228 |
229 | ```
230 | Output
231 | ```
232 | 123
233 | 123
234 | 123
235 | ```
236 |
237 | ## Nested do while loop
238 |
239 | ```c
240 | /*package whatever //do not write package name here */
241 |
242 | import java.io.*;
243 |
244 | class GFG {
245 | public static void main(String[] args)
246 | {
247 |
248 | int row = 1, column = 1;
249 | int x;
250 | do {
251 | x = 4;
252 | do {
253 | System.out.print("");
254 | x--;
255 | } while (x >= row);
256 | column = 1;
257 | do {
258 | System.out.print(column + " ");
259 | column++;
260 |
261 | } while (column <= 5);
262 | System.out.println(" ");
263 | row++;
264 | } while (row <= 5);
265 | }
266 | }
267 |
268 | ```
269 |
270 | Output
271 | ```
272 | 1 2 3 4 5
273 | 1 2 3 4 5
274 | 1 2 3 4 5
275 | 1 2 3 4 5
276 | 1 2 3 4 5
277 |
278 | ```
279 | ## Nested while and for loop
280 |
281 | ```c
282 | /*package whatever //do not write package name here */
283 |
284 | import java.io.*;
285 |
286 | class GFG {
287 | public static void main(String[] args)
288 | {
289 |
290 | int weeks = 3;
291 | int days = 7;
292 | int i = 1;
293 |
294 | // outer loop
295 | while (i <= weeks) {
296 | System.out.println("Week: " + i);
297 |
298 | // inner loop
299 | for (int j = 1; j <= days; ++j) {
300 | System.out.println(" Days: " + j);
301 | }
302 | ++i;
303 | }
304 | }
305 | }
306 |
307 | ```
308 | Output
309 |
310 | ```
311 | Week: 1
312 | Days: 1
313 | Days: 2
314 | Days: 3
315 | Days: 4
316 | Days: 5
317 | Days: 6
318 | Days: 7
319 | Week: 2
320 | Days: 1
321 | Days: 2
322 | Days: 3
323 | Days: 4
324 | Days: 5
325 | Days: 6
326 | Days: 7
327 | Week: 3
328 | Days: 1
329 | Days: 2
330 | Days: 3
331 | Days: 4
332 | Days: 5
333 | Days: 6
334 | Days: 7
335 |
336 | ```
337 |
338 | # Pitfalls of Java
339 |
340 | ```Infinite loop```
341 |
342 | One of the most common mistakes while implementing any sort of looping is that it may not ever exit, that is the loop runs for infinite time. This happens when the condition fails for some reason
343 |
344 | Example
345 |
346 | Infinite for loop
347 |
348 | ```c
349 | /*package whatever //do not write package name here */
350 |
351 | import java.io.*;
352 |
353 | class GFG {
354 | public static void main(String[] args)
355 | {
356 | for (;;) {
357 | }
358 | }
359 | }
360 |
361 | ```
362 | Infinite while loop
363 |
364 | ```c
365 | //Java program to illustrate various pitfalls.
366 | public class LooppitfallsDemo
367 | {
368 | public static void main(String[] args)
369 | {
370 |
371 | // infinite loop because condition is not apt
372 | // condition should have been i>0.
373 | for (int i = 5; i != 0; i -= 2)
374 | {
375 | System.out.println(i);
376 | }
377 | int x = 5;
378 |
379 | // infinite loop because update statement
380 | // is not provided.
381 | while (x == 5)
382 | {
383 | System.out.println("In the loop");
384 | }
385 | }
386 | }
387 |
388 | ```
389 |
390 |
391 |
392 | [Previous](../04_Control_structure/control_structure.md) Control Flow
393 |
394 | [Next](../06_Arrays/arrays.md) Arrays
395 |
--------------------------------------------------------------------------------
/06_Arrays/2D_Arrays:
--------------------------------------------------------------------------------
1 | //2d array intro (3x3 Matrix)
2 | import java.util.*;
3 | class new_arrays {
4 | public static void main(String[] args) {
5 | int [][]arr=new int[3][3];
6 | Scanner sc=new Scanner(System.in);
7 | for (int i = 0; i < arr.length; i++) {
8 | for (int j = 0; j < arr[i].length; j++) {
9 | arr[i][j]=sc.nextInt();
10 | }
11 | }
12 | for(int []i:arr){
13 | for(int j:i) {
14 | System.out.print(j+" ");
15 | }
16 | System.out.println();
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/07_Lists/lists.md:
--------------------------------------------------------------------------------
1 | [Previous](../06_Arrays/Arrays.md) Arrays
2 |
3 | [Next](../08_Strings/strings.md) Strings
4 |
5 |
6 | * [Lists](./lists.md)
7 | * [Lists in Java](./lists.md#lists-in-java)
8 | * [Creating Lists](./lists.md#creating-lists)
9 | * [Convert Array to List](./lists.md#convert-array-to-list)
10 | * [Convert List to Array](./lists.md#convert-list-to-array)
11 | * [Sort List](./lists.md#sort-list)
12 | * [Adding elements to List class](./lists.md#adding-elements-to-list-class)
13 | * [Updating elements](./lists.md#updating-elements)
14 | * [Searching for elements](./lists.md#searching-for-elements)
15 | * [Removing elements](./lists.md#removing-elements)
16 |
17 | ## Lists in Java
18 |
19 | The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.
20 |
21 | The List interface is found in java.util package and inherits the Collection interface. It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward directions. The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector. ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5.
22 |
23 |
24 |
25 | ## Creating Lists
26 |
27 | The ArrayList and LinkedList classes provide the implementation of List interface. Let's see the examples to create the List:
28 |
29 | ```c
30 | //Creating a List of type String using ArrayList
31 | List list=new ArrayList();
32 |
33 | //Creating a List of type Integer using ArrayList
34 | List list=new ArrayList();
35 |
36 | //Creating a List of type Book using ArrayList
37 | List list=new ArrayList();
38 |
39 | //Creating a List of type String using LinkedList
40 | List list=new LinkedList();
41 | ```
42 |
43 | In short, you can create the List of any type. The ArrayList and LinkedList classes are used to specify the type. Here, T denotes the type.
44 |
45 |
46 | ## Convert Array to List
47 |
48 | We can convert the Array to List by traversing the array and adding the element in list one by one using list.add() method. Let's see a simple example to convert array elements into List.
49 |
50 | ```c
51 | import java.util.*;
52 | public class ArrayToListExample{
53 | public static void main(String args[]){
54 | //Creating Array
55 | String[] array={"Java","Python","PHP","C++"};
56 | System.out.println("Printing Array: "+Arrays.toString(array));
57 | //Converting Array to List
58 | List list=new ArrayList();
59 | for(String lang:array){
60 | list.add(lang);
61 | }
62 | System.out.println("Printing List: "+list);
63 |
64 | }
65 | }
66 | ```
67 |
68 | Output:
69 |
70 | ```
71 | Printing Array: [Java, Python, PHP, C++]
72 | Printing List: [Java, Python, PHP, C++]
73 | ```
74 |
75 | ## Convert List to Array
76 |
77 | We can convert the List to Array by calling the list.toArray() method. Let's see a simple example to convert list elements into array.
78 |
79 | ```c
80 | import java.util.*;
81 | public class ListToArrayExample{
82 | public static void main(String args[]){
83 | List fruitList = new ArrayList<>();
84 | fruitList.add("Mango");
85 | fruitList.add("Banana");
86 | fruitList.add("Apple");
87 | fruitList.add("Strawberry");
88 | //Converting ArrayList to Array
89 | String[] array = fruitList.toArray(new String[fruitList.size()]);
90 | System.out.println("Printing Array: "+Arrays.toString(array));
91 | System.out.println("Printing List: "+fruitList);
92 | }
93 | }
94 | ```
95 | Output:
96 |
97 | ```
98 | Printing Array: [Mango, Banana, Apple, Strawberry]
99 | Printing List: [Mango, Banana, Apple, Strawberry]
100 | ```
101 |
102 | ## Sort List
103 |
104 | There are various ways to sort the List, here we are going to use Collections.sort() method to sort the list element. The java.util package provides a utility class **Collections** which has the static method sort(). Using the ```Collections.sort()``` method, we can easily sort any List.
105 |
106 | ```c
107 | import java.util.*;
108 | class SortArrayList{
109 | public static void main(String args[]){
110 | //Creating a list of fruits
111 | List list1=new ArrayList();
112 | list1.add("Mango");
113 | list1.add("Apple");
114 | list1.add("Banana");
115 | list1.add("Grapes");
116 | //Sorting the list
117 | Collections.sort(list1);
118 | //Traversing list through the for-each loop
119 | for(String fruit:list1)
120 | System.out.println(fruit);
121 |
122 | System.out.println("Sorting numbers...");
123 | //Creating a list of numbers
124 | List list2=new ArrayList();
125 | list2.add(21);
126 | list2.add(11);
127 | list2.add(51);
128 | list2.add(1);
129 | //Sorting the list
130 | Collections.sort(list2);
131 | //Traversing list through the for-each loop
132 | for(Integer number:list2)
133 | System.out.println(number);
134 | }
135 |
136 | }
137 | ```
138 |
139 | Output:
140 |
141 | ```
142 | Apple
143 | Banana
144 | Grapes
145 | Mango
146 | Sorting numbers...
147 | 1
148 | 11
149 | 21
150 | 51
151 | ```
152 |
153 |
154 | ## Operations in a List interface
155 |
156 | Since List is an interface, it can be used only with a class that implements this interface. Now, let’s see how to perform a few frequently used operations on the List.
157 |
158 | 1) Operation 1: Adding elements to List class using add() method
159 |
160 |
161 | 2) Operation 2: Updating elements in List class using set() method
162 |
163 |
164 | 3) Operation 3: Searching for elements using indexOf(), lastIndexOf, contains() methods
165 |
166 |
167 | 4) Operation 4: Removing elements using remove() method
168 |
169 |
170 | ## Adding elements to List class
171 |
172 | In order to add an element to the list, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters.
173 |
174 | **Parameters**
175 |
176 | **add(Object)**: This method is used to add an element at the end of the List.
177 |
178 | **add(int index, Object)**: This method is used to add an element at a specific index in the List
179 |
180 |
181 | Example
182 |
183 | ```c
184 |
185 | // Java Program to Add Elements to a List
186 |
187 | // Importing all utility classes
188 | import java.util.*;
189 |
190 | // Main class
191 | class GFG {
192 |
193 | // Main driver method
194 | public static void main(String args[])
195 | {
196 | // Creating an object of List interface,
197 | // implemented by ArrayList class
198 | List al = new ArrayList<>();
199 |
200 | // Adding elements to object of List interface
201 | // Custom elements
202 | al.add("Geeks");
203 | al.add("Geeks");
204 | al.add(1, "For");
205 |
206 | // Print all the elements inside the
207 | // List interface object
208 | System.out.println(al);
209 | }
210 | }
211 |
212 | ```
213 |
214 | Output
215 |
216 | ```
217 | [Geeks, For, Geeks]
218 |
219 | ```
220 |
221 | ## Updating elements
222 |
223 | After adding the elements, if we wish to change the element, it can be done using the set() method. Since List is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index.
224 |
225 | Example:
226 |
227 | ```c
228 |
229 | // Java Program to Update Elements in a List
230 |
231 | // Importing utility classes
232 | import java.util.*;
233 |
234 | // Main class
235 | class GFG {
236 |
237 | // Main driver method
238 | public static void main(String args[])
239 | {
240 | // Creating an object of List interface
241 | List al = new ArrayList<>();
242 |
243 | // Adding elements to object of List class
244 | al.add("Geeks");
245 | al.add("Geeks");
246 | al.add(1, "Geeks");
247 |
248 | // Display theinitial elements in List
249 | System.out.println("Initial ArrayList " + al);
250 |
251 | // Setting (updating) element at 1st index
252 | // using set() method
253 | al.set(1, "For");
254 |
255 | // Print and display the updated List
256 | System.out.println("Updated ArrayList " + al);
257 | }
258 | }
259 |
260 | ```
261 |
262 | Output
263 |
264 | ```c
265 |
266 | Initial ArrayList [Geeks, Geeks, Geeks]
267 | Updated ArrayList [Geeks, For, Geeks]
268 |
269 | ```
270 |
271 | ## Searching for elements
272 |
273 | Searching for elements in the List interface is a common operation in Java programming. The List interface provides several methods to search for elements, such as the indexOf(), lastIndexOf(), and contains() methods.
274 |
275 |
276 | The ```indexOf()``` method returns the index of the first occurrence of a specified element in the list, while the lastIndexOf() method returns the index of the last occurrence of a specified element.
277 |
278 |
279 | The ```contains()``` method returns true if the list contains the specified element, and false otherwise. These methods allow for quick and easy searching of elements in a list and enable efficient operations on them.
280 |
281 |
282 | Parameters:
283 |
284 | ```indexOf(element)```: Returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found
285 |
286 |
287 | ```lastIndexOf(element)```: Returns the index of the last occurrence of the specified element in the list, or -1 if the element is not found
288 |
289 |
290 | ```contains(element)```: Returns true if the list contains the specified element.
291 |
292 |
293 | Example
294 |
295 | ```c
296 |
297 | import java.util.ArrayList;
298 | import java.util.List;
299 |
300 | public class ListExample {
301 | public static void main(String[] args) {
302 | // create a list of integers
303 | List numbers = new ArrayList<>();
304 |
305 | // add some integers to the list
306 | numbers.add(1);
307 | numbers.add(2);
308 | numbers.add(3);
309 | numbers.add(2);
310 |
311 | // use indexOf() to find the first occurrence of an element in the list
312 | int index = numbers.indexOf(2);
313 | System.out.println("The first occurrence of 2 is at index " + index);
314 |
315 | // use lastIndexOf() to find the last occurrence of an element in the list
316 | int lastIndex = numbers.lastIndexOf(2);
317 | System.out.println("The last occurrence of 2 is at index " + lastIndex);
318 |
319 | // use contains() to check if the list contains a specific element
320 | boolean containsTwo = numbers.contains(2);
321 | System.out.println("The list contains 2: " + containsTwo);
322 | }
323 | }
324 |
325 | ```
326 |
327 | Output
328 |
329 | ```
330 | The first occurrence of 2 is at index 1
331 | The last occurrence of 2 is at index 3
332 | The list contains 2: true
333 |
334 | ```
335 |
336 | ## Removing Elements
337 |
338 | In order to remove an element from a list, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are:
339 |
340 | **Parameters**
341 |
342 | ```remove(Object)```: This method is used to simply remove an object from the List. If there are multiple such objects, then the first occurrence of the object is removed.
343 |
344 |
345 | ```remove(int index)```: Since a List is indexed, this method takes an integer value which simply removes the element present at that specific index in the List. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated.
346 |
347 |
348 | Example
349 |
350 | ```c
351 |
352 | // Java Program to Remove Elements from a List
353 |
354 | // Importing List and ArrayList classes
355 | // from java.util package
356 | import java.util.ArrayList;
357 | import java.util.List;
358 |
359 | // Main class
360 | class GFG {
361 |
362 | // Main driver method
363 | public static void main(String args[])
364 | {
365 |
366 | // Creating List class object
367 | List al = new ArrayList<>();
368 |
369 | // Adding elements to the object
370 | // Custom inputs
371 | al.add("Geeks");
372 | al.add("Geeks");
373 |
374 | // Adding For at 1st indexes
375 | al.add(1, "For");
376 |
377 | // Print the initialArrayList
378 | System.out.println("Initial ArrayList " + al);
379 |
380 | // Now remove element from the above list
381 | // present at 1st index
382 | al.remove(1);
383 |
384 | // Print the List after removal of element
385 | System.out.println("After the Index Removal " + al);
386 |
387 | // Now remove the current object from the updated
388 | // List
389 | al.remove("Geeks");
390 |
391 | // Finally print the updated List now
392 | System.out.println("After the Object Removal "
393 | + al);
394 | }
395 | }
396 |
397 | ```
398 |
399 |
400 | Output
401 |
402 | ```
403 | Initial ArrayList [Geeks, For, Geeks]
404 | After the Index Removal [Geeks, Geeks]
405 | After the Object Removal [Geeks]
406 |
407 | ```
408 |
409 | #
410 | [Previous](../06_Loops/loops.md) Loops
411 |
412 | [Next](../08_Strings/strings.md) Strings
413 |
414 |
415 |
--------------------------------------------------------------------------------
/08_Strings/PalindromeChecker.java:
--------------------------------------------------------------------------------
1 | package 08_Strings;
2 |
3 | import java.util.Scanner;
4 |
5 | public class PalindromeChecker{
6 |
7 | //main() created, that will be recognised by compiler to initiate program execution
8 | public static void main(String args[]){
9 | Scanner sc = new Scanner(System.in); // Scanner class object created to take user input from console
10 | System.out.print("Enter a word - ");
11 | String wrd = sc.next();
12 | if (isPalin(wrd) == true) // using function call (pass-by-value technique) to check palindrome validity
13 | System.out.println(wrd+" is a Palindrome word");
14 | else
15 | System.out.println(wrd+" is not a Palindrome word");
16 | }
17 |
18 | // user-defined function used to reduce code complexity and enhance readability
19 | private static boolean isPalin(String s){
20 | boolean flag = false; // using flag-variable concept to check for validity
21 | String rev = "";
22 | // reversing the word by travesing using reverse indexing
23 | for (int i = s.length() - 1; i >= 0; i--)
24 | rev += Character.toString(s.charAt(i));
25 | // CONSTRAINT - CASE OF STRING WHILE CHECKING IS IGNORED
26 | if (rev.equalsIgnoreCase(s))
27 | flag = true;
28 | return flag;
29 | }
30 | }
31 |
32 |
--------------------------------------------------------------------------------
/08_Strings/strings.md:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/09_Functions/functions.md:
--------------------------------------------------------------------------------
1 | [Previous](../08_Strings/strings.md) Strings
2 |
3 | [Next](../10_Inheritance/inheritance.md) Inheritance
4 |
5 |
6 | * [Functions](./functions.md)
7 | * [Java Methods](./functions.md#java-methods)
8 | * [Create a Method](./functions.md#create-a-method)
9 | * [Call a Method](./functions.md#call-a-method)
10 | * [Java Method Parameters](./functions.md#java-method-parameters)
11 | * [Multiple Parameters](./functions.md#multiple-parameters)
12 | * [Return Values](./functions.md#return-values)
13 | * [A Method with If Else](./functions.md#a-method-with-if-else)
14 | * [Java Method Overloading](./functions.md#java-method-overloading)
15 | * [Java Recursion](./functions.md#java-recursion)
16 | * [Halting Condition](./functions.md#halting-condition)
17 |
18 | ## Java Methods
19 | A method is a block of code which only runs when it is called.
20 |
21 | You can pass data, known as parameters, into a method.
22 |
23 | Methods are used to perform certain actions, and they are also known as functions.
24 |
25 | Why use methods? To reuse code: define the code once, and use it many times.
26 |
27 | ## Create a Method
28 | A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as ```System.out.println()```, but you can also create your own methods to perform certain actions:
29 |
30 | Example
31 | ```c
32 | Create a method inside Main:
33 |
34 | public class Main {
35 | static void myMethod() {
36 | // code to be executed
37 | }
38 | }
39 | ```
40 |
41 |
42 | Example Explained
43 |
44 | - ```myMethod()``` is the name of the method
45 | - ```static``` means that the method belongs to the Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial.
46 | - ```void``` means that this method does not have a return value. You will learn more about return values later in this chapter
47 |
48 |
49 | ## Call a Method
50 | To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
51 |
52 | In the following example, myMethod() is used to print a text (the action), when it is called
53 |
54 | Example
55 |
56 | Inside main, call the myMethod() method:
57 | ```c
58 | public class Main {
59 | static void myMethod() {
60 | System.out.println("I just got executed!");
61 | }
62 |
63 | public static void main(String[] args) {
64 | myMethod();
65 | }
66 | }
67 |
68 | // Outputs "I just got executed!"
69 |
70 | ```
71 |
72 | A method can also be called multiple times:
73 |
74 | Example
75 | ```c
76 | public class Main {
77 | static void myMethod() {
78 | System.out.println("I just got executed!");
79 | }
80 |
81 | public static void main(String[] args) {
82 | myMethod();
83 | myMethod();
84 | myMethod();
85 | }
86 | }
87 |
88 | // I just got executed!
89 | // I just got executed!
90 | // I just got executed!
91 | ```
92 |
93 | # Java Method Parameters
94 |
95 | ## Parameters and Arguments
96 | Information can be passed to methods as parameter. Parameters act as variables inside the method.
97 |
98 | Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
99 |
100 | The following example has a method that takes a String called fname as parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name:
101 |
102 | Example
103 | ```c
104 | public class Main {
105 | static void myMethod(String fname) {
106 | System.out.println(fname + " Refsnes");
107 | }
108 |
109 | public static void main(String[] args) {
110 | myMethod("Liam");
111 | myMethod("Jenny");
112 | myMethod("Anja");
113 | }
114 | }
115 | // Liam Refsnes
116 | // Jenny Refsnes
117 | // Anja Refsnes
118 | ```
119 |
120 | ## Multiple Parameters
121 | You can have as many parameters as you like:
122 |
123 | Example
124 | ```c
125 | public class Main {
126 | static void myMethod(String fname, int age) {
127 | System.out.println(fname + " is " + age);
128 | }
129 |
130 | public static void main(String[] args) {
131 | myMethod("Liam", 5);
132 | myMethod("Jenny", 8);
133 | myMethod("Anja", 31);
134 | }
135 | }
136 |
137 | // Liam is 5
138 | // Jenny is 8
139 | // Anja is 31
140 | ```
141 |
142 | ## Return Values
143 | The ```void``` keyword, used in the examples above, indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method:
144 |
145 | Example
146 | ```c
147 | public class Main {
148 | static int myMethod(int x) {
149 | return 5 + x;
150 | }
151 |
152 | public static void main(String[] args) {
153 | System.out.println(myMethod(3));
154 | }
155 | }
156 | // Outputs 8 (5 + 3)
157 | ```
158 |
159 | This example returns the sum of a method's two parameters:
160 |
161 | Example
162 | ```c
163 | public class Main {
164 | static int myMethod(int x, int y) {
165 | return x + y;
166 | }
167 |
168 | public static void main(String[] args) {
169 | System.out.println(myMethod(5, 3));
170 | }
171 | }
172 | // Outputs 8 (5 + 3)
173 | ```
174 |
175 | ## A Method with If Else
176 | It is common to use if...else statements inside methods:
177 |
178 | Example
179 | ```c
180 | public class Main {
181 |
182 | // Create a checkAge() method with an integer variable called age
183 | static void checkAge(int age) {
184 |
185 | // If age is less than 18, print "access denied"
186 | if (age < 18) {
187 | System.out.println("Access denied - You are not old enough!");
188 |
189 | // If age is greater than, or equal to, 18, print "access granted"
190 | } else {
191 | System.out.println("Access granted - You are old enough!");
192 | }
193 |
194 | }
195 |
196 | public static void main(String[] args) {
197 | checkAge(20); // Call the checkAge method and pass along an age of 20
198 | }
199 | }
200 |
201 | // Outputs "Access granted - You are old enough!"
202 | ```
203 |
204 | Test Yourself With Exercises
205 | Exercise:
206 | Add a ```fname``` parameter of type ```String``` to ```myMethod```, and output "John Doe":
207 | ```c
208 | static void myMethod(
209 |
210 | ) {
211 | System.out.println(
212 | + " Doe");
213 | }
214 |
215 | public static void main(String[] args) {
216 | myMethod("John");
217 | }
218 | ```
219 |
220 | # Java Method Overloading
221 |
222 | ## Method Overloading
223 | With method overloading, multiple methods can have the same name with different parameters:
224 |
225 | Example
226 | ```c
227 | int myMethod(int x)
228 | float myMethod(float x)
229 | double myMethod(double x, double y)
230 | Consider the following example, which has two methods that add numbers of different type:
231 |
232 | ExampleGet your own Java Server
233 | static int plusMethodInt(int x, int y) {
234 | return x + y;
235 | }
236 |
237 | static double plusMethodDouble(double x, double y) {
238 | return x + y;
239 | }
240 |
241 | public static void main(String[] args) {
242 | int myNum1 = plusMethodInt(8, 5);
243 | double myNum2 = plusMethodDouble(4.3, 6.26);
244 | System.out.println("int: " + myNum1);
245 | System.out.println("double: " + myNum2);
246 | }
247 | ```
248 |
249 | Instead of defining two methods that should do the same thing, it is better to overload one.
250 |
251 | In the example below, we overload the plusMethod method to work for both int and double:
252 |
253 | Example
254 | ```c
255 | static int plusMethod(int x, int y) {
256 | return x + y;
257 | }
258 |
259 | static double plusMethod(double x, double y) {
260 | return x + y;
261 | }
262 |
263 | public static void main(String[] args) {
264 | int myNum1 = plusMethod(8, 5);
265 | double myNum2 = plusMethod(4.3, 6.26);
266 | System.out.println("int: " + myNum1);
267 | System.out.println("double: " + myNum2);
268 | }
269 | ```
270 |
271 | # Java Recursion
272 |
273 | ## Java Recursion
274 | Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.
275 |
276 | Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.
277 |
278 | Recursion Example
279 | Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding two numbers:
280 |
281 | Example
282 | ```c
283 | Use recursion to add all of the numbers up to 10.
284 |
285 | public class Main {
286 | public static void main(String[] args) {
287 | int result = sum(10);
288 | System.out.println(result);
289 | }
290 | public static int sum(int k) {
291 | if (k > 0) {
292 | return k + sum(k - 1);
293 | } else {
294 | return 0;
295 | }
296 | }
297 | }
298 | ```
299 |
300 | Example Explained:
301 |
302 | ```
303 | When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the result. When k becomes 0, the function just returns 0. When running, the program follows these steps:
304 |
305 | 10 + sum(9)
306 | 10 + ( 9 + sum(8) )
307 | 10 + ( 9 + ( 8 + sum(7) ) )
308 | ...
309 | 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
310 | 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
311 | Since the function does not call itself when k is 0, the program stops there and returns the result.
312 | ```
313 |
314 | ## Halting Condition
315 | Just as loops can run into the problem of infinite looping, recursive functions can run into the problem of infinite recursion. Infinite recursion is when the function never stops calling itself. Every recursive function should have a halting condition, which is the condition where the function stops calling itself. In the previous example, the halting condition is when the parameter k becomes 0.
316 |
317 | It is helpful to see a variety of different examples to better understand the concept. In this example, the function adds a range of numbers between a start and an end. The halting condition for this recursive function is when end is not greater than start:
318 |
319 | Example
320 | ```c
321 | Use recursion to add all of the numbers between 5 to 10.
322 |
323 | public class Main {
324 | public static void main(String[] args) {
325 | int result = sum(5, 10);
326 | System.out.println(result);
327 | }
328 | public static int sum(int start, int end) {
329 | if (end > start) {
330 | return end + sum(start, end - 1);
331 | } else {
332 | return end;
333 | }
334 | }
335 | }
336 | ```
337 |
338 | [Previous](../08_Strings/strings.md) Strings
339 |
340 | [Next](../10_Inheritance/inheritance.md) Inheritance
341 |
--------------------------------------------------------------------------------
/10_Inheritance/inheritance.md:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/11_Polymorphism/polymorphism.md:
--------------------------------------------------------------------------------
1 | # POLYMORPHISM IN JAVA
2 |
3 | Polymorphism is the ability to present the same interface for differing underlying forms (data types). With polymorphism, each of these classes will have different underlying data. Precisely, Poly means ‘many’ and morphism means ‘forms’.
4 |
5 |
6 | **Types of Polymorphism**
7 |
8 |
9 | 1. Compile Time Polymorphism (Static)
10 |
11 | 2. Runtime Polymorphism (Dynamic)
12 |
13 | ## ***Compile Time Polymorphism :***
14 |
15 | The polymorphism which is implemented at the compile time is known as compile-time polymorphism. Example - Method Overloading
16 | Example:
17 | multiply(num1, num2)
18 | multiply(num1, num2, num3)
19 |
20 | *Method Overloading*
21 |
22 | Method overloading is a technique which allows you to have more than one function with the same function name but with different functionality. Method overloading can be possible on the following basis:
23 |
24 | 1. The type of the parameters passed to the function.
25 |
26 |
27 | 2. The number of parameters passed to the function.
28 |
29 | ```
30 | class Student {
31 | String name;
32 | int age;
33 |
34 | public void displayInfo(String name) {
35 | System.out.println(name);
36 | }
37 |
38 |
39 | public void displayInfo(int age) {
40 | System.out.println(age);
41 | }
42 |
43 |
44 | public void displayInfo(String name, int age) {
45 | System.out.println(name);
46 | System.out.println(age);
47 | }
48 | }
49 |
50 | ```
51 |
52 | ## ***Runtime Polymorphism :***
53 |
54 | Runtime polymorphism is also known as dynamic polymorphism.
55 | Example:
56 | eat():
57 | implementation1: "Eating Fish"
58 | implementation1: "Eating Chips"
59 |
60 |
61 | ***Function overriding is an example of runtime polymorphism.***
62 |
63 |
64 | Function overriding means when the child class contains the method which is already present in the parent class. Hence, the child class overrides the method of the parent class. In case of function overriding, ***parent and child classes both contain the same function with a different definition.*** The call to the function is determined at runtime is known as runtime polymorphism.
65 |
66 |
67 | ```
68 | class Shape {
69 | public void area() {
70 | System.out.println("Displays Area of Shape");
71 | }
72 | }
73 | class Triangle extends Shape {
74 | public void area(int h, int b) {
75 | System.out.println((1/2)*b*h);
76 | }
77 | }
78 | class Circle extends Shape {
79 | public void area(int r) {
80 | System.out.println((3.14)*r*r);
81 | }
82 | }
83 | ```
84 |
85 | ### Benefits of polymorphism**
86 |
87 |
88 | Polymorphism offers a number of benefits, including:
89 |
90 | ## Code reuse:
91 |
92 | Polymorphism allows you to reuse code by writing methods that can be used with different types of objects. This can save you time and effort, and it can also make your code more maintainable.
93 |
94 |
95 | ## Flexibility:
96 | Polymorphism makes your code more flexible by allowing you to change the behavior of your program at runtime. This can be useful for implementing features such as pluggability and dynamic dispatch.
97 |
98 |
99 |
100 | ## Extensibility:
101 | Polymorphism makes your code more extensible by allowing you to add new functionality without breaking existing code. This is because you can override existing methods in subclasses to provide new implementations.
102 |
103 |
104 | **Conclusion**
105 | Polymorphism is a powerful feature of Java that can be used to write more reusable, flexible, and extensible code. By understanding how to use polymorphism, you can write better code that is easier to maintain and extend.
106 |
107 |
108 |
109 | ```
110 | // Create a superclass with a method
111 | class Animal {
112 | void makeSound() {
113 | System.out.println("Animal makes a sound");
114 | }
115 | }
116 |
117 | // Create subclasses that override the method
118 | class Dog extends Animal {
119 | @Override
120 | void makeSound() {
121 | System.out.println("Dog barks");
122 | }
123 | }
124 |
125 | class Cat extends Animal {
126 | @Override
127 | void makeSound() {
128 | System.out.println("Cat meows");
129 | }
130 | }
131 |
132 | // Create a class that uses polymorphism
133 | public class PolymorphismExample {
134 | public static void main(String[] args) {
135 | // Create objects of different subclasses
136 | Animal myDog = new Dog();
137 | Animal myCat = new Cat();
138 |
139 | // Call the makeSound method on each object
140 | myDog.makeSound(); // Output: Dog barks
141 | myCat.makeSound(); // Output: Cat meows
142 | }
143 | }
144 | ```
145 |
--------------------------------------------------------------------------------
/12_Exceptions/exceptions.md:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/13_File_io/file_io.md:
--------------------------------------------------------------------------------
1 |
2 | # File Input and Output in Java
3 |
4 | File input and output (I/O) operations are essential for reading data from and writing data to files in Java. This guide will introduce you to the basics of file I/O in Java.
5 |
6 | ## Reading from a File
7 |
8 | To read data from a file in Java, you can use the following steps:
9 |
10 | 1. **Import necessary classes**:
11 | ```java
12 | import java.io.*;
13 |
--------------------------------------------------------------------------------
/14_GUI_programming/gui_prime_for_beginners:
--------------------------------------------------------------------------------
1 |
2 | //java gui demo program
3 | import javax.swing.JOptionPane;
4 | public class new_prc {
5 | public static void main(String[] args) {
6 | String name=JOptionPane.showInputDialog("Enter a number: ");
7 | int n=Integer.parseInt(name);
8 | class new1{
9 | int z=1;
10 | public new1(int a){
11 | System.out.println(a);
12 | }
13 | }
14 | int x=0;
15 | for(int i=1;i<=n;i++){
16 | if(n%i==0){
17 | x++;
18 | }
19 | }
20 | if(x==2){
21 | JOptionPane.showMessageDialog(null,"Prime");
22 | }
23 | else
24 | JOptionPane.showMessageDialog(null,"Not Prime");
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/14_GUI_programming/gui_programming.md:
--------------------------------------------------------------------------------
1 |
2 | # GUI Programming with Java
3 |
4 | Graphical User Interface (GUI) programming is essential for creating user-friendly applications. In this resource, we will explore GUI programming in Java, focusing on the Java Swing library.
5 |
6 | ## Table of Contents
7 |
8 | 1. [Introduction to GUI Programming](#introduction-to-gui-programming)
9 | 2. [Setting Up the Development Environment](#setting-up-the-development-environment)
10 | 3. [Creating Your First GUI Application](#creating-your-first-gui-application)
11 | 4. [Swing Components](#swing-components)
12 | 5. [Layout Management](#layout-management)
13 | 6. [Event Handling](#event-handling)
14 | 7. [Advanced GUI Features](#advanced-gui-features)
15 | 8. [Tips and Best Practices](#tips-and-best-practices)
16 | 9. [Additional Resources](#additional-resources)
17 |
18 | ## Introduction to GUI Programming
19 |
20 | ### What is GUI Programming?
21 |
22 | GUI programming allows you to create applications with graphical interfaces, making them more user-friendly and interactive. This section introduces the importance of GUIs in modern software development.
23 |
24 | ### Java Swing - The GUI Toolkit
25 |
26 | Learn about Java Swing, a powerful library for creating GUI applications in Java. Understand its key features and advantages for cross-platform GUI development.
27 |
28 | ## Setting Up the Development Environment
29 |
30 | ### Installing Java
31 |
32 | Before you start building GUI applications, you need to set up your development environment. Follow step-by-step instructions to install Java on your system.
33 |
34 | ### Choosing an IDE
35 |
36 | Select an Integrated Development Environment (IDE) that suits your needs. We'll guide you through the installation and configuration of popular IDEs like IntelliJ IDEA and Eclipse.
37 |
38 | ## Creating Your First GUI Application
39 |
40 | ### Getting Started
41 |
42 | Let's dive into practical coding! Create a simple "Hello World" GUI application to get hands-on experience with Swing components and layout management.
43 |
44 | ### Understanding Swing Components
45 |
46 | Explore fundamental Swing components such as `JFrame`, `JPanel`, `JButton`, and `JLabel`. Learn how to add them to your application and set their properties.
47 |
48 | ## Swing Components
49 |
50 | ### Text Fields and Labels
51 |
52 | Implement text fields and labels to gather user input and display information. Customize their appearance and behavior to match your application's requirements.
53 |
54 | ### Buttons and ActionListeners
55 |
56 | Discover how to create interactive buttons and handle user actions with `ActionListener`. Implement click events and execute code in response to button clicks.
57 |
58 | ## Layout Management
59 |
60 | ### FlowLayout
61 |
62 | Efficiently arrange and manage the placement of GUI components within your application window using layout managers. Explore different layout managers like `BorderLayout`, `GridLayout`, and `FlowLayout`.
63 |
64 | ### BorderLayout
65 |
66 | Understand how to use `BorderLayout` to organize components in five regions: North, South, East, West, and Center. Create flexible and responsive user interfaces.
67 |
68 | ## Event Handling
69 |
70 | ### Event Listeners
71 |
72 | Master event handling in Swing by implementing event listeners. Respond to user interactions such as button clicks and mouse movements.
73 |
74 | ### Mouse and Keyboard Events
75 |
76 | Learn to capture and process mouse and keyboard events. Implement custom behavior based on user input.
77 |
78 | ## Advanced GUI Features
79 |
80 | ### Dialogs and Pop-ups
81 |
82 | Discover how to create dialog boxes and pop-up windows. Use them to display messages, receive user input, and handle important application events.
83 |
84 | ### Menus and Toolbars
85 |
86 | Design user-friendly menus and toolbars for your application. Implement dropdown menus, context menus, and toolbar buttons.
87 |
88 | ## Tips and Best Practices
89 |
90 | ### Design Principles
91 |
92 | Learn valuable tips and best practices for designing effective GUIs. Understand the principles of layout design, usability, and user experience.
93 |
94 | ### Code Organization
95 |
96 | Organize your GUI code for readability and maintainability. Apply design patterns and avoid common pitfalls.
97 |
98 | ## Additional Resources
99 |
100 | Explore further resources, tutorials, and books to deepen your knowledge of GUI programming with Java Swing.
101 |
102 | By the end of this learning resource, you'll have a solid foundation in GUI programming with Java and the skills to create user-friendly applications with ease.
103 |
104 | Start your journey into GUI programming with Java today!
105 |
--------------------------------------------------------------------------------
/15_Frameworks/frameworks.md:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/16_FirstContribution/Algorithms/FloydWarshall.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 | public class FloydWarshall {
3 | public static void main(String[] args) {
4 | int[][] graph = {
5 | {0, 5, Integer.MAX_VALUE, 10},
6 | {Integer.MAX_VALUE, 0, 3, Integer.MAX_VALUE},
7 | {Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 1},
8 | {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 0}
9 | };
10 |
11 | int[][] shortestDistances = floydWarshall(graph);
12 |
13 | // Display the shortest distances between all pairs of vertices
14 | for (int i = 0; i < shortestDistances.length; i++) {
15 | for (int j = 0; j < shortestDistances.length; j++) {
16 | if (shortestDistances[i][j] == Integer.MAX_VALUE) {
17 | System.out.print("INF\t");
18 | } else {
19 | System.out.print(shortestDistances[i][j] + "\t");
20 | }
21 | }
22 | System.out.println();
23 | }
24 | }
25 |
26 | public static int[][] floydWarshall(int[][] graph) {
27 | int V = graph.length;
28 | int[][] dist = new int[V][V];
29 |
30 | // Initialize distance matrix with the same values as the input graph
31 | for (int i = 0; i < V; i++) {
32 | for (int j = 0; j < V; j++) {
33 | dist[i][j] = graph[i][j];
34 | }
35 | }
36 |
37 | // Applying Floyd-Warshall algorithm
38 | for (int k = 0; k < V; k++) {
39 | for (int i = 0; i < V; i++) {
40 | for (int j = 0; j < V; j++) {
41 | // If vertex k is on the shortest path from i to j,
42 | // updating the distance
43 | if (dist[i][k] != Integer.MAX_VALUE && dist[k][j] != Integer.MAX_VALUE
44 | && dist[i][k] + dist[k][j] < dist[i][j]) {
45 | dist[i][j] = dist[i][k] + dist[k][j];
46 | }
47 | }
48 | }
49 | }
50 |
51 | return dist;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/16_FirstContribution/BuzzNumberChecker.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class BuzzNumberChecker {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 | System.out.print("Enter an integer: ");
7 |
8 | // Read the input integer
9 | int number = scanner.nextInt();
10 |
11 | // Check if it's a Buzz number
12 | if (isBuzzNumber(number)) {
13 | System.out.println(number + " is a Buzz number.");
14 | } else {
15 | System.out.println(number + " is not a Buzz number.");
16 | }
17 |
18 | // Close the scanner
19 | scanner.close();
20 | }
21 |
22 | // Function to check if a number is a Buzz number
23 | public static boolean isBuzzNumber(int number) {
24 | // Check if the number ends with 7 or is divisible by 7
25 | return (number % 10 == 7) || (number % 7 == 0);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/16_FirstContribution/Calculator.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class Calculator {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 |
7 | System.out.println("Simple Calculator");
8 | System.out.print("Enter the first number: ");
9 | double num1 = scanner.nextDouble();
10 |
11 | System.out.print("Enter the second number: ");
12 | double num2 = scanner.nextDouble();
13 |
14 | System.out.println("Select operation (+, -, *, /): ");
15 | char operator = scanner.next().charAt(0);
16 |
17 | double result;
18 |
19 | switch (operator) {
20 | case '+':
21 | result = num1 + num2;
22 | break;
23 | case '-':
24 | result = num1 - num2;
25 | break;
26 | case '*':
27 | result = num1 * num2;
28 | break;
29 | case '/':
30 | if (num2 != 0) {
31 | result = num1 / num2;
32 | } else {
33 | System.out.println("Error: Division by zero");
34 | return;
35 | }
36 | break;
37 | default:
38 | System.out.println("Error: Invalid operator");
39 | return;
40 | }
41 |
42 | System.out.println("Result: " + result);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/16_FirstContribution/Data Structures/CustomBinaryTree.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | /**
4 | * CustomBinaryTree is a simple implementation of a binary tree data structure in Java.
5 | */
6 | public class CustomBinaryTree {
7 | private Node root;
8 |
9 | /**
10 | * A class representing a node in the binary tree.
11 | */
12 | private static class Node {
13 | T data;
14 | Node left;
15 | Node right;
16 |
17 | Node(T data) {
18 | this.data = data;
19 | left = null;
20 | right = null;
21 | }
22 | }
23 |
24 | /**
25 | * Constructs an empty CustomBinaryTree.
26 | */
27 | public CustomBinaryTree() {
28 | root = null;
29 | }
30 |
31 | /**
32 | * Inserts a new node with the specified data into the binary tree.
33 | *
34 | * @param data the data to insert
35 | */
36 | public void insert(T data) {
37 | root = insertRecursive(root, data);
38 | }
39 |
40 | /**
41 | * Helper method to recursively insert a new node with the specified data into the binary tree.
42 | *
43 | * @param current the current node being considered
44 | * @param data the data to insert
45 | * @return the updated node after insertion
46 | */
47 | private Node insertRecursive(Node current, T data) {
48 | if (current == null) {
49 | return new Node<>(data);
50 | }
51 |
52 | if (compare(data, current.data) < 0) {
53 | current.left = insertRecursive(current.left, data);
54 | } else if (compare(data, current.data) > 0) {
55 | current.right = insertRecursive(current.right, data);
56 | }
57 |
58 | return current;
59 | }
60 |
61 | /**
62 | * Searches for a node with the specified data in the binary tree.
63 | *
64 | * @param data the data to search for
65 | * @return true if the data is found in the tree, false otherwise
66 | */
67 | public boolean search(T data) {
68 | return searchRecursive(root, data);
69 | }
70 |
71 | /**
72 | * Helper method to recursively search for a node with the specified data in the binary tree.
73 | *
74 | * @param current the current node being considered
75 | * @param data the data to search for
76 | * @return true if the data is found in the tree, false otherwise
77 | */
78 | private boolean searchRecursive(Node current, T data) {
79 | if (current == null) {
80 | return false;
81 | }
82 |
83 | if (compare(data, current.data) == 0) {
84 | return true;
85 | }
86 |
87 | if (compare(data, current.data) < 0) {
88 | return searchRecursive(current.left, data);
89 | }
90 |
91 | return searchRecursive(current.right, data);
92 | }
93 |
94 | /**
95 | * Deletes a node with the specified data from the binary tree.
96 | *
97 | * @param data the data to delete
98 | */
99 | public void delete(T data) {
100 | root = deleteRecursive(root, data);
101 | }
102 |
103 | /**
104 | * Helper method to recursively delete a node with the specified data from the binary tree.
105 | *
106 | * @param current the current node being considered
107 | * @param data the data to delete
108 | * @return the updated node after deletion
109 | */
110 | private Node deleteRecursive(Node current, T data) {
111 | if (current == null) {
112 | return null;
113 | }
114 |
115 | if (compare(data, current.data) < 0) {
116 | current.left = deleteRecursive(current.left, data);
117 | } else if (compare(data, current.data) > 0) {
118 | current.right = deleteRecursive(current.right, data);
119 | } else {
120 | if (current.left == null) {
121 | return current.right;
122 | } else if (current.right == null) {
123 | return current.left;
124 | }
125 |
126 | current.data = minValue(current.right);
127 | current.right = deleteRecursive(current.right, current.data);
128 | }
129 |
130 | return current;
131 | }
132 |
133 | /**
134 | * Finds the minimum value in the binary tree.
135 | *
136 | * @param node the root of the subtree to search
137 | * @return the minimum value in the tree
138 | */
139 | private T minValue(Node node) {
140 | T minValue = node.data;
141 | while (node.left != null) {
142 | minValue = node.left.data;
143 | node = node.left;
144 | }
145 | return minValue;
146 | }
147 |
148 | /**
149 | * Compares two elements to determine their order in the tree.
150 | *
151 | * @param a the first element
152 | * @param b the second element
153 | * @return a negative integer if a < b, 0 if a == b, a positive integer if a > b
154 | */
155 | private int compare(T a, T b) {
156 | return ((Comparable) a).compareTo(b);
157 | }
158 |
159 | /**
160 | * Performs an in-order traversal of the binary tree and returns the elements in sorted order.
161 | *
162 | * @return an array containing the sorted elements
163 | */
164 | public T[] inOrderTraversal() {
165 | @SuppressWarnings("unchecked")
166 | T[] result = (T[]) new Object[size()];
167 | inOrderTraversalRecursive(root, result, 0);
168 | return result;
169 | }
170 |
171 | /**
172 | * Helper method to perform an in-order traversal of the binary tree and populate the sorted elements in an array.
173 | *
174 | * @param current the current node being considered
175 | * @param result the array to store the sorted elements
176 | * @param index the current index in the result array
177 | * @return the updated index
178 | */
179 | private int inOrderTraversalRecursive(Node current, T[] result, int index) {
180 | if (current != null) {
181 | index = inOrderTraversalRecursive(current.left, result, index);
182 | result[index++] = current.data;
183 | index = inOrderTraversalRecursive(current.right, result, index);
184 | }
185 | return index;
186 | }
187 |
188 | /**
189 | * Returns the number of nodes in the binary tree.
190 | *
191 | * @return the number of nodes
192 | */
193 | public int size() {
194 | return sizeRecursive(root);
195 | }
196 |
197 | /**
198 | * Helper method to recursively calculate the number of nodes in the binary tree.
199 | *
200 | * @param current the current node being considered
201 | * @return the number of nodes in the tree
202 | */
203 | private int sizeRecursive(Node current) {
204 | if (current == null) {
205 | return 0;
206 | }
207 | return 1 + sizeRecursive(current.left) + sizeRecursive(current.right);
208 | }
209 |
210 | /**
211 | * Clears all nodes from the binary tree, making it empty.
212 | */
213 | public void clear() {
214 | root = null;
215 | }
216 |
217 | public static void main(String[] args) {
218 | // Create a CustomBinaryTree of integers
219 | CustomBinaryTree customBinaryTree = new CustomBinaryTree<>();
220 |
221 | // Insert elements into the tree
222 | customBinaryTree.insert(5);
223 | customBinaryTree.insert(2);
224 | customBinaryTree.insert(8);
225 | customBinaryTree.insert(1);
226 | customBinaryTree.insert(3);
227 |
228 | System.out.println("In-Order Traversal: " + Arrays.toString(customBinaryTree.inOrderTraversal()));
229 |
230 | // Search for elements in the tree
231 | System.out.println("Search for 2: " + customBinaryTree.search(2));
232 | System.out.println("Search for 6: " + customBinaryTree.search(6));
233 |
234 | // Delete an element from the tree
235 | customBinaryTree.delete(2);
236 | System.out.println("After deleting 2: " + Arrays.toString(customBinaryTree.inOrderTraversal()));
237 |
238 | System.out.println("Size of the tree: " + customBinaryTree.size());
239 |
240 | // Clear the tree
241 | customBinaryTree.clear();
242 | System.out.println("Is the tree empty? " + (customBinaryTree.size() == 0));
243 | }
244 | }
245 |
--------------------------------------------------------------------------------
/16_FirstContribution/Data Structures/CustomCircularQueue.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | /**
4 | * CustomCircularQueue is a simple implementation of a circular queue in Java.
5 | * It supports basic queue operations such as enqueue, dequeue, and checking if the queue is empty or full.
6 | */
7 | public class CustomCircularQueue {
8 | private final Object[] queue;
9 | private int front; // Front of the queue
10 | private int rear; // Rear of the queue
11 | private int size; // Current size of the queue
12 | private final int capacity; // Maximum capacity of the queue
13 |
14 | /**
15 | * Constructs a circular queue with a specified capacity.
16 | *
17 | * @param capacity the maximum capacity of the circular queue
18 | */
19 | public CustomCircularQueue(int capacity) {
20 | this.capacity = capacity;
21 | this.queue = new Object[capacity];
22 | this.front = this.rear = -1;
23 | this.size = 0;
24 | }
25 |
26 | /**
27 | * Adds an element to the rear of the circular queue.
28 | *
29 | * @param element the element to enqueue
30 | * @return true if the element was enqueued, false if the queue is full
31 | */
32 | public boolean enqueue(T element) {
33 | if (isFull()) {
34 | return false; // Queue is full
35 | }
36 | if (isEmpty()) {
37 | front = 0;
38 | }
39 | rear = (rear + 1) % capacity;
40 | queue[rear] = element;
41 | size++;
42 | return true;
43 | }
44 |
45 | /**
46 | * Removes and returns the element from the front of the circular queue.
47 | *
48 | * @return the element dequeued, or null if the queue is empty
49 | */
50 | public T dequeue() {
51 | if (isEmpty()) {
52 | return null; // Queue is empty
53 | }
54 | T element = (T) queue[front];
55 | if (front == rear) {
56 | front = rear = -1;
57 | } else {
58 | front = (front + 1) % capacity;
59 | }
60 | size--;
61 | return element;
62 | }
63 |
64 | /**
65 | * Checks if the circular queue is empty.
66 | *
67 | * @return true if the queue is empty, false if it contains elements
68 | */
69 | public boolean isEmpty() {
70 | return size == 0;
71 | }
72 |
73 | /**
74 | * Checks if the circular queue is full.
75 | *
76 | * @return true if the queue is full, false if it has room for more elements
77 | */
78 | public boolean isFull() {
79 | return size == capacity;
80 | }
81 |
82 | /**
83 | * Returns the current size of the circular queue.
84 | *
85 | * @return the size of the queue
86 | */
87 | public int size() {
88 | return size;
89 | }
90 |
91 | /**
92 | * Returns the elements in the circular queue as an array.
93 | *
94 | * @return an array containing the elements in the queue
95 | */
96 | public Object[] toArray() {
97 | Object[] result = new Object[size];
98 | if (isEmpty()) {
99 | return result;
100 | }
101 | int index = 0;
102 | for (int i = front; i != rear; i = (i + 1) % capacity) {
103 | result[index++] = queue[i];
104 | }
105 | result[index] = queue[rear];
106 | return result;
107 | }
108 |
109 | /**
110 | * Clears all elements from the circular queue, making it empty.
111 | */
112 | public void clear() {
113 | front = rear = -1;
114 | size = 0;
115 | }
116 |
117 | @Override
118 | public String toString() {
119 | return Arrays.toString(toArray());
120 | }
121 |
122 | public static void main(String[] args) {
123 | // Create a CustomCircularQueue of integers with a capacity of 5
124 | CustomCircularQueue circularQueue = new CustomCircularQueue<>(5);
125 |
126 | // Enqueue elements
127 | circularQueue.enqueue(1);
128 | circularQueue.enqueue(2);
129 | circularQueue.enqueue(3);
130 |
131 | System.out.println("Queue: " + circularQueue);
132 |
133 | // Dequeue elements
134 | Integer dequeued = circularQueue.dequeue();
135 | System.out.println("Dequeued: " + dequeued);
136 |
137 | System.out.println("Updated Queue: " + circularQueue);
138 | System.out.println("Is the queue empty? " + circularQueue.isEmpty());
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/16_FirstContribution/Data Structures/CustomDeque.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | /**
4 | * CustomDeque is a simple implementation of a double-ended queue (Deque) data structure in Java.
5 | *
6 | * @param the type of elements to be stored in the Deque
7 | */
8 | public class CustomDeque {
9 | private final Object[] deque; // Array to store elements
10 | private int front; // Front of the Deque
11 | private int rear; // Rear of the Deque
12 | private int size; // Current size of the Deque
13 | private final int capacity; // Maximum capacity of the Deque
14 |
15 | /**
16 | * Constructs a CustomDeque with the specified initial capacity.
17 | *
18 | * @param capacity the initial capacity of the Deque
19 | */
20 | public CustomDeque(int capacity) {
21 | this.capacity = capacity;
22 | deque = new Object[capacity];
23 | front = rear = -1;
24 | size = 0;
25 | }
26 |
27 | /**
28 | * Adds an element to the front of the Deque.
29 | *
30 | * @param element the element to add to the front
31 | * @return true if the element was added, false if the Deque is full
32 | */
33 | public boolean addToFront(T element) {
34 | if (isFull()) {
35 | return false; // Deque is full
36 | }
37 | if (isEmpty()) {
38 | front = rear = 0;
39 | } else if (front == 0) {
40 | front = capacity - 1;
41 | } else {
42 | front--;
43 | }
44 | deque[front] = element;
45 | size++;
46 | return true;
47 | }
48 |
49 | /**
50 | * Adds an element to the rear of the Deque.
51 | *
52 | * @param element the element to add to the rear
53 | * @return true if the element was added, false if the Deque is full
54 | */
55 | public boolean addToRear(T element) {
56 | if (isFull()) {
57 | return false; // Deque is full
58 | }
59 | if (isEmpty()) {
60 | front = rear = 0;
61 | } else if (rear == capacity - 1) {
62 | rear = 0;
63 | } else {
64 | rear++;
65 | }
66 | deque[rear] = element;
67 | size++;
68 | return true;
69 | }
70 |
71 | /**
72 | * Removes and returns the element from the front of the Deque.
73 | *
74 | * @return the element removed from the front, or null if the Deque is empty
75 | */
76 | public T removeFromFront() {
77 | if (isEmpty()) {
78 | return null; // Deque is empty
79 | }
80 | T element = (T) deque[front];
81 | if (front == rear) {
82 | front = rear = -1;
83 | } else if (front == capacity - 1) {
84 | front = 0;
85 | } else {
86 | front++;
87 | }
88 | size--;
89 | return element;
90 | }
91 |
92 | /**
93 | * Removes and returns the element from the rear of the Deque.
94 | *
95 | * @return the element removed from the rear, or null if the Deque is empty
96 | */
97 | public T removeFromRear() {
98 | if (isEmpty()) {
99 | return null; // Deque is empty
100 | }
101 | T element = (T) deque[rear];
102 | if (front == rear) {
103 | front = rear = -1;
104 | } else if (rear == 0) {
105 | rear = capacity - 1;
106 | } else {
107 | rear--;
108 | }
109 | size--;
110 | return element;
111 | }
112 |
113 | /**
114 | * Checks if the Deque is empty.
115 | *
116 | * @return true if the Deque is empty, false if it contains elements
117 | */
118 | public boolean isEmpty() {
119 | return size == 0;
120 | }
121 |
122 | /**
123 | * Checks if the Deque is full.
124 | *
125 | * @return true if the Deque is full, false if it has room for more elements
126 | */
127 | public boolean isFull() {
128 | return size == capacity;
129 | }
130 |
131 | /**
132 | * Returns the current size of the Deque.
133 | *
134 | * @return the size of the Deque
135 | */
136 | public int size() {
137 | return size;
138 | }
139 |
140 | /**
141 | * Returns the elements in the Deque as an array.
142 | *
143 | * @return an array containing the elements in the Deque
144 | */
145 | public Object[] toArray() {
146 | Object[] result = new Object[size];
147 | if (isEmpty()) {
148 | return result;
149 | }
150 | int index = 0;
151 | for (int i = front; index < size; i = (i + 1) % capacity) {
152 | result[index] = deque[i];
153 | index++;
154 | }
155 | return result;
156 | }
157 |
158 | /**
159 | * Clears all elements from the Deque, making it empty.
160 | */
161 | public void clear() {
162 | front = rear = -1;
163 | size = 0;
164 | }
165 |
166 | @Override
167 | public String toString() {
168 | return Arrays.toString(toArray());
169 | }
170 |
171 | public static void main(String[] args) {
172 | // Create a CustomDeque of integers with a capacity of 5
173 | CustomDeque customDeque = new CustomDeque<>(5);
174 |
175 | // Add elements to the front and rear of the Deque
176 | customDeque.addToFront(1);
177 | customDeque.addToFront(2);
178 | customDeque.addToRear(3);
179 |
180 | System.out.println("Deque: " + customDeque);
181 |
182 | // Remove elements from the front and rear
183 | Integer removedFront = customDeque.removeFromFront();
184 | Integer removedRear = customDeque.removeFromRear();
185 | System.out.println("Removed from front: " + removedFront);
186 | System.out.println("Removed from rear: " + removedRear);
187 |
188 | System.out.println("Updated Deque: " + customDeque);
189 | System.out.println("Is the Deque empty? " + customDeque.isEmpty());
190 | }
191 | }
192 |
--------------------------------------------------------------------------------
/16_FirstContribution/Data Structures/CustomLinearQueue.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | /**
4 | * CustomLinearQueue is a simple implementation of a linear queue (FIFO) data structure in Java.
5 | */
6 | public class CustomLinearQueue {
7 | private final Object[] queue; // Array to store elements
8 | private int front; // Front of the queue
9 | private int rear; // Rear of the queue
10 | private int size; // Current size of the queue
11 | private final int capacity; // Maximum capacity of the queue
12 |
13 | /**
14 | * Constructs a CustomLinearQueue with the specified initial capacity.
15 | *
16 | * @param capacity the initial capacity of the queue
17 | */
18 | public CustomLinearQueue(int capacity) {
19 | this.capacity = capacity;
20 | queue = new Object[capacity];
21 | front = rear = -1;
22 | size = 0;
23 | }
24 |
25 | /**
26 | * Adds an element to the rear of the queue.
27 | *
28 | * @param element the element to enqueue
29 | * @return true if the element was enqueued, false if the queue is full
30 | */
31 | public boolean enqueue(T element) {
32 | if (isFull()) {
33 | return false; // Queue is full
34 | }
35 | if (isEmpty()) {
36 | front = 0;
37 | }
38 | rear++;
39 | queue[rear] = element;
40 | size++;
41 | return true;
42 | }
43 |
44 | /**
45 | * Removes and returns the element from the front of the queue.
46 | *
47 | * @return the element dequeued, or null if the queue is empty
48 | */
49 | public T dequeue() {
50 | if (isEmpty()) {
51 | return null; // Queue is empty
52 | }
53 | T element = (T) queue[front];
54 | if (front == rear) {
55 | front = rear = -1;
56 | } else {
57 | front++;
58 | }
59 | size--;
60 | return element;
61 | }
62 |
63 | /**
64 | * Checks if the queue is empty.
65 | *
66 | * @return true if the queue is empty, false if it contains elements
67 | */
68 | public boolean isEmpty() {
69 | return size == 0;
70 | }
71 |
72 | /**
73 | * Checks if the queue is full.
74 | *
75 | * @return true if the queue is full, false if it has room for more elements
76 | */
77 | public boolean isFull() {
78 | return size == capacity;
79 | }
80 |
81 | /**
82 | * Returns the current size of the queue.
83 | *
84 | * @return the size of the queue
85 | */
86 | public int size() {
87 | return size;
88 | }
89 |
90 | /**
91 | * Returns the elements in the queue as an array.
92 | *
93 | * @return an array containing the elements in the queue
94 | */
95 | public Object[] toArray() {
96 | Object[] result = new Object[size];
97 | if (isEmpty()) {
98 | return result;
99 | }
100 | for (int i = 0; i < size; i++) {
101 | result[i] = queue[front + i];
102 | }
103 | return result;
104 | }
105 |
106 | /**
107 | * Clears all elements from the queue, making it empty.
108 | */
109 | public void clear() {
110 | front = rear = -1;
111 | size = 0;
112 | }
113 |
114 | @Override
115 | public String toString() {
116 | return Arrays.toString(toArray());
117 | }
118 |
119 | public static void main(String[] args) {
120 | // Create a CustomLinearQueue of integers with a capacity of 5
121 | CustomLinearQueue linearQueue = new CustomLinearQueue<>(5);
122 |
123 | // Enqueue elements
124 | linearQueue.enqueue(1);
125 | linearQueue.enqueue(2);
126 | linearQueue.enqueue(3);
127 |
128 | System.out.println("Queue: " + linearQueue);
129 |
130 | // Dequeue elements
131 | Integer dequeued = linearQueue.dequeue();
132 | System.out.println("Dequeued: " + dequeued);
133 |
134 | System.out.println("Updated Queue: " + linearQueue);
135 | System.out.println("Is the queue empty? " + linearQueue.isEmpty());
136 | }
137 | }
--------------------------------------------------------------------------------
/16_FirstContribution/Data Structures/CustomLinkedList.java:
--------------------------------------------------------------------------------
1 | public class CustomLinkedList {
2 |
3 | private Node head;
4 | private int size;
5 |
6 | public CustomLinkedList() {
7 | head = null;
8 | size = 0;
9 | }
10 |
11 | public void add(T element) {
12 | Node newNode = new Node<>(element);
13 |
14 | if (head == null) {
15 | head = newNode;
16 | } else {
17 | Node currentNode = head;
18 | while (currentNode.next != null) {
19 | currentNode = currentNode.next;
20 | }
21 | currentNode.next = newNode;
22 | }
23 | size++;
24 | }
25 |
26 | public void addFirst(T element) {
27 | Node newNode = new Node<>(element);
28 | newNode.next = head;
29 | head = newNode;
30 | size++;
31 | }
32 |
33 | public void addLast(T element) {
34 | Node newNode = new Node<>(element);
35 |
36 | if (head == null) {
37 | head = newNode;
38 | } else {
39 | Node currentNode = head;
40 | while (currentNode.next != null) {
41 | currentNode = currentNode.next;
42 | }
43 | currentNode.next = newNode;
44 | }
45 | size++;
46 | }
47 |
48 | public T removeFirst() {
49 | if (head == null) {
50 | return null;
51 | }
52 |
53 | T element = head.data;
54 | head = head.next;
55 | size--;
56 |
57 | return element;
58 | }
59 |
60 | public T removeLast() {
61 | if (head == null) {
62 | return null;
63 | }
64 |
65 | if (head.next == null) {
66 | T element = head.data;
67 | head = null;
68 | size--;
69 | return element;
70 | }
71 |
72 | Node currentNode = head;
73 | while (currentNode.next.next != null) {
74 | currentNode = currentNode.next;
75 | }
76 |
77 | T element = currentNode.next.data;
78 | currentNode.next = null;
79 | size--;
80 |
81 | return element;
82 | }
83 |
84 | public T remove(int index) {
85 | if (index < 0 || index >= size) {
86 | return null;
87 | }
88 |
89 | if (index == 0) {
90 | return removeFirst();
91 | }
92 |
93 | Node currentNode = head;
94 | for (int i = 0; i < index - 1; i++) {
95 | currentNode = currentNode.next;
96 | }
97 |
98 | T element = currentNode.next.data;
99 | currentNode.next = currentNode.next.next;
100 | size--;
101 |
102 | return element;
103 | }
104 |
105 | public int size() {
106 | return size;
107 | }
108 |
109 | public void display() {
110 | Node currentNode = head;
111 | while (currentNode != null) {
112 | System.out.print(currentNode.data + " ");
113 | currentNode = currentNode.next;
114 | }
115 | System.out.println();
116 | }
117 |
118 | private static class Node {
119 | private T data;
120 | private Node next;
121 |
122 | public Node(T data) {
123 | this.data = data;
124 | next = null;
125 | }
126 | }
127 |
128 | public static void main(String[] args) {
129 | CustomLinkedList list = new CustomLinkedList<>();
130 |
131 | // Test adding elements
132 | list.add(1);
133 | list.add(2);
134 | list.add(3);
135 |
136 | System.out.println("Expected: 1 2 3");
137 | System.out.print("Actual: ");
138 | list.display();
139 | System.out.println();
140 |
141 | // Test adding elements at the beginning
142 | list.addFirst(0);
143 | System.out.println("Expected: 0 1 2 3");
144 | System.out.print("Actual: ");
145 | list.display();
146 | System.out.println();
147 |
148 | // Test adding elements at the end
149 | list.addLast(4);
150 | System.out.println("Expected: 0 1 2 3 4");
151 | System.out.print("Actual: ");
152 | list.display();
153 | System.out.println();
154 |
155 | // Test removing elements
156 | int removed = list.removeFirst();
157 | System.out.println("Expected: Removed: 0");
158 | System.out.println("Actual: Removed: " + removed);
159 | System.out.println("Expected: 1 2 3 4");
160 | System.out.print("Actual: ");
161 | list.display();
162 | System.out.println();
163 |
164 | removed = list.removeLast();
165 | System.out.println("Expected: Removed: 4");
166 | System.out.println("Actual: Removed: " + removed);
167 | System.out.println("Expected: 1 2 3");
168 | System.out.print("Actual: ");
169 | list.display();
170 | System.out.println();
171 |
172 | // Test removing elements by index
173 | removed = list.remove(1);
174 | System.out.println("Expected: Removed: 2");
175 | System.out.println("Actual: Removed: " + removed);
176 | System.out.println("Expected: 1 3");
177 | System.out.print("Actual: ");
178 | list.display();
179 | System.out.println();
180 |
181 | // Test removing elements by invalid index
182 | removed = list.remove(3);
183 | System.out.println("Expected: Removed: null (Invalid index)");
184 | System.out.println("Actual: Removed: " + removed);
185 | }
186 | }
187 |
188 |
--------------------------------------------------------------------------------
/16_FirstContribution/Data Structures/CustomMap.java:
--------------------------------------------------------------------------------
1 | /**
2 | * CustomMap is a simple implementation of a map (key-value pairs) data structure in Java.
3 | */
4 | public class CustomMap {
5 | private static final int DEFAULT_CAPACITY = 16; // Default initial capacity
6 | private final Entry[] table; // Array of key-value pairs
7 | private int size; // Current number of key-value pairs
8 |
9 | /**
10 | * An entry in the map containing a key and a value.
11 | */
12 | static class Entry {
13 | K key;
14 | V value;
15 | Entry next; // For handling collisions
16 |
17 | Entry(K key, V value) {
18 | this.key = key;
19 | this.value = value;
20 | }
21 | }
22 |
23 | /**
24 | * Constructs a CustomMap with the default initial capacity.
25 | */
26 | public CustomMap() {
27 | this(DEFAULT_CAPACITY);
28 | }
29 |
30 | /**
31 | * Constructs a CustomMap with a specified initial capacity.
32 | *
33 | * @param initialCapacity the initial capacity of the map
34 | */
35 | public CustomMap(int initialCapacity) {
36 | table = new Entry[initialCapacity];
37 | size = 0;
38 | }
39 |
40 | /**
41 | * Associates the specified value with the specified key in the map.
42 | *
43 | * @param key the key to associate with the value
44 | * @param value the value to be associated with the key
45 | */
46 | public void put(K key, V value) {
47 | int index = key.hashCode() % table.length;
48 |
49 | Entry newEntry = new Entry<>(key, value);
50 | if (table[index] == null) {
51 | table[index] = newEntry;
52 | } else {
53 | // Handle collisions by adding to the linked list at the same index
54 | Entry current = table[index];
55 | while (current.next != null) {
56 | if (current.key.equals(key)) {
57 | current.value = value; // Update the value for an existing key
58 | return;
59 | }
60 | current = current.next;
61 | }
62 | current.next = newEntry;
63 | }
64 | size++;
65 | }
66 |
67 | /**
68 | * Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
69 | *
70 | * @param key the key whose associated value is to be returned
71 | * @return the value to which the specified key is mapped, or null if the key is not found
72 | */
73 | public V get(K key) {
74 | int index = key.hashCode() % table.length;
75 | Entry entry = table[index];
76 |
77 | while (entry != null) {
78 | if (entry.key.equals(key)) {
79 | return entry.value;
80 | }
81 | entry = entry.next;
82 | }
83 | return null; // Key not found
84 | }
85 |
86 | /**
87 | * Removes the mapping for the specified key from this map if present.
88 | *
89 | * @param key the key whose mapping is to be removed from the map
90 | */
91 | public void remove(K key) {
92 | int index = key.hashCode() % table.length;
93 | Entry current = table[index];
94 | Entry previous = null;
95 |
96 | while (current != null) {
97 | if (current.key.equals(key)) {
98 | if (previous != null) {
99 | previous.next = current.next;
100 | } else {
101 | table[index] = current.next;
102 | }
103 | size--;
104 | return;
105 | }
106 | previous = current;
107 | current = current.next;
108 | }
109 | }
110 |
111 | /**
112 | * Returns the number of key-value mappings in this map.
113 | *
114 | * @return the number of key-value mappings in this map
115 | */
116 | public int size() {
117 | return size;
118 | }
119 |
120 | /**
121 | * Checks if the map is empty.
122 | *
123 | * @return true if the map is empty, false otherwise
124 | */
125 | public boolean isEmpty() {
126 | return size == 0;
127 | }
128 |
129 | /**
130 | * Clears all key-value mappings from the map, making it empty.
131 | */
132 | public void clear() {
133 | for (int i = 0; i < table.length; i++) {
134 | table[i] = null;
135 | }
136 | size = 0;
137 | }
138 |
139 | @Override
140 | public String toString() {
141 | StringBuilder sb = new StringBuilder();
142 | sb.append("{ ");
143 | for (Entry entry : table) {
144 | while (entry != null) {
145 | sb.append(entry.key).append("=").append(entry.value).append(", ");
146 | entry = entry.next;
147 | }
148 | }
149 | if (sb.length() > 2) {
150 | sb.setLength(sb.length() - 2); // Remove the trailing ", "
151 | }
152 | sb.append(" }");
153 | return sb.toString();
154 | }
155 |
156 | public static void main(String[] args) {
157 | CustomMap customMap = new CustomMap<>();
158 |
159 | customMap.put("one", 1);
160 | customMap.put("two", 2);
161 | customMap.put("three", 3);
162 |
163 | System.out.println("Map: " + customMap);
164 | System.out.println("Size: " + customMap.size());
165 |
166 | customMap.remove("two");
167 | System.out.println("Map after removing 'two': " + customMap);
168 | System.out.println("Is the map empty? " + customMap.isEmpty());
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/16_FirstContribution/Data Structures/CustomSet.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | /**
5 | * CustomSet is a simple implementation of a Set data structure in Java.
6 | * It stores a collection of unique elements without duplicates and provides basic Set operations.
7 | */
8 | public class CustomSet {
9 | private final List elements;
10 |
11 | /**
12 | * Constructs an empty CustomSet.
13 | */
14 | public CustomSet() {
15 | elements = new ArrayList<>();
16 | }
17 |
18 | /**
19 | * Adds an element to the set if it is not already present.
20 | *
21 | * @param element the element to add
22 | * @return true if the element was added, false if it was already in the set
23 | */
24 | public boolean add(T element) {
25 | if (!contains(element)) {
26 | elements.add(element);
27 | return true;
28 | }
29 | return false;
30 | }
31 |
32 | /**
33 | * Removes an element from the set if it exists.
34 | *
35 | * @param element the element to remove
36 | * @return true if the element was removed, false if it was not in the set
37 | */
38 | public boolean remove(T element) {
39 | return elements.remove(element);
40 | }
41 |
42 | /**
43 | * Checks if the set contains a specific element.
44 | *
45 | * @param element the element to check for
46 | * @return true if the element is in the set, false otherwise
47 | */
48 | public boolean contains(T element) {
49 | return elements.contains(element);
50 | }
51 |
52 | /**
53 | * Returns the size (number of elements) of the set.
54 | *
55 | * @return the size of the set
56 | */
57 | public int size() {
58 | return elements.size();
59 | }
60 |
61 | /**
62 | * Checks if the set is empty.
63 | *
64 | * @return true if the set is empty, false if it contains elements
65 | */
66 | public boolean isEmpty() {
67 | return elements.isEmpty();
68 | }
69 |
70 | /**
71 | * Returns the elements in the set as a List.
72 | *
73 | * @return a List of elements in the set
74 | */
75 | public List toList() {
76 | return elements;
77 | }
78 |
79 | /**
80 | * Clears all elements from the set, making it empty.
81 | */
82 | public void clear() {
83 | elements.clear();
84 | }
85 |
86 | @Override
87 | public String toString() {
88 | return elements.toString();
89 | }
90 |
91 | public static void main(String[] args) {
92 | // Create a CustomSet of integers
93 | CustomSet intSet = new CustomSet<>();
94 |
95 | // Add elements to the set
96 | intSet.add(5);
97 | intSet.add(10);
98 | intSet.add(5); // Adding a duplicate element
99 |
100 | System.out.println("Set: " + intSet);
101 | System.out.println("Size: " + intSet.size());
102 |
103 | // Remove an element
104 | intSet.remove(10);
105 |
106 | System.out.println("Set after removing 10: " + intSet);
107 | System.out.println("Is the set empty? " + intSet.isEmpty());
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/16_FirstContribution/Data Structures/CustomStack.java:
--------------------------------------------------------------------------------
1 | /**
2 | * CustomStack is a simple implementation of a stack (Last-In, First-Out - LIFO) data structure in Java.
3 | */
4 | public class CustomStack {
5 | private final Object[] stack; // Array to store elements
6 | private int top; // Index of the top element
7 | private final int capacity; // Maximum capacity of the stack
8 |
9 | /**
10 | * Constructs a CustomStack with the specified initial capacity.
11 | *
12 | * @param capacity the initial capacity of the stack
13 | */
14 | public CustomStack(int capacity) {
15 | this.capacity = capacity;
16 | stack = new Object[capacity];
17 | top = -1;
18 | }
19 |
20 | /**
21 | * Pushes an element onto the stack.
22 | *
23 | * @param element the element to push
24 | */
25 | public void push(T element) {
26 | if (isFull()) {
27 | return; // Stack is full
28 | }
29 | top++;
30 | stack[top] = element;
31 | }
32 |
33 | /**
34 | * Pops and returns the top element from the stack.
35 | *
36 | * @return the top element, or null if the stack is empty
37 | */
38 | public T pop() {
39 | if (isEmpty()) {
40 | return null; // Stack is empty
41 | }
42 | T element = (T) stack[top];
43 | top--;
44 | return element;
45 | }
46 |
47 | /**
48 | * Retrieves the top element from the stack without removing it.
49 | *
50 | * @return the top element, or null if the stack is empty
51 | */
52 | public T peek() {
53 | if (isEmpty()) {
54 | return null; // Stack is empty
55 | }
56 | return (T) stack[top];
57 | }
58 |
59 | /**
60 | * Checks if the stack is empty.
61 | *
62 | * @return true if the stack is empty, false if it contains elements
63 | */
64 | public boolean isEmpty() {
65 | return top == -1;
66 | }
67 |
68 | /**
69 | * Checks if the stack is full.
70 | *
71 | * @return true if the stack is full, false if it has room for more elements
72 | */
73 | public boolean isFull() {
74 | return top == capacity - 1;
75 | }
76 |
77 | /**
78 | * Returns the current size of the stack.
79 | *
80 | * @return the size of the stack
81 | */
82 | public int size() {
83 | return top + 1;
84 | }
85 |
86 | /**
87 | * Clears all elements from the stack, making it empty.
88 | */
89 | public void clear() {
90 | top = -1;
91 | }
92 |
93 | @Override
94 | public String toString() {
95 | StringBuilder sb = new StringBuilder();
96 | sb.append("[ ");
97 | for (int i = 0; i <= top; i++) {
98 | sb.append(stack[i]);
99 | if (i < top) {
100 | sb.append(", ");
101 | }
102 | }
103 | sb.append(" ]");
104 | return sb.toString();
105 | }
106 |
107 | public static void main(String[] args) {
108 | // Create a CustomStack of integers with a capacity of 5
109 | CustomStack customStack = new CustomStack<>(5);
110 |
111 | // Push elements onto the stack
112 | customStack.push(1);
113 | customStack.push(2);
114 | customStack.push(3);
115 |
116 | System.out.println("Stack: " + customStack);
117 |
118 | // Pop elements
119 | Integer popped = customStack.pop();
120 | System.out.println("Popped: " + popped);
121 |
122 | System.out.println("Updated Stack: " + customStack);
123 | System.out.println("Is the stack empty? " + customStack.isEmpty());
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/16_FirstContribution/Dijkstra's algorithm/Dijkstra.java:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * This class implements Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a graph.
4 | * The graph is represented as a 2D array of integers, where -1 represents no edge between two nodes.
5 | * The class contains methods to find the minimum distance from the source node to a given node, print the shortest distances from the source node to all other nodes,
6 | * and run the Dijkstra's algorithm on the graph to find the shortest distances.
7 | */
8 | import java.util.*;
9 |
10 | public class Dijkstra {
11 | static final int totalVertices = 9;
12 |
13 | /**
14 | * Find the vertex with the minimum distance value from the set of vertices not yet included
15 | * in the shortest path tree.
16 | *
17 | * @param distances An array of distances from the source node to all other nodes.
18 | * @param shortestPathSet An array to track whether a node is included in the shortest path.
19 | * @return The index of the vertex with the minimum distance.
20 | */
21 | int findMinimumDistance(int distances[], Boolean shortestPathSet[]) {
22 | int minDistance = Integer.MAX_VALUE;
23 | int minIndex = -1;
24 |
25 | // Loop through all vertices to find the one with the minimum distance.
26 | for (int vertex = 0; vertex < totalVertices; vertex++) {
27 | // Check if the vertex is not yet included in the shortest path set
28 | // and its distance is less than or equal to the current minimum distance.
29 | if (!shortestPathSet[vertex] && distances[vertex] <= minDistance) {
30 | minDistance = distances[vertex];
31 | minIndex = vertex;
32 | }
33 | }
34 | return minIndex;
35 | }
36 |
37 | /**
38 | * Print the shortest distances from the source node to all other nodes.
39 | *
40 | * @param distances An array of distances from the source node to all other nodes.
41 | * @param n The total number of nodes.
42 | */
43 | void printShortestDistances(int distances[], int n) {
44 | System.out.println("The shortest distances from source node 0 to all other nodes are: ");
45 | for (int node = 0; node < n; node++)
46 | System.out.println("To Node " + node + ", the shortest distance is: " + distances[node]);
47 | }
48 |
49 | /**
50 | * Compute the shortest paths from a source node to all other nodes in the given graph
51 | * using Dijkstra's algorithm.
52 | *
53 | * @param graph The adjacency matrix representing the graph.
54 | * @param sourceNode The source node from which to find the shortest paths.
55 | */
56 | void dijkstra(int graph[][], int sourceNode) {
57 | int distances[] = new int[totalVertices];
58 | Boolean shortestPathSet[] = new Boolean[totalVertices];
59 |
60 | // Initialize distances and shortestPathSet arrays.
61 | for (int node = 0; node < totalVertices; node++) {
62 | distances[node] = Integer.MAX_VALUE;
63 | shortestPathSet[node] = false;
64 | }
65 |
66 | distances[sourceNode] = 0; // Distance from source to itself is always 0.
67 |
68 | // Find the shortest paths for all vertices.
69 | for (int count = 0; count < totalVertices - 1; count++) {
70 | int u = findMinimumDistance(distances, shortestPathSet);
71 | shortestPathSet[u] = true;
72 |
73 | // Update distances for adjacent vertices if a shorter path is found.
74 | for (int v = 0; v < totalVertices; v++) {
75 | if (!shortestPathSet[v] && graph[u][v] != -1 && distances[u] != Integer.MAX_VALUE
76 | && distances[u] + graph[u][v] < distances[v]) {
77 | distances[v] = distances[u] + graph[u][v];
78 | }
79 | }
80 | }
81 |
82 | // Print the shortest distances to all nodes.
83 | printShortestDistances(distances, totalVertices);
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/16_FirstContribution/Dijkstra's algorithm/DijkstraTest.java:
--------------------------------------------------------------------------------
1 | // An example to test the build dijkstra algorithm taken from JavTpoint
2 |
3 | public class DijkstraTest {
4 | public static void main(String[] args) {
5 | int graph[][] = new int[][] { { -1, 3, -1, -1, -1, -1, -1, 7, -1 },
6 | { 3, -1, 7, -1, -1, -1, -1, 10, 4 },
7 | { -1, 7, -1, 6, -1, 2, -1, -1, 1 },
8 | { -1, -1, 6, -1, 8, 13, -1, -1, 3 },
9 | { -1, -1, -1, 8, -1, 9, -1, -1, -1 },
10 | { -1, -1, 2, 13, 9, -1, 4, -1, 5 },
11 | { -1, -1, -1, -1, -1, 4, -1, 2, 5 },
12 | { 7, 10, -1, -1, -1, -1, 2, -1, 6 },
13 | { -1, 4, 1, 3, -1, 5, 5, 6, -1 } };
14 |
15 | Dijkstra obj = new Dijkstra();
16 | obj.dijkstra(graph, 0);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/16_FirstContribution/Dijkstra's algorithm/Explanation.md:
--------------------------------------------------------------------------------
1 | ## **Current Example**
2 | ### source : JavaTpoint
3 |
4 | 
5 |
6 |
7 | # Dijkstra's Algorithm
8 |
9 | ## Overview
10 |
11 | Dijkstra's algorithm is a graph search algorithm that finds the shortest path between a designated starting node (or source) and all other nodes in a weighted graph. It operates in a greedy manner, continually selecting the node with the smallest tentative distance from the source and expanding outward.
12 |
13 | ## Key Steps
14 |
15 | 1. **Initialization**: Initialize an array to store the distances from the source to all other nodes. Initially, set the distance to the source as 0 and all other distances as infinity.
16 |
17 | 2. **Selection**: Repeatedly select the unvisited node with the smallest distance from the source. Initially, this will be the source node itself.
18 |
19 | 3. **Relaxation**: For the selected node, consider all of its unvisited neighbors. Calculate their tentative distances through the current node and update their distances if a shorter path is found.
20 |
21 | 4. **Marking Visited**: Once all neighbors have been considered, mark the selected node as visited to ensure it is not selected again.
22 |
23 | 5. **Termination**: Repeat steps 2 to 4 until all nodes have been visited or the destination node (if specified) has been reached.
24 |
25 | ## Output
26 |
27 | Dijkstra's algorithm provides the shortest distance from the source to every other node in the graph and, if needed, the shortest path itself.
28 |
29 | ## Key Properties
30 |
31 | - Dijkstra's algorithm works for graphs with non-negative edge weights.
32 | - It may not find the correct solution for graphs with negative edge weights or cycles.
33 | - It guarantees the shortest path when all edge weights are non-negative.
34 |
35 | ## Applications
36 |
37 | - Routing algorithms in computer networks and GPS navigation systems.
38 | - Shortest path problems in transportation and logistics.
39 | - Network topology analysis.
40 | - Robot path planning.
41 |
42 | ## Complexity
43 |
44 | - Time Complexity: O(V^2) for the straightforward implementation with an adjacency matrix, or O((V + E) log V) using a priority queue (e.g., min-heap).
45 | - Space Complexity: O(V) for storing distances and visited nodes.
46 |
--------------------------------------------------------------------------------
/16_FirstContribution/FibonacciSequenceGenerator.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class FibonacciSequenceGenerator {
4 | public static void generateFibonacci(int n) {
5 | long[] fibonacci = new long[n];
6 |
7 | if (n >= 1) {
8 | fibonacci[0] = 0;
9 | }
10 | if (n >= 2) {
11 | fibonacci[1] = 1;
12 | }
13 |
14 | for (int i = 2; i < n; i++) {
15 | fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
16 | }
17 |
18 | System.out.println("Fibonacci Sequence up to " + n + " terms:");
19 | for (int i = 0; i < n; i++) {
20 | System.out.print(fibonacci[i] + " ");
21 | }
22 | }
23 |
24 | public static void main(String[] args) {
25 | Scanner scanner = new Scanner(System.in);
26 | System.out.print("Enter a number: ");
27 | int numTerms = scanner.nextInt();
28 | scanner.close();
29 | generateFibonacci(numTerms);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/16_FirstContribution/FizzBuzz.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 |
3 | import java.util.Scanner;
4 |
5 | public class FizzBuzz{
6 |
7 | public static void main(String args[]){
8 | Scanner sc = new Scanner(System.in);
9 | System.out.print("Enter a number - ");
10 | int n = sc.nextInt();
11 | List result = fizzBuzz(n);
12 | System.out.println("Resultant String Array" + result);
13 | }
14 |
15 | private static List fizzBuzz(int n) {
16 | List list = new ArrayList();
17 | for (int i=1; i<=n; i++){
18 | if ((i%3 == 0) && (i%5 == 0))
19 | list.add("FizzBuzz");
20 | else if (i%3 == 0)
21 | list.add("Fizz");
22 | else if (i%5 == 0)
23 | list.add("Buzz");
24 | else
25 | list.add(String.valueOf(i));
26 | }
27 | return list;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/16_FirstContribution/GUI Programs/DigitalClock.java:
--------------------------------------------------------------------------------
1 | import javax.swing.*;
2 | import java.awt.*;
3 | import java.text.SimpleDateFormat;
4 | import java.util.Date;
5 |
6 | /**
7 | * DigitalClock is a simple Swing application that displays a visually appealing digital clock in a 12-hour format with AM/PM.
8 | */
9 | public class DigitalClock extends JFrame {
10 | private final JLabel clockLabel;
11 |
12 | public DigitalClock() {
13 | // Set up the JFrame
14 | setTitle("Digital Clock");
15 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16 | setSize(300, 150);
17 | setLocationRelativeTo(null);
18 | setResizable(false);
19 | setLayout(new FlowLayout(FlowLayout.CENTER, 0, 20));
20 |
21 | // Create clock label with custom styling
22 | clockLabel = new JLabel();
23 | clockLabel.setFont(new Font("Digital", Font.PLAIN, 48));
24 | clockLabel.setForeground(Color.BLUE);
25 | add(clockLabel);
26 |
27 | // Use a timer to update the clock every second
28 | Timer timer = new Timer(1000, e -> updateClock());
29 | timer.start();
30 |
31 | updateClock(); // Initial clock update
32 | }
33 |
34 | /**
35 | * Updates the clock's display with the current time in 12-hour format with AM/PM.
36 | */
37 | private void updateClock() {
38 | SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss a");
39 | String time = dateFormat.format(new Date());
40 | clockLabel.setText(time);
41 | }
42 |
43 | public static void main(String[] args) {
44 | SwingUtilities.invokeLater(() -> {
45 | DigitalClock clock = new DigitalClock();
46 | clock.setVisible(true);
47 | });
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/16_FirstContribution/GUI Programs/SwingCalculator.java:
--------------------------------------------------------------------------------
1 | import javax.swing.*;
2 | import java.awt.*;
3 | import java.awt.event.ActionEvent;
4 | import java.awt.event.ActionListener;
5 |
6 | /*
7 | * This class implements a simple calculator using Swing components.
8 | */
9 |
10 | public class SwingCalculator {
11 |
12 | private JTextField mathInput; // Input text field for mathematical expression
13 | private JTextField resultDisplay; // Text field to display the result
14 |
15 | private double firstOperand = 0; // The first operand for calculations
16 | private String operator = ""; // The operator (+, -, *, /)
17 | private boolean startNewCalculation = true; // Flag to start a new calculation
18 |
19 | public static void main(String[] args) {
20 | SwingUtilities.invokeLater(() -> new SwingCalculator().createAndShowGUI());
21 | }
22 |
23 | /**
24 | * Create and display the Swing-based calculator GUI.
25 | */
26 | private void createAndShowGUI() {
27 | JFrame frame = new JFrame("Swing Calculator");
28 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
29 | frame.setSize(300, 300);
30 |
31 | JPanel panel = new JPanel();
32 | panel.setLayout(new BorderLayout());
33 |
34 | mathInput = new JTextField();
35 | mathInput.setEditable(true);
36 | mathInput.setHorizontalAlignment(JTextField.RIGHT);
37 | panel.add(mathInput, BorderLayout.NORTH);
38 |
39 | resultDisplay = new JTextField();
40 | resultDisplay.setEditable(false);
41 | resultDisplay.setHorizontalAlignment(JTextField.RIGHT);
42 | panel.add(resultDisplay, BorderLayout.CENTER);
43 |
44 | JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
45 | String[] buttonLabels = {
46 | "7", "8", "9", "/",
47 | "4", "5", "6", "*",
48 | "1", "2", "3", "-",
49 | "0", "C", "=", "+"
50 | };
51 |
52 | for (String label : buttonLabels) {
53 | JButton button = makeButton(label);
54 | buttonPanel.add(button);
55 | }
56 | panel.add(buttonPanel, BorderLayout.SOUTH);
57 |
58 | frame.add(panel);
59 | frame.setVisible(true);
60 | }
61 |
62 | /**
63 | * Create a JButton with the given label and ActionListener.
64 | *
65 | * @param label The label to display on the button.
66 | * @return The created JButton.
67 | */
68 | private JButton makeButton(String label) {
69 | JButton button = new JButton(label);
70 | button.addActionListener(new ActionListener() {
71 | @Override
72 | public void actionPerformed(ActionEvent e) {
73 | String buttonText = button.getText();
74 |
75 | if (buttonText.matches("[0-9]")) {
76 | if (startNewCalculation) {
77 | mathInput.setText("");
78 | startNewCalculation = false;
79 | }
80 | mathInput.setText(mathInput.getText() + buttonText);
81 | } else if (buttonText.matches("[+\\-*/]")) {
82 | if (!operator.isEmpty()) {
83 | calculate();
84 | }
85 | operator = buttonText;
86 | firstOperand = Double.parseDouble(mathInput.getText());
87 | startNewCalculation = true;
88 | } else if (buttonText.equals("=")) {
89 | calculate();
90 | operator = "";
91 | } else if (buttonText.equals("C")) {
92 | mathInput.setText("");
93 | resultDisplay.setText("");
94 | firstOperand = 0;
95 | operator = "";
96 | }
97 | }
98 |
99 | /**
100 | * Perform the calculation based on the stored operator and operands.
101 | */
102 | private void calculate() {
103 | double secondOperand = Double.parseDouble(mathInput.getText());
104 | double result = 0;
105 | switch (operator) {
106 | case "+":
107 | result = firstOperand + secondOperand;
108 | break;
109 | case "-":
110 | result = firstOperand - secondOperand;
111 | break;
112 | case "*":
113 | result = firstOperand * secondOperand;
114 | break;
115 | case "/":
116 | if (secondOperand != 0) {
117 | result = firstOperand / secondOperand;
118 | } else {
119 | resultDisplay.setText("Error");
120 | }
121 | break;
122 | }
123 | resultDisplay.setText(String.valueOf(result));
124 | startNewCalculation = true;
125 | }
126 | });
127 |
128 | return button;
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/16_FirstContribution/GUI Programs/TemperatureConverter.java:
--------------------------------------------------------------------------------
1 | import javax.swing.*;
2 | import javax.swing.text.AbstractDocument;
3 | import javax.swing.text.AttributeSet;
4 | import javax.swing.text.BadLocationException;
5 | import javax.swing.text.DocumentFilter;
6 | import java.awt.*;
7 | import java.awt.event.KeyAdapter;
8 | import java.awt.event.KeyEvent;
9 | import java.text.DecimalFormat;
10 |
11 | /**
12 | * TemperatureConverter is a basic Swing application to convert temperatures between Celsius and Fahrenheit.
13 | */
14 | public class TemperatureConverter extends JFrame {
15 |
16 | private final JTextField celsiusField;
17 | private final JTextField fahrenheitField;
18 |
19 | public TemperatureConverter() {
20 | // Set up the JFrame
21 | setTitle("Temperature Converter");
22 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
23 | setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
24 |
25 | // Create Celsius label and input field
26 | JLabel celsiusLabel = new JLabel("Celsius:");
27 | celsiusField = new JTextField(10);
28 | celsiusField.setToolTipText("Enter temperature in Celsius");
29 | add(celsiusLabel);
30 | add(celsiusField);
31 |
32 | // Create Fahrenheit label and input field
33 | JLabel fahrenheitLabel = new JLabel("Fahrenheit:");
34 | fahrenheitField = new JTextField(10);
35 | fahrenheitField.setToolTipText("Enter temperature in Fahrenheit");
36 | add(fahrenheitLabel);
37 | add(fahrenheitField);
38 |
39 | // Create convert button
40 | JButton convertButton = new JButton("Convert");
41 | add(convertButton);
42 |
43 | // Add ActionListener to the convert button
44 | convertButton.addActionListener(e -> convertTemperature());
45 |
46 | // Add DocumentFilter to allow only numeric input
47 | ((AbstractDocument) celsiusField.getDocument()).setDocumentFilter(new NumericInputFilter());
48 | ((AbstractDocument) fahrenheitField.getDocument()).setDocumentFilter(new NumericInputFilter());
49 |
50 | // Add KeyListeners to clear the opposite input field when a value is changed
51 | celsiusField.addKeyListener(new KeyAdapter() {
52 | @Override
53 | public void keyTyped(KeyEvent e) {
54 | fahrenheitField.setText("");
55 | }
56 | });
57 |
58 | fahrenheitField.addKeyListener(new KeyAdapter() {
59 | @Override
60 | public void keyTyped(KeyEvent e) {
61 | celsiusField.setText("");
62 | }
63 | });
64 |
65 | pack();
66 | setLocationRelativeTo(null); // Center the JFrame
67 | }
68 |
69 | /**
70 | * Converts the temperature between Celsius and Fahrenheit and updates the input fields.
71 | */
72 | private void convertTemperature() {
73 | try {
74 | if (!celsiusField.getText().isEmpty()) {
75 | double celsius = Double.parseDouble(celsiusField.getText());
76 | double fahrenheit = (celsius * 9 / 5) + 32;
77 | DecimalFormat df = new DecimalFormat("#.##");
78 | fahrenheitField.setText(df.format(fahrenheit));
79 | } else if (!fahrenheitField.getText().isEmpty()) {
80 | double fahrenheit = Double.parseDouble(fahrenheitField.getText());
81 | double celsius = (fahrenheit - 32) * 5 / 9;
82 | DecimalFormat df = new DecimalFormat("#.##");
83 | celsiusField.setText(df.format(celsius));
84 | }
85 | } catch (NumberFormatException ex) {
86 | celsiusField.setText("");
87 | fahrenheitField.setText("");
88 | }
89 | }
90 |
91 | /**
92 | * DocumentFilter to allow only numeric input.
93 | */
94 | private static class NumericInputFilter extends DocumentFilter {
95 | String regex = "[-+]?[0-9]*\\.?[0-9]*";
96 | @Override
97 | public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
98 | if (text.matches(regex)) {
99 | super.insertString(fb, offset, text, attr);
100 | }
101 | }
102 |
103 | @Override
104 | public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
105 | if (text.matches(regex)) {
106 | super.replace(fb, offset, length, text, attrs);
107 | }
108 | }
109 | }
110 |
111 | public static void main(String[] args) {
112 | SwingUtilities.invokeLater(() -> {
113 | TemperatureConverter converter = new TemperatureConverter();
114 | converter.setVisible(true);
115 | });
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/16_FirstContribution/Games/SnakeLadder/Game.java:
--------------------------------------------------------------------------------
1 | package Games.SnakeLadder;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.List;
6 | import java.util.Map;
7 |
8 | public class Game {
9 | private List players;
10 | private Map snakePositionMapping;
11 | private Map ladderPositionMapping;
12 | public Integer turn; // shows user id whose turn was previous
13 | public Integer minPosition;
14 | public Integer maxPosition;
15 | private Game() {
16 | this.turn = -1;
17 | this.minPosition = 1;
18 | this.maxPosition = 100;
19 | }
20 |
21 | public Game playNext() {
22 | if (players.isEmpty()) return this;
23 | turn = (turn + 1)%players.size();
24 | Player player = players.get(turn);
25 | // THROW DICE
26 | System.out.println("----- " + player.getName() + "'s turn --");
27 | Integer dicePos = (int)(Math.random()*6 + 1);
28 | System.out.println("Dice rolled " + dicePos);
29 | Integer finalPosition = player.getPosition() + dicePos;
30 | if (this.ladderPositionMapping.containsKey(finalPosition)) {
31 | Integer prevPosition = finalPosition;
32 | finalPosition = Math.min(this.maxPosition, this.ladderPositionMapping.get(finalPosition).getTo());
33 | System.out.println("WoHoo!! Climbed up a ladder at position: " + prevPosition + " to position: " + finalPosition);
34 | }
35 | if (this.snakePositionMapping.containsKey(finalPosition)) {
36 | Integer prevPosition = finalPosition;
37 | finalPosition = Math.max(minPosition, this.snakePositionMapping.get(finalPosition).getTail());
38 | System.out.println("Damn, bit by a snake at position: " + prevPosition + " now will be moved to position: " + finalPosition);
39 | }
40 | player.setPosition(finalPosition);
41 | System.out.println("Final Position after turn: " + finalPosition);
42 |
43 | if (finalPosition.equals(maxPosition)) {
44 | System.out.println("WoHoo!! " + player.getName() + " Finished the game!!");
45 | this.players.remove(player);
46 | }
47 |
48 | return this;
49 | }
50 |
51 | public static class GameBuilder {
52 | private final List players;
53 | private final List snakes;
54 | private final List ladders;
55 | public GameBuilder() {
56 | this.players = new ArrayList<>();
57 | this.snakes = new ArrayList<>();
58 | this.ladders = new ArrayList<>();
59 | }
60 | public GameBuilder addPlayer(Player player) {
61 | if (player != null) {
62 | this.players.add(player);
63 | }
64 | return this;
65 | }
66 | public GameBuilder addSnake(Snake snake) {
67 | if (snake != null) {
68 | this.snakes.add(snake);
69 | }
70 | return this;
71 | }
72 |
73 | public GameBuilder addLadder(Ladder ladder) {
74 | if (ladder != null) {
75 | this.ladders.add(ladder);
76 | }
77 | return this;
78 | }
79 |
80 | public Game build() {
81 | Map laddersPositionMapping = new HashMap<>();
82 | this.ladders.stream().forEach(ladder -> {
83 | laddersPositionMapping.put(ladder.getFrom(), ladder);
84 | });
85 | Map snakePositionMapping = new HashMap<>();
86 | this.snakes.stream().forEach(snake -> {
87 | snakePositionMapping.put(snake.getFace(), snake);
88 | });
89 |
90 | Game game = new Game();
91 | // game.playerIdMapping = playerIdMapping;
92 | game.ladderPositionMapping = laddersPositionMapping;
93 | game.snakePositionMapping = snakePositionMapping;
94 | game.players = this.players;
95 | return game;
96 | }
97 | }
98 |
99 | }
100 |
--------------------------------------------------------------------------------
/16_FirstContribution/Games/SnakeLadder/Ladder.java:
--------------------------------------------------------------------------------
1 | package Games.SnakeLadder;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | public class Ladder {
7 | private static final Set ladderStartPosition = new HashSet<>();
8 | private final Integer from;
9 | private final Integer to;
10 |
11 | public Ladder(Integer from, Integer to) {
12 | if (!ladderStartPosition.contains(from)) {
13 | this.from = from;
14 | this.to = to;
15 | ladderStartPosition.add(from);
16 | } else {
17 | this.from = this.to = -1;
18 | }
19 | }
20 |
21 | public Integer getFrom() {
22 | return from;
23 | }
24 |
25 | public Integer getTo() {
26 | return to;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/16_FirstContribution/Games/SnakeLadder/Player.java:
--------------------------------------------------------------------------------
1 | package Games.SnakeLadder;
2 |
3 | public class Player {
4 | private static Integer id = 0;
5 | private Integer playerId;
6 | private String name;
7 | private Integer position;
8 | public Player(String name) {
9 | this.playerId = id;
10 | this.name = name;
11 | this.position = 0;
12 | id++;
13 | }
14 |
15 | public Integer getPlayerId() {
16 | return playerId;
17 | }
18 |
19 | public Integer getPosition() {
20 | return position;
21 | }
22 |
23 | public void setPosition(Integer position) {
24 | this.position = position;
25 | }
26 |
27 | public String getName() {
28 | return name;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/16_FirstContribution/Games/SnakeLadder/Snake.java:
--------------------------------------------------------------------------------
1 | package Games.SnakeLadder;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | public class Snake {
7 | private static final Set uniqueFacePositions = new HashSet<>();
8 | private final Integer face;
9 | private final Integer tail;
10 | public Snake(Integer face, Integer tail) {
11 | if (!uniqueFacePositions.contains(face)) {
12 | this.face = face;
13 | this.tail = tail;
14 | uniqueFacePositions.add(face);
15 | } else {
16 | this.face = this.tail = -1;
17 | }
18 | }
19 |
20 | public Integer getFace() {
21 | return face;
22 | }
23 |
24 | public Integer getTail() {
25 | return tail;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/16_FirstContribution/HelloWorld.java:
--------------------------------------------------------------------------------
1 | public class HelloWorld {
2 | public static void main(String[] args) {
3 | System.out.println("Hello, World!");
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/16_FirstContribution/NeonNumbers.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class NeonNumbers {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 | System.out.print("\nEnter the limit: ");
7 | int limit = scanner.nextInt();
8 | scanner.close();
9 |
10 | boolean foundNeonNumber = false;
11 | System.out.println("\nNeon numbers up to " + limit + ":");
12 |
13 | for (int i = 0; i <= limit; i++) {
14 | if (isNeonNumber(i)) {
15 | System.out.println(i);
16 | foundNeonNumber = true;
17 | }
18 | }
19 |
20 | if (!foundNeonNumber) {
21 | System.out.println("\nNo Neon numbers present in the specified limit.");
22 | }
23 | }
24 |
25 | // Function to check if a number is a Neon number
26 | public static boolean isNeonNumber(int num) {
27 | int sumOfDigitSquares = 0;
28 |
29 | // Calculate the sum of squares of digits
30 | int square = num * num;
31 | while (square > 0) {
32 | int digit = square % 10;
33 | sumOfDigitSquares += digit;
34 | square /= 10;
35 | }
36 |
37 | // Check if the sum of squares equals the original number
38 | return sumOfDigitSquares == num;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/16_FirstContribution/NumberToWordsConverter.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class NumberToWordsConverter {
4 | private static final String[] ones = {
5 | "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
6 | };
7 |
8 | private static final String[] teens = {
9 | "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
10 | };
11 |
12 | private static final String[] tens = {
13 | "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
14 | };
15 |
16 | private static final String[] thousands = {
17 | "", "thousand", "million", "billion", "trillion"
18 | };
19 |
20 | public static String convertToWords(long number) {
21 | if (number == 0) {
22 | return "zero";
23 | }
24 |
25 | return convertToWordsHelper(number).trim();
26 | }
27 |
28 | private static String convertToWordsHelper(long number) {
29 | if (number < 10) {
30 | return ones[(int)number];
31 | } else if (number < 20) {
32 | return teens[(int) (number - 10)];
33 | } else if (number < 100) {
34 | return tens[(int) (number / 10)] + " " + ones[(int) (number % 10)];
35 | } else if (number < 1000) {
36 | return ones[(int) (number / 100)] + " hundred " + convertToWordsHelper(number % 100);
37 | } else {
38 | int i = 0;
39 | String words = "";
40 | while (number > 0) {
41 | if (number % 1000 != 0) {
42 | words = convertToWordsHelper(number % 1000) + " " + thousands[i] + " " + words;
43 | }
44 | number /= 1000;
45 | i++;
46 | }
47 | return words;
48 | }
49 | }
50 |
51 | public static void main(String[] args) {
52 | Scanner scanner = new Scanner(System.in);
53 | System.out.print("Enter a number: ");
54 | long number = scanner.nextLong();
55 | scanner.close();
56 |
57 | String words = convertToWords(number);
58 | System.out.println("In words: " + words);
59 | }
60 | }
--------------------------------------------------------------------------------
/16_FirstContribution/Numbers/ArmstrongNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /**
4 | * This class contains code to check if a number is an Armstrong number (or Narcissistic number)
5 | * An Armstrong number (or Narcissistic number) is a number that is equal to the sum of its own digits
6 | * each raised to the power of the number of digits.
7 | * Example: 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.
8 | */
9 |
10 | public class ArmstrongNumber {
11 | public static void main(String[] args) {
12 | // Initialize the scanner class to take input
13 | Scanner sc = new Scanner(System.in);
14 |
15 | // Prompt the user for input
16 | System.out.print("Enter number to check if it is Armstrong or not : ");
17 |
18 | // Take input
19 | int num = sc.nextInt();
20 |
21 | // Check if number is armstrong and print the desired message
22 | if (checkArmstrong(num))
23 | System.out.println("This number is an Armstrong Number");
24 | else
25 | System.out.println("This number is not an Armstrong Number");
26 | }
27 |
28 |
29 | /**
30 | * This method checks if a number is Armstrong number (or Narcissistic number) or not
31 | *
32 | * @param number The number to check if Armstrong or not
33 | * @return true if the number is an armstrong number, otherwise false
34 | */
35 | public static boolean checkArmstrong(int number) {
36 | // Store the number in a temporary variable to be used in loop for condition
37 | int temp = number;
38 |
39 | // Stores the number of digits in the provided number
40 | int numberOfDigits = 0;
41 |
42 | // Counts the number of digits in the provided number
43 | // temp gets decreased inside the loop
44 | while (temp > 0) {
45 | // We increment number of digits by 1 since temp > 0
46 | numberOfDigits += 1;
47 |
48 | // "temp" will become 0 if all the digits are counted since it is an integer
49 | temp = temp / 10;
50 | }
51 |
52 | // Store the number in a temporary variable to be used in loop for condition
53 | temp = number;
54 |
55 | // Stores the sum of digits each to the power of "numberOfDigits"
56 | int sumOfPoweredDigits = 0;
57 |
58 | // Counts the number of digits in the provided number
59 | // temp gets decreased inside the loop
60 | while (temp > 0) {
61 | // Stores the last digit of a number
62 | int lastDigitOfNumber = temp % 10;
63 |
64 | // Add the last digit to the power "numberOfDigits" to the sum
65 | sumOfPoweredDigits += (int) Math.pow(lastDigitOfNumber, numberOfDigits);
66 |
67 | // Removes the last digit of the number
68 | temp = temp / 10;
69 | }
70 |
71 | // Return if the sum is equal to the original number
72 | return number == sumOfPoweredDigits;
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/16_FirstContribution/Numbers/AutomorphicNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /*
4 | * An automorphic number is a number whose square ends with the number itself.
5 | * For example, 5 is an automorphic number, 5 * 5 = 25, 6 * 6 = 36, 25 * 25 = 625 and so on.
6 | */
7 | public class AutomorphicNumber {
8 | public static void main(String[] args) {
9 | // Initialize the scanner class to take input
10 | Scanner sc = new Scanner(System.in);
11 |
12 | // Prompt the user for input
13 | System.out.print("Enter number to check if it is Automorphic or not : ");
14 |
15 | // Take input
16 | int num = sc.nextInt();
17 |
18 | // Check if number is automorphic and print the desired message
19 | if (checkAutomorphic(num))
20 | System.out.println("This number is an Automorphic Number");
21 | else
22 | System.out.println("This number is not an Automorphic Number");
23 | }
24 |
25 | /**
26 | * Check if the given number is automorphic or not
27 | *
28 | * @param number The number to check
29 | * @return true if the number is automorphic, false otherwise
30 | */
31 | public static boolean checkAutomorphic(int number) {
32 | // Store the square of the number
33 | int square = number * number;
34 |
35 | // Check if the number is automorphic or not
36 | while (number > 0) {
37 | // If the last digit of the number and square are not equal, return false
38 | if (number % 10 != square % 10) {
39 | return false;
40 | }
41 | // Remove the last digit from the number and square
42 | number /= 10;
43 |
44 | // Remove the last digit from the square
45 | square /= 10;
46 | }
47 | return true;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/16_FirstContribution/Numbers/HappyNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /*
4 | * A happy number is a number that, when you repeatedly replace it with the sum of the square of its digits,
5 | * eventually reaches 1.
6 | * Example: 19 is a happy number because 1^2 + 9^2 = 82, and 8^2 + 2^2 = 68, and so on until it reaches 1.
7 | */
8 | public class HappyNumber {
9 | public static void main(String[] args) {
10 | // Initialize the scanner class to take input
11 | Scanner scanner = new Scanner(System.in);
12 |
13 | // Prompt the user for input
14 | System.out.print("Enter a number to check if it's a Happy Number: ");
15 |
16 | // Take input
17 | int number = scanner.nextInt();
18 |
19 | // Check if the number is a Happy Number and print the desired message
20 | if (isHappy(number)) {
21 | System.out.println(number + " is a Happy Number.");
22 | } else {
23 | System.out.println(number + " is not a Happy Number.");
24 | }
25 | }
26 |
27 | /**
28 | * Checks if a given integer is a Happy Number.
29 | *
30 | * @param number the number to check.
31 | * @return true if the input number is a Happy Number, false otherwise.
32 | */
33 | public static boolean isHappy(int number) {
34 | // Initialize the sum of squared digits to 0.
35 | int sum = 0;
36 |
37 | // Iterate until n becomes 0.
38 | while (number > 0) {
39 | // Extract the last digit.
40 | int temp = number % 10;
41 |
42 | // Square and add the digit to the sum.
43 | sum += (int) Math.pow(temp, 2);
44 |
45 | // Remove the last digit by integer division.
46 | number /= 10;
47 | }
48 |
49 | // Check if the sum of squared digits is 1, indicating a Happy Number.
50 | if (sum == 1) {
51 | return true;
52 | } else if (sum == 4) {
53 | // If the sum becomes 4, it will never reach 1, so it's not a Happy Number.
54 | return false;
55 | } else {
56 | // Recursively call isHappy with the sum until we reach either 1 or 4.
57 | return isHappy(sum);
58 | }
59 | }
60 | }
--------------------------------------------------------------------------------
/16_FirstContribution/Numbers/KaprekarNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /*
4 | * A Kaprekar number is a number whose square when divided into two parts
5 | * and such that sum of parts is equal to the original number and none of the parts has value 0.
6 | * For example, 45 is a Kaprekar number, because 45^2 = 2025 and 20 + 25 = 45.
7 | */
8 | public class KaprekarNumber {
9 | public static void main(String[] args) {
10 | // Initialize the scanner class to take input
11 | Scanner sc = new Scanner(System.in);
12 |
13 | // Prompt the user for input
14 | System.out.print("Enter number to check if it is Kaprekar or not : ");
15 |
16 | // Take input
17 | int num = sc.nextInt();
18 |
19 | // Check if number is Kaprekar and print the desired message
20 | if (checkKaprekar(num))
21 | System.out.println("This number is an Kaprekar Number");
22 | else
23 | System.out.println("This number is not an Kaprekar Number");
24 | }
25 |
26 | public static boolean checkKaprekar(int number){
27 | // 1. Find square of number
28 | int square = number * number;
29 |
30 | // 2. Count number of digits in square
31 | int count = 0;
32 |
33 | // 3. Find sum of digits from right side
34 | while (square != 0){
35 | count++;
36 | square /= 10;
37 | }
38 |
39 | // 4. Find sum of digits from left side
40 | square = number * number;
41 |
42 | // 5. Check if sum of digits is equal to original number
43 | for (int i = 1; i < count; i++){
44 | int first = (int) (square / Math.pow(10, i));
45 | int second = (int) (square % Math.pow(10, i));
46 | if (first + second == number && first != 0 && second != 0){
47 | return true;
48 | }
49 | }
50 | return false;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/16_FirstContribution/Numbers/KrishnamurthyNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /*
4 | * A Krishnamurthy number (or strong number) is a number whose sum of the factorial of digits is equal to the number itself.
5 | * For example 145, 1! + 4! + 5! = 1 + 24 + 120 = 145.
6 | */
7 | public class KrishnamurthyNumber {
8 | public static void main(String[] args) {
9 | // Initialize the scanner class to take input
10 | Scanner sc = new Scanner(System.in);
11 |
12 | // Prompt the user for input
13 | System.out.print("Enter number to check if it is Krishnamurthy or not : ");
14 |
15 | // Take input
16 | int num = sc.nextInt();
17 |
18 | // Check if number is Krishnamurthy and print the desired message
19 | if (isKrishnamurthy(num))
20 | System.out.println("This number is a Krishnamurthy Number");
21 | else
22 | System.out.println("This number is not a Krishnamurthy Number");
23 |
24 | }
25 |
26 | /**
27 | * This method checks if a number is Krishnamurthy or not
28 | * @param number the number to check
29 | * @return true if number is Krishnamurthy, false otherwise
30 | */
31 | public static boolean isKrishnamurthy(int number) {
32 | // Store the sum of factorial of digits
33 | int sum = 0;
34 |
35 | // Copy n to temp
36 | int temp = number;
37 |
38 | // Calculate sum of factorial of digits
39 | while (temp > 0) {
40 | // Get the last digit
41 | sum += factorial(temp % 10);
42 |
43 | // Remove the last digit
44 | temp /= 10;
45 | }
46 |
47 | // Check if sum is equal to n
48 | return sum == number;
49 | }
50 |
51 | public static int factorial(int n) {
52 | // 0! = 1
53 | if (n == 0) return 1;
54 |
55 | // n! = n * (n - 1)!
56 | return n * factorial(n - 1);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/16_FirstContribution/Numbers/PalindromeNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /**
4 | * This class contains code to check if a number is a Palindrome number
5 | * A Palindrome number is a number that is equal to the number formed by reversing the digits
6 | * Example: 121 is a Palindrome number because 121 reversed is 121.
7 | * Example: 123 is not a Palindrome number because 123 reversed is 321.
8 | */
9 |
10 | public class PalindromeNumber {
11 | public static void main(String[] args) {
12 | // Create a Scanner object to read input from the console
13 | Scanner scanner = new Scanner(System.in);
14 |
15 | // Prompt the user to enter a number
16 | System.out.print("Enter a number: ");
17 |
18 | // Read the number from the console
19 | int number = scanner.nextInt();
20 |
21 | // Check if the number is a Palindrome number
22 | if (checkPalindrome(number)) {
23 | System.out.println(number + " is a Palindrome number");
24 | } else {
25 | System.out.println(number + " is not a Palindrome number");
26 | }
27 | }
28 |
29 | /**
30 | * This method checks if a number is a Palindrome number
31 | * @param number The number to be checked
32 | * @return true if the number is a Palindrome number, otherwise false
33 | **/
34 | public static boolean checkPalindrome(int number) {
35 | // Store the number in a temporary variable to be used in loop for condition
36 | int temp = number;
37 |
38 | // Stores the number formed by reversing the digits of the provided number
39 | int reversedNumber = 0;
40 |
41 | // Counts the number of digits in the provided number
42 | // temp gets decreased inside the loop
43 | while (temp > 0) {
44 | // We multiply the reversedNumber by 10 to shift the digits to the left
45 | // Example: 123 becomes 1230
46 | reversedNumber = reversedNumber * 10;
47 |
48 | // We add the last digit of the number to the reversedNumber
49 | // Example: 123 becomes 1230 + 3 = 1233
50 | reversedNumber = reversedNumber + temp % 10;
51 |
52 | // We divide the original number by 10 to remove the last digit
53 | // Example: 123 becomes 12
54 | temp = temp / 10;
55 | }
56 |
57 | // Return if the reversed number is equal to the original number
58 | return reversedNumber == number;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/16_FirstContribution/Numbers/PerfectNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /*
4 | * A perfect number is a positive integer that is equal to the sum of its proper divisors.
5 | * A proper divisor is a positive integer other than the number itself that divides the number evenly.
6 | * For example, 6 is a perfect number because the sum of its proper divisors, 1, 2, and 3, is equal to 6.
7 | */
8 | public class PerfectNumber {
9 | public static void main(String[] args) {
10 | // Create a Scanner object
11 | Scanner sc = new Scanner(System.in);
12 |
13 | // Prompt the user to enter an integer
14 | System.out.print("Enter an integer: ");
15 |
16 | // Read the integer
17 | int number = sc.nextInt();
18 |
19 | // Check if number is perfect number and print the desired message
20 | if (isPerfect(number))
21 | System.out.println(number + " is a perfect number");
22 | else
23 | System.out.println(number + " is not a perfect number");
24 | }
25 |
26 | /**
27 | * Check if a number is perfect number
28 | * @param number the number to check
29 | * @return true if number is perfect number, false otherwise
30 | */
31 | public static boolean isPerfect(int number) {
32 | // Store the sum of proper divisors
33 | int sum = 0;
34 |
35 | // Find all divisors and add them
36 | for (int i = 1; i < number; i++) {
37 | if (number % i == 0) {
38 | sum += i;
39 | }
40 | }
41 |
42 | // Return true if sum is equal to number
43 | return sum == number;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/16_FirstContribution/Numbers/PrimeNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /*
4 | * This program will determine if a number is prime or not.
5 | * A prime number is a number that is only divisible by 1 and itself.
6 | * Note: 1 is not a prime number.
7 | * Example: 2 is a prime number.
8 | * Example: 4 is not a prime number.
9 | */
10 |
11 | public class PrimeNumber {
12 | public static void main(String[] args) {
13 | // Create a Scanner object to read input.
14 | Scanner sc = new Scanner(System.in);
15 |
16 | // Prompt the user to enter a number.
17 | System.out.print("Enter a number: ");
18 | int number = sc.nextInt();
19 |
20 | // Check if the number is prime.
21 | if (isPrime(number)) {
22 | System.out.println(number + " is a prime number.");
23 | } else {
24 | System.out.println(number + " is not a prime number.");
25 | }
26 | }
27 |
28 | /**
29 | * This method will determine if a number is prime or not.
30 | * @param number The number to check.
31 | * @return true if the number is prime, false otherwise.
32 | */
33 | public static boolean isPrime(int number) {
34 | // If the number is 1, then it is not prime.
35 | if (number == 1)
36 | return false;
37 |
38 | // We loop for each divisor from 2 to square root(number) and check if there is no remainder.
39 | // If there is no remainder, then the number is not prime.
40 | // We can stop at square root(number) because after that, we will be checking the same divisors again.
41 | for (int i = 2; i < Math.sqrt(number); i++) {
42 | // If there is no remainder, then the number is not prime.
43 | if (number % i == 0)
44 | return false;
45 | }
46 | // If we get here, then the number is prime.
47 | return true;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/16_FirstContribution/Numbers/PronicNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /*
4 | * This class contains code to check if a number is a Pronic number (or Narcissistic number)
5 | * A pronic number is a number which is the product of two consecutive integers, that is, a number of the form n(n + 1).
6 | * The first few pronic numbers are:
7 | * 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, …….
8 | */
9 | public class PronicNumber {
10 | public static void main(String[] args) {
11 | // Create a Scanner object
12 | Scanner sc = new Scanner(System.in);
13 |
14 | // Prompt the user to enter a number
15 | System.out.print("Enter a number: ");
16 |
17 | // Read the number
18 | int n = sc.nextInt();
19 |
20 | // Check if n is a pronic number
21 | if (isPronic(n)) {
22 | System.out.println(n + " is a pronic number");
23 | } else {
24 | System.out.println(n + " is not a pronic number");
25 | }
26 | }
27 |
28 |
29 | /**
30 | * This method checks if a number is a pronic number
31 | * @param number The number to be checked
32 | * @return true if the number is a pronic number, false otherwise
33 | */
34 | public static boolean isPronic(int number) {
35 | // Loop variable
36 | int i = 0;
37 |
38 | // Loop until i * (i + 1) is less than or equal to n
39 | while (i * (i + 1) <= number) {
40 | // Check if i * (i + 1) is equal to n
41 | if (i * (i + 1) == number) {
42 | // If yes, then n is a pronic number
43 | return true;
44 | }
45 |
46 | // Increment i
47 | i++;
48 | }
49 |
50 | // If no, then n is not a pronic number
51 | return false;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/16_FirstContribution/Numbers/TriangularNumber:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /**
4 | * This class checks if a number is triangular or not.
5 | * A number is triangular if it is formed by the addition of
6 | * consecutive sequence of integers starting from 1.
7 | * @author Sayan Biswas
8 | * @version 13.10.2023
9 | */
10 | public class TriangularNumber {
11 |
12 | /**
13 | * Stores the number
14 | */
15 | private int x;
16 |
17 | /**
18 | * Initializes instance variables
19 | */
20 | private TriangularNumber() {
21 | x=0;
22 | }
23 |
24 | /**
25 | * Inputs number from user
26 | */
27 | private void input() {
28 | Scanner sc = new Scanner(System.in);
29 | System.out.print("Enter natural number: ");
30 | x = Integer.parseInt(sc.next());
31 | if(x < 1) {
32 | System.out.println("Wrong input! Try again.");
33 | input();
34 | return;
35 | }
36 | }
37 |
38 | /**
39 | * This method checks if a number is triangular or not.
40 | * A number is triangular if it is formed by the addition
41 | * of consecutive sequence of integers starting from 1.
42 | * Let x be the sum of n consecutive numbers from 1.
43 | * So, x=n*(n+1)/2, where n is a natural number.
44 | * Calculating we get, n=-0.5+-(Math.sqrt(1+8*x))/2
45 | * If n is a natural number then x is a triangular number.
46 | * @return true or false
47 | */
48 | private boolean triangularCheck() {
49 | double n1, n2;
50 | n1 = -0.5+(Math.sqrt(1+8*x))/2;
51 | n2 = -0.5-(Math.sqrt(1+8*x))/2;
52 | return n1 % 1 == 0 || n2 % 1 == 0;
53 | }
54 |
55 | /**
56 | * Calls other methods
57 | * @param args Arguments passed to main method
58 | */
59 | public static void main(String[] args) {
60 | TriangularNumber ob = new TriangularNumber();
61 | ob.input();
62 | System.out.println(ob.triangularCheck() ?
63 | "Number is a triangular number." :
64 | "Number is not a triangular number.");
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/16_FirstContribution/Numbers/UniqueNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /*
4 | * This program will take in a number and check if it is unique.
5 | * A unique number is a number that has no repeating digits.
6 | * For example, 1234 is a unique number, but 1224 is not.
7 | */
8 | public class UniqueNumber {
9 | public static void main(String[] args) {
10 | // Create a Scanner object to read input
11 | Scanner input = new Scanner(System.in);
12 |
13 | // Prompt the user to enter a number
14 | System.out.print("Enter a number: ");
15 |
16 | // Read the number
17 | int number = input.nextInt();
18 |
19 | // Check if the number is unique
20 | if (isUnique(number)) {
21 | System.out.println(number + " is a unique number.");
22 | } else {
23 | System.out.println(number + " is not a unique number.");
24 | }
25 | }
26 |
27 | /**
28 | * This method will take in a number and check if it is unique.
29 | *
30 | * @param number The number to check if it is unique
31 | * @return true if the number is unique, false otherwise
32 | */
33 | public static boolean isUnique(int number) {
34 | // Create an array to store the number of times each digit appears
35 | // Digits can be from 0 to 9, so the array will have 10 elements
36 | // The digits will represent indexes of the array
37 | int[] array = new int[10];
38 |
39 | // Loop through each digit of the number
40 | while (number > 0) {
41 | // Get the last digit of the number
42 | int digit = number % 10;
43 |
44 | // Increment the number of times the digit appears
45 | array[digit]++;
46 |
47 | // Remove the last digit from the number
48 | number /= 10;
49 | }
50 |
51 | // Loop through the array
52 | for (int j : array) {
53 | // If a digit appears more than once, the number is not unique
54 | if (j > 1) {
55 | return false;
56 | }
57 | }
58 |
59 | // If the loop finishes, the number is unique
60 | return true;
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/16_FirstContribution/PasswordGenerator.java:
--------------------------------------------------------------------------------
1 | import java.security.SecureRandom;
2 | import java.util.*;
3 |
4 |
5 | public class PasswordGenerator {
6 |
7 | static char[] SYMBOLS = "^$*.[]{}()?-\"!@#%&/\\,><':;|_~`".toCharArray();
8 | static char[] LOWERCASE = "abcdefghijklmnopqrstuvwxyz".toCharArray();
9 | static char[] UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
10 | static char[] NUMBERS = "0123456789".toCharArray();
11 | static char[] EASY = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
12 | static char[] MED = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
13 |
14 | static char[] ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789^$*.[]{}()?-\"!@#%&/\\,><':;|_~`".toCharArray();
15 | static Random rand = new SecureRandom();
16 |
17 | public static String getPassword(int length , int c) {
18 | assert length >= 4;
19 | char[] password = new char[length];
20 |
21 | switch (c){
22 | case 1:
23 | password[0] = LOWERCASE[rand.nextInt(LOWERCASE.length)];
24 | password[1] = UPPERCASE[rand.nextInt(UPPERCASE.length)];
25 |
26 | //populate rest of the password with random chars
27 | for (int i = 2; i < length; i++) {
28 | password[i] = EASY[rand.nextInt(EASY.length)];
29 | }
30 | break;
31 |
32 | case 2:
33 | password[0] = LOWERCASE[rand.nextInt(LOWERCASE.length)];
34 | password[1] = UPPERCASE[rand.nextInt(UPPERCASE.length)];
35 | password[2] = NUMBERS[rand.nextInt(NUMBERS.length)];
36 |
37 | for (int i = 3; i < length; i++) {
38 | password[i] = MED[rand.nextInt(MED.length)];
39 | }
40 | break;
41 |
42 |
43 | case 3:
44 | password[0] = LOWERCASE[rand.nextInt(LOWERCASE.length)];
45 | password[1] = UPPERCASE[rand.nextInt(UPPERCASE.length)];
46 | password[2] = NUMBERS[rand.nextInt(NUMBERS.length)];
47 | password[3] = SYMBOLS[rand.nextInt(SYMBOLS.length)];
48 |
49 |
50 | for (int i = 4; i < length; i++) {
51 | password[i] = ALL_CHARS[rand.nextInt(ALL_CHARS.length)];
52 | }
53 | break;
54 |
55 | default:
56 | return "";
57 | }
58 |
59 |
60 | //shuffle it up
61 | for (int i = 0; i < password.length; i++) {
62 | int randomPosition = rand.nextInt(password.length);
63 | char temp = password[i];
64 | password[i] = password[randomPosition];
65 | password[randomPosition] = temp;
66 | }
67 |
68 | return new String(password);
69 | }
70 |
71 | public static void main(String[] args) {
72 | Scanner sc=new Scanner(System.in);
73 | System.out.println("Enter the length of the password you want");
74 | int l=sc.nextInt();
75 | System.out.println("Enter the complexity of Password you want 1-Easy 2-Medium 3-Hard");
76 | int c=sc.nextInt();
77 | System.out.println(getPassword(l,c));
78 | }
79 | }
--------------------------------------------------------------------------------
/16_FirstContribution/Patterns/ButterflyPattern.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class ButterflyPattern {
4 | public static void main(String[] args) {
5 | int i, j, n;
6 | Scanner sc = new Scanner(System.in);
7 | n = sc.nextInt();
8 | // upper half of the pattern
9 | for (i = 0; i < n; i++) {
10 | for (j = 0; j < (2 * n); j++) {
11 | if (i >= j) // upper left triangle
12 | System.out.print("*");
13 | else
14 | System.out.print(" ");
15 | if (i >= (2 * n - 1) - j) // upper right triangle
16 | System.out.print("*");
17 | else
18 | System.out.print(" ");
19 | }
20 | System.out.println("");
21 | }
22 | // bottom half of the pattern
23 | for (i = 0; i < n; i++) {
24 | for (j = 0; j < (2 * n); j++) {
25 | if (i + j <= n - 1) // bottom left triangle
26 | System.out.print("*");
27 | else
28 | System.out.print(" ");
29 | if ((i + n) <= j) // bottom right triangle
30 | System.out.print("*");
31 | else
32 | System.out.print(" ");
33 | }
34 | System.out.println("");
35 | }
36 | }
37 | }
--------------------------------------------------------------------------------
/16_FirstContribution/PlaySnakeNLadder.java:
--------------------------------------------------------------------------------
1 | import Games.SnakeLadder.Game;
2 | import Games.SnakeLadder.Ladder;
3 | import Games.SnakeLadder.Player;
4 | import Games.SnakeLadder.Snake;
5 |
6 | public class PlaySnakeNLadder {
7 | public static void main(String[] args) {
8 | System.out.println("Hello world!");
9 |
10 | // ---------------- SNAKE & LADDER GAME ------------- //
11 | Game snakeLadder = new Game.GameBuilder()
12 | .addPlayer(new Player("TangoRishi"))
13 | .addPlayer(new Player("CompetitiveBlood"))
14 | .addLadder(new Ladder(3,80))
15 | .addLadder(new Ladder(12, 81))
16 | .addLadder(new Ladder(45, 82))
17 | .addLadder(new Ladder(69, 83))
18 | .addSnake(new Snake(73, 1))
19 | .addSnake(new Snake(12, 3))
20 | .build();
21 |
22 | snakeLadder
23 | .playNext().playNext()
24 | .playNext().playNext()
25 | .playNext().playNext()
26 | .playNext().playNext()
27 | .playNext().playNext()
28 | .playNext().playNext();
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/16_FirstContribution/SORTING/BubbleSort.java:
--------------------------------------------------------------------------------
1 | public class BubbleSort {
2 | // Sorts an array using Bubble Sort algorithm
3 | public static void bubbleSort(int[] arr) {
4 | int n = arr.length;
5 | boolean swapped;
6 | do {
7 | swapped = false;
8 | for (int i = 1; i < n; i++) {
9 | if (arr[i - 1] > arr[i]) {
10 | // Swap arr[i-1] and arr[i]
11 | int temp = arr[i - 1];
12 | arr[i - 1] = arr[i];
13 | arr[i] = temp;
14 | swapped = true;
15 | }
16 | }
17 | n--; // Decrease the size of the unsorted portion
18 | } while (swapped);
19 | }
20 |
21 | public static void main(String[] args) {
22 | // Test Case 1: Small array
23 | int[] arr1 = {64, 34, 25, 12, 22, 11, 90};
24 | bubbleSort(arr1);
25 | System.out.println("Sorted array for Test Case 1:");
26 | printArray(arr1);
27 |
28 | // Test Case 2: Large array
29 | int[] arr2 = {5, 2, 9, 1, 5, 6, 0, 3, 8, 7, 4};
30 | bubbleSort(arr2);
31 | System.out.println("Sorted array for Test Case 2:");
32 | printArray(arr2);
33 | }
34 |
35 | // Utility method to print an array
36 | public static void printArray(int[] arr) {
37 | for (int num : arr) {
38 | System.out.print(num + " ");
39 | }
40 | System.out.println();
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/16_FirstContribution/SORTING/InsertionSort:
--------------------------------------------------------------------------------
1 | class insertion_sort {
2 | // Insertion sort function
3 | static void insertionSort(int[] arr, int n) {
4 | int i, j;
5 | // Assuming 0th element to be already sorted and checking further
6 | for (i = 1; i < n; i++) {
7 | int key = arr[i];
8 | j = i - 1;
9 | // Comparing jth element with j-1 for swapping
10 | while (j >= 0 && arr[j] > key) {
11 | arr[j + 1] = arr[j];
12 | j = j - 1;
13 | }
14 | // Updating the 0th position
15 | arr[j + 1] = key;
16 | }
17 | }
18 | }
19 | public static void main(String[] args) {
20 | // Creating and accepting/inputting values in an array from user
21 | int n;
22 | int[] arr;
23 | Scanner sc = new Scanner(System.in);
24 | System.out.print("Enter number of elements: ");
25 | n = sc.nextInt();
26 | arr = new int[n];
27 | for (int i = 0; i < n; i++) {
28 | arr[i] = sc.nextInt();
29 | }
30 | System.out.println();
31 | insertionSort(arr,n);
32 | // Checking/Printing the sorted Array
33 | for (int i = 0; i < n; i++) {
34 | System.out.println(arr[i]);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/16_FirstContribution/SORTING/MergeSort.java:
--------------------------------------------------------------------------------
1 | public class MergeSort {
2 | // Sorts an array using Merge Sort algorithm
3 | public static void mergeSort(int[] arr) {
4 | int n = arr.length;
5 | if (n > 1) {
6 | int mid = n / 2;
7 |
8 | // Split the array into two halves
9 | int[] left = new int[mid];
10 | int[] right = new int[n - mid];
11 |
12 | System.arraycopy(arr, 0, left, 0, mid);
13 | System.arraycopy(arr, mid, right, 0, n - mid);
14 |
15 | // Recursively sort the two halves
16 | mergeSort(left);
17 | mergeSort(right);
18 |
19 | // Merge the sorted halves
20 | merge(arr, left, right);
21 | }
22 | }
23 |
24 | // Merges two sorted arrays into one sorted array
25 | private static void merge(int[] arr, int[] left, int[] right) {
26 | int i = 0, j = 0, k = 0;
27 |
28 | while (i < left.length && j < right.length) {
29 | if (left[i] < right[j]) {
30 | arr[k++] = left[i++];
31 | } else {
32 | arr[k++] = right[j++];
33 | }
34 | }
35 |
36 | while (i < left.length) {
37 | arr[k++] = left[i++];
38 | }
39 |
40 | while (j < right.length) {
41 | arr[k++] = right[j++];
42 | }
43 | }
44 |
45 | public static void main(String[] args) {
46 | // Test Case 1: Small array
47 | int[] arr1 = {64, 34, 25, 12, 22, 11, 90};
48 | mergeSort(arr1);
49 | System.out.println("Sorted array for Test Case 1:");
50 | printArray(arr1);
51 |
52 | // Test Case 2: Large array
53 | int[] arr2 = {5, 2, 9, 1, 5, 6, 0, 3, 8, 7, 4};
54 | mergeSort(arr2);
55 | System.out.println("Sorted array for Test Case 2:");
56 | printArray(arr2);
57 | }
58 |
59 | // Utility method to print an array
60 | public static void printArray(int[] arr) {
61 | for (int num : arr) {
62 | System.out.print(num + " ");
63 | }
64 | System.out.println();
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/16_FirstContribution/SORTING/SelectionSort.java:
--------------------------------------------------------------------------------
1 | public class SelectionSort {
2 | // Sorts an array using Selection Sort algorithm
3 | public static void selectionSort(int[] arr) {
4 | int n = arr.length;
5 |
6 | for (int i = 0; i < n - 1; i++) {
7 | // Find the minimum element in the unsorted portion
8 | int minIndex = i;
9 | for (int j = i + 1; j < n; j++) {
10 | if (arr[j] < arr[minIndex]) {
11 | minIndex = j;
12 | }
13 | }
14 |
15 | // Swap the minimum element with the current element
16 | if (minIndex != i) {
17 | int temp = arr[i];
18 | arr[i] = arr[minIndex];
19 | arr[minIndex] = temp;
20 | }
21 | }
22 | }
23 |
24 | public static void main(String[] args) {
25 | // Test Case 1: Small array
26 | int[] arr1 = {64, 34, 25, 12, 22, 11, 90};
27 | selectionSort(arr1);
28 | System.out.println("Sorted array for Test Case 1:");
29 | printArray(arr1);
30 |
31 | // Test Case 2: Large array
32 | int[] arr2 = {5, 2, 9, 1, 5, 6, 0, 3, 8, 7, 4};
33 | selectionSort(arr2);
34 | System.out.println("Sorted array for Test Case 2:");
35 | printArray(arr2);
36 | }
37 |
38 | // Utility method to print an array
39 | public static void printArray(int[] arr) {
40 | for (int num : arr) {
41 | System.out.print(num + " ");
42 | }
43 | System.out.println();
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/16_FirstContribution/StonePaperScissors:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 | import java.util.Random;
3 |
4 | class spsgame {
5 | public static void main(String[] args) {
6 | Scanner sc = new Scanner(System.in);
7 | int i=0 ;
8 | while (i != 5) {
9 | System.out.println("1 --- Stone");
10 | System.out.println("2 --- Paper");
11 | System.out.println("3 --- Scissors");
12 | System.out.println();
13 | int u;
14 | u = sc.nextInt();
15 | if (u == 1) {
16 | System.out.println("User got Stone");
17 | }
18 | if (u == 2) {
19 | System.out.println("User got Paper");
20 | }
21 | if (u == 3) {
22 | System.out.println("User got Scissors");
23 | }
24 | Random r = new Random();
25 | int c = r.nextInt(1, 4);
26 | if (c == 1) {
27 | System.out.println("Computer got Stone");
28 | }
29 | if (c == 2) {
30 | System.out.println("Computer got Paper");
31 | }
32 | if (c == 3) {
33 | System.out.println("Computer got Scissors");
34 | }
35 |
36 | if (u == c) {
37 | System.out.println("It's a tie");
38 | } else if (u == 1 && c == 2) {
39 | System.out.println(("Computer wins!"));
40 | } else if (u == 1 && c == 3) {
41 | System.out.println(("User wins!"));
42 | } else if (u == 2 && c == 1) {
43 | System.out.println(("User wins!"));
44 | } else if (u == 2 && c == 3) {
45 | System.out.println(("Computer wins!"));
46 | } else if (u == 3 && c == 1) {
47 | System.out.println(("Computer wins!"));
48 | } else if (u == 3 && c == 2) {
49 | System.out.println(("User wins!"));
50 | }
51 | System.out.println("");
52 | System.out.println("4 --- Play Again ");
53 | System.out.println("5 --- EXIT ");
54 | i = sc.nextInt();
55 | }
56 | System.out.println("Thanks for playing");
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/16_FirstContribution/TowerOfHanoi.java:
--------------------------------------------------------------------------------
1 | public class TowerOfHanoi {
2 |
3 | public static void main(String[] args) {
4 | towerOfHanoi(3, 'A', 'C', 'B');
5 | }
6 |
7 | public static void towerOfHanoi(int n, char fromRod, char toRod, char auxRod) {
8 | if (n == 1) {
9 | System.out.println("Move disk 1 from rod " + fromRod + " to rod " + toRod);
10 | return;
11 | }
12 |
13 | towerOfHanoi(n - 1, fromRod, auxRod, toRod);
14 | System.out.println("Move disk " + n + " from rod " + fromRod + " to rod " + toRod);
15 | towerOfHanoi(n - 1, auxRod, toRod, fromRod);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/16_FirstContribution/WashingMachine.java:
--------------------------------------------------------------------------------
1 | public class WashingMachine {
2 | public static int minMovesToBalance(int[] machines) {
3 | int totalDresses = 0;
4 | int numMachines = machines.length;
5 |
6 | for (int i = 0; i < numMachines; i++) {
7 | totalDresses += machines[i];
8 | }
9 |
10 | if (totalDresses % numMachines != 0) {
11 | return -1;
12 | }
13 |
14 | int targetDresses = totalDresses / numMachines;
15 | int maxBalance = 0;
16 | int runningBalance = 0;
17 |
18 | for (int i = 0; i < numMachines; i++) {
19 | int balance = machines[i] - targetDresses;
20 | runningBalance += balance;
21 | maxBalance = Math.max(maxBalance, Math.abs(runningBalance));
22 | }
23 |
24 | return maxBalance;
25 | }
26 |
27 | public static void main(String[] args) {
28 | int[] machines1 = {1, 0, 5};
29 | int result1 = minMovesToBalance(machines1);
30 | System.out.println(result1);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/16_FirstContribution/minMax.java:
--------------------------------------------------------------------------------
1 | //Finding the Largest and Smallest value from user input of 10 values
2 |
3 | import java.util.Scanner;
4 |
5 | public class minMax {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int[] cat = new int[10];
9 |
10 |
11 | for (int i = 0; i < cat.length; i++) {
12 | System.out.print("Enter the value of [" + i + "]: ");
13 | cat[i] = scanner.nextInt();
14 | }
15 |
16 | int small = cat[0];
17 | int large = cat[0];
18 | for (int i = 1; i < cat.length; i++) {
19 | if (cat[i] < small) {
20 | small = cat[i];
21 | }
22 | if (cat[i] > large) {
23 | large = cat[i];
24 | }
25 | }
26 |
27 | System.out.println("Largest is " + large + " and smallest is " + small);
28 |
29 | scanner.close();
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/17_Stream_API/stream_api.md:
--------------------------------------------------------------------------------
1 | # Java Stream API
2 |
3 | The Java Stream API is a powerful feature introduced in Java 8 to manipulate and process collections of data in a more functional and expressive way. It provides a higher-level abstraction for working with sequences of elements, allowing developers to perform various operations on the data with concise and readable code.
4 |
5 | ## Purpose
6 |
7 | The Stream API simplifies complex data processing tasks by allowing developers to express their intent more declaratively. It offers an efficient and streamlined approach for performing common operations on collections, such as filtering, mapping, reducing, and more. This results in code that is not only easier to read and maintain but also often more efficient due to potential optimizations by the underlying framework.
8 |
9 | In essence, the Stream API promotes the following key benefits:
10 |
11 | - **Conciseness**: Stream operations are typically shorter and more expressive than equivalent imperative code.
12 | - **Readability**: Stream code reads like a series of data transformations, making it easier to understand.
13 | - **Parallel Processing**: Streams can easily be parallelized for improved performance on multi-core processors.
14 |
15 | Java Streams make it possible to process collections without manually writing loops, providing a more functional and declarative style of programming.
16 |
17 | ## Version
18 |
19 | The Stream API was introduced in Java 8, and it represents a significant enhancement to the language's capabilities for handling collections and data manipulation. Since its introduction, it has become a fundamental tool in Java for working with data in a more modern and efficient way.
20 |
21 | Whether you're dealing with lists, arrays, or any other data source, the Stream API can simplify your code and make it more maintainable.
22 |
23 | # Java Stream API Examples
24 |
25 | Java Stream API provides a powerful and expressive way to work with collections and process data. Here are examples of different Stream API methods and operations:
26 |
27 | ## Creating a Stream
28 |
29 | You can create a Stream from various data sources, such as a collection, array, or using `Stream.of()`.
30 |
31 | ```java
32 | List numbers = Arrays.asList(1, 2, 3, 4, 5);
33 | Stream numberStream = numbers.stream();
34 |
35 | Stream stringStream = Stream.of("apple", "banana", "cherry");
36 | ```
37 |
38 | ### Using Collection's stream() method
39 |
40 | The most common way to get a Stream is by calling the `stream()` method on any collection object. This returns an immutable and ordered Stream consisting
41 | The easiest way is by calling `.stream()` on any existing collection object (e.g., List). This returns an ordered sequential Stream containing all elements
42 |
43 | Now let's discuss different methods of Stream API
44 |
45 | # Java Stream API - `forEach()` Method
46 |
47 | The `forEach()` method is a terminal operation in the Java Stream API that allows you to perform an action on each element of the stream. It is often used to iterate through the stream and apply a specific operation to each element without producing a new stream or collection.
48 | It takes a `Consumer functional interface` as the argument.
49 |
50 | ## Example
51 |
52 | Let's say you have a list of numbers and you want to print each number to the console using the `forEach()` method:
53 |
54 | ```java
55 | List numbers = Arrays.asList(1, 2, 3, 4, 5);
56 |
57 | // Using forEach to print each number
58 | numbers.stream()
59 | .forEach(number -> System.out.println(number));
60 | ```
61 |
62 | In this example, the lambda expression `(number -> System.out.println(number))` is used as a Consumer to specify the action to be performed on each element.
63 |
64 | # Java Stream API - `filter()` Method
65 |
66 | The `filter()` method is an intermediate operation in the Java Stream API that allows you to select elements from a stream based on a specified condition. It is commonly used to filter out elements that do not meet a particular criteria, creating a new stream that contains only the elements that pass the filter.
67 | It commonly takes a `Predicate` functional interface as the argument.
68 |
69 | ## Example
70 |
71 | Let's say you have a list of numbers and you want to create a new stream that contains only the even numbers using the `filter()` method:
72 |
73 | ```java
74 | List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
75 |
76 | // Using filter to select even numbers
77 | Stream evenNumbers = numbers.stream()
78 | .filter(number -> number % 2 == 0);
79 | ```
80 |
81 | In this example, a lambda expression of the form `(number -> number % 2 == 0)` is used as the Predicate to filter out the even numbers.
82 |
83 | # Java Stream API - `map()` Method
84 |
85 | The `map()` method is an intermediate operation in the Java Stream API that allows you to transform each element of a stream into another object. It commonly takes a `Function` functional interface as the argument.
86 |
87 | ## Example
88 |
89 | Let's say you have a list of integers, and you want to create a new stream that contains the square of each integer using the `map()` method:
90 |
91 | ```java
92 | List numbers = Arrays.asList(1, 2, 3, 4, 5);
93 |
94 | // Using map to square each number
95 | Stream squaredNumbers = numbers.stream()
96 | .map(number -> number * number);
97 | ```
98 |
99 | In this example, a lambda expression `(number -> number * number)` is used as a Function to square each integer in the stream. The resulting stream, squaredNumbers, contains the squared values.
100 |
101 | # Java Stream API - `reduce()` Method
102 |
103 | The `reduce()` method in the Java Stream API is a terminal operation used to combine elements of a stream into a single result. It allows you to perform reductions such as summing, finding the maximum or minimum, and more.
104 |
105 | ## Example
106 |
107 | Let's say you have a list of numbers and you want to find the sum of all the numbers using the `reduce()` operation:
108 |
109 | ```java
110 | List numbers = Arrays.asList(1, 2, 3, 4, 5);
111 |
112 | // Using reduce to calculate the sum of numbers
113 | int sum = numbers.stream()
114 | .reduce(0, (a, b) -> a + b);
115 | ```
116 |
117 | In this example, the reduce operation takes two arguments:
118 |
119 | 1. The identity value (0 in this case) is the initial value for the accumulation.
120 | 2. lambda expression (a, b) -> a + b is used as the binary operator to combine the elements. It defines how the accumulation is performed.
121 |
122 | The result is the sum of all the numbers in the stream.
123 |
124 | # Collectors in Java Stream API
125 |
126 | Collectors are utility classes in the Java Stream API that facilitate the collection of elements from a stream into various data structures, such as lists, sets, and maps. They also enable operations like grouping, summing, averaging, and more. Let's explore some common collectors and their usage.
127 |
128 | ## Collecting to a List
129 |
130 | You can use the `Collectors.toList()` collector to collect elements from a stream into a List.
131 |
132 | ## Example
133 |
134 | - To collect elements into a List, you can use the `Collectors.toList()` collector:
135 |
136 | ```java
137 | List fruits = Stream.of("apple", "banana", "cherry")
138 | .collect(Collectors.toList());
139 | ```
140 |
141 | This will create a list containing ["apple", "banana", "cherry"].
142 |
143 | - To collect elements into a Set, you can use the `Collectors.toSet()` collector:
144 |
145 | ```java
146 | Set numbers = Stream.of(1, 2, 2, 3, 4)
147 | .collect(Collectors.toSet());
148 | ```
149 |
150 | The elements in the stream are collected into a Set, which automatically removes duplicates.
151 |
152 | - The Collectors.groupingBy() collector allows you to group elements based on a specific criterion. For example, to group a list of people by their age:
153 |
154 | ```java
155 | List people = /* List of Person objects */;
156 | Map> ageGroups = people.stream()
157 | .collect(Collectors.groupingBy(Person::getAge));
158 | ```
159 |
160 | This creates a map where keys are ages, and values are lists of people of that age.
161 |
162 | # Sorting in Java Stream API
163 |
164 | Sorting is a common operation when working with data, and the Java Stream API provides a convenient way to sort elements in a stream. You can sort elements in ascending or descending order based on various criteria. Let's explore sorting using the Stream API.
165 |
166 | ## Example
167 |
168 | Suppose you have a list of names and you want to sort them alphabetically in ascending order using the `sorted` method:
169 |
170 | ```java
171 | List names = Arrays.asList("Alice", "David", "Bob", "Eve", "Carol");
172 |
173 | // Sorting names in ascending order
174 | List sortedNames = names.stream()
175 | .sorted()
176 | .collect(Collectors.toList());
177 | ```
178 |
179 | This will sort the names alphabetically and return a new list with ["Alice", "Bob", "Carol", "David", "Eve"]
180 |
--------------------------------------------------------------------------------
/18_Multithreading/multithreading.md:
--------------------------------------------------------------------------------
1 | # Java Multithreading (Parallel Programming)
2 |
3 | Java multithreading allows you to run multiple threads (smaller, concurrent units of a program) within a single Java program. This guide will introduce you to the basics of multithreading in Java.
4 |
5 | ## Table of Contents
6 |
7 | 1. [Introduction to Threads](#introduction-to-threads)
8 | 2. [Introduction to Multithreaded Programming](#introduction-to-multithreaded-programming)
9 | 3. [Thread class in Java](#thread-class-in-java)
10 | 4. [Sample Multithread application in Java](#sample-multithread-application-in-java)
11 |
12 | ## Introduction to Threads
13 |
14 | - A thread is the smallest unit of execution in a program. It is a lightweight, independent path of execution within a process.
15 |
16 | - Threads share the same memory space as the process they belong to, allowing them to access and modify shared data, making them useful for concurrent and parallel programming.
17 |
18 | - Threads are used to perform multiple tasks concurrently, which can lead to better resource utilization, responsiveness, and improved performance in multi-core processors.
19 |
20 | - Threads can run independently or in coordination with other threads, and they can be used for a wide range of purposes, from background tasks in user interfaces to complex parallel processing in server applications.
21 |
22 | - If there occurs exception in one thread, it doesn't affect other threads.
23 |
24 | ## Introduction to Multithreaded Programming
25 |
26 | Multithreaded programming involves the concurrent execution of multiple threads within a single program, enabling better utilization of modern multi-core processors. To understand the significance of multithreading, let's explore a simple example.
27 |
28 | ### Highway Traffic Analogy
29 |
30 | Imagine a single-lane road where vehicles can only move in one direction at a time. If one car breaks down or encounters an obstacle, the entire traffic flow comes to a halt. It's similar to a single-threaded program that gets stuck when a time-consuming task is being executed.
31 |
32 | Now, visualize a multithreaded highway with multiple lanes. If a car faces an issue in one lane, other vehicles can smoothly continue on the adjacent lanes, ensuring that traffic keeps flowing. In multithreaded programming, tasks are divided into separate threads, allowing the program to function smoothly even when one thread encounters a delay.
33 |
34 | ## Thread class in Java
35 |
36 | In Java, the `Thread` class is a fundamental class provided by the Java Standard Library (`java.lang` package) for creating and managing threads. It is part of Java's multithreading support, and it's used to create and control threads within a Java program.
37 |
38 | Here are some key aspects of the `Thread` class in Java:
39 |
40 | - **Thread Creation**: You can create a new thread by either extending the `Thread` class or by implementing the `Runnable` interface and passing it to a `Thread` object.
41 |
42 | - **Thread Execution**: To start the execution of a thread, you call the `start()` method of the `Thread` class. This method, in turn, calls the `run()` method that you override to define the thread's behavior.
43 |
44 | - **Lifecycle Management**: Threads have a lifecycle that includes states like "New," "Runnable," "Blocked," and "Terminated." You can manage these states using various methods provided by the `Thread` class, such as `sleep()`, `join()`, and `interrupt()`.
45 |
46 | - **Concurrency**: Threads can run concurrently and execute code independently. This enables parallel execution of tasks, which is essential for multitasking and utilizing multi-core processors effectively.
47 |
48 | - **Thread Synchronization**: The `Thread` class also provides synchronization mechanisms, such as `synchronized` blocks and methods, to manage shared resources and ensure thread safety.
49 |
50 | - **Thread Priority**: Threads can have priorities assigned to them using the `setPriority()` method. Priority levels help the operating system determine which threads to execute when multiple threads are competing for resources.
51 |
52 | Here's a simple example of creating and starting a thread using the `Thread` class:
53 |
54 | ```java
55 | class MyThread extends Thread {
56 | public void run() {
57 | System.out.println("Thread is running.");
58 | }
59 | }
60 |
61 | public class Main {
62 | public static void main(String[] args) {
63 | MyThread thread = new MyThread();
64 | thread.start(); // This starts the execution of the thread.
65 | }
66 | }
67 |
68 | ```
69 |
70 | ## Sample Multithread application in Java
71 |
72 | ```java
73 | public class MultithreadingDemo {
74 | public static void main(String[] args) {
75 | int numberOfThreads = 5; // Number of threads to create
76 |
77 | for (int i = 1; i <= numberOfThreads; i++) {
78 | Thread thread = new Thread(new PrintThread("Thread " + i));
79 | thread.start(); // Start the thread
80 | }
81 | }
82 |
83 | static class PrintThread implements Runnable {
84 | private String message;
85 |
86 | public PrintThread(String message) {
87 | this.message = message;
88 | }
89 |
90 | public void run() {
91 | for (int i = 1; i <= 5; i++) {
92 | System.out.println(message + " - Message " + i);
93 | try {
94 | Thread.sleep(1000); // Sleep (pause the current thread) for 1 second
95 | } catch (InterruptedException e) {
96 | e.printStackTrace();
97 | }
98 | }
99 | }
100 | }
101 | }
102 |
103 | ```
104 |
105 | ### Explanation
106 |
107 | In this program, we create multiple threads (specified by `numberOfThreads`) using the `Runnable` interface. Each thread has a `run()` method that prints a message five times with a 1-second pause between each print. Since the threads are running concurrently, you'll see their messages being printed at approximately the same time, demonstrating the concept of thread concurrency. The order in which the messages appear may vary on each run due to the concurrent nature of threads.
108 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 |
2 | # learnJava contributing guidelines
3 |
4 | Thank you for taking the time to contribute to our project! Please take a moment to read the following guidelines before contributing:
5 |
6 | > ⚠️IMPORTANT **Note**
7 | >
8 | > **Pull Requests having no issue associated with them will not be accepted. Firstly get an issue assigned, whether it's already opened or raised by you, and then create a Pull Request.**
9 |
10 | ## Prerequisites
11 |
12 | - Open Source Etiquette: If you've never contributed to an open source project before, have a read of [Basic etiquette](https://developer.mozilla.org/en-US/docs/MDN/Community/Open_source_etiquette) for open source projects.
13 |
14 | - Basic familiarity with Git and GitHub: If you are also new to these tools, visit [GitHub for complete beginners](https://developer.mozilla.org/en-US/docs/MDN/Contribute/GitHub_beginners) for a comprehensive introduction to them
15 |
16 | ## How to Contribute 🤔
17 |
18 | Look at the existing [**Issues**](https://github.com/tangorishi/learnJava/issues) or [**create a new issue**](https://github.com/tangorishi/learnJava/issues/new/choose)!
19 | - [**Fork the Repo**](https://github.com/tangorishi/learnJava/fork). Then, create a branch for any issue that you are working on. Finally, commit your work.
20 | - Create a **[Pull Request](https://github.com/tangorishi/learnJava/compare)** (_PR_), which will be promptly reviewed and given suggestions for improvements by the community.
21 | - Add screenshots or screen captures to your Pull Request to help us understand the effects of the changes proposed in your PR.
22 |
23 | ### Adding new Links 🔗
24 |
25 | > ✨ You can also create [issue(s)](https://github.com/tangorishi/learnJava/issues/new/choose) for inserting your links and someone else will take care of them.
26 |
27 | #### 🌟Follow these steps to get your Content/Code added into the Repository
28 |
29 | * A newly created category and subcategory should be added to the data file
30 | * Each category has it's own folder with it's name
31 | * Every subcategory should be placed in it respective category folder
32 |
33 | > i.e images should be inside Frontend folder
34 |
35 | * To add a new category ensure to create a folder with it's name
36 |
37 | > i.e Resources
38 |
39 | **NOTE**
40 | When you're adding a *YouTube* channel's link, please specify *language* of the channel they are using to teach in for example English, Hindi, Spanish etc. If the language is NOT specified, remove the language property.
41 |
42 | > **⚠️Important**
43 | >
44 | > - Do not make duplicate entries.
45 | > - Ensure that your entries are error-free by double-checking before staging your changes.
46 | > - Your entries should follow the above structure.
47 |
48 | ## Remarks ✅
49 |
50 | If something is missing here, or you feel something is not well described, either directly create a PR or [create an issue](https://github.com/tangorishi/learnJava/issues).
51 |
52 |
--------------------------------------------------------------------------------
/Insertionsort.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | public class Insertionsort
3 | {
4 | public static void main(String[] args) {
5 | Scanner sc=new Scanner(System.in);
6 | System.out.println("Enter the number of elements in the array");
7 | int n1=sc.nextInt();
8 | int arr[]=new int[n1];
9 | //taking array input
10 | for(int i=0;i=0 && arr[j]>=currval ){
22 | arr[j+1]=arr[j];
23 | j=j-1;
24 | }
25 | arr[j+1]=currval;
26 | }
27 | //displaying sorted array
28 | for(int i=0;i
56 |
57 |
58 | ## Table of Topics
59 |
60 | Explore the various Java topics covered in this repository:
61 |
62 | | Week | Topics |
63 | | ---- | ------ |
64 | | 0 | [Introduction](./00_Introduction/introduction.md) |
65 | | 1 | [Hello World](./01_Hello_world/hello_world.md) |
66 | | 2 | [Variables](./02_Variables/variables.md) |
67 | | 3 | [Java operators](./03_Operators/operators.md) |
68 | | 4 | [Control Structures](./04_Control_structures/control_structures.md) |
69 | | 5 | [Loops](./05_Loops/loops.md) |
70 | | 6 | [Arrays](./06_Arrays/arrays.md) |
71 | | 7 | [Lists](./07_Lists/lists.md) |
72 | | 8 | [Strings](./08_Strings/strings.md) |
73 | | 9 | [Functions](./09_Functions/functions.md) |
74 | | 10 | [Inheritance](./10_Inheritance/inheritance.md) |
75 | | 11 | [Polymorphism](./11_Polymorphism/polymorphism.md) |
76 | | 12 | [Exceptions](./12_Exceptions/exceptions.md) |
77 | | 13 | [File IO](./13_File_io/file_io.md) |
78 | | 14 | [GUI Programming with Java Swing](./14_GUI_programming/gui_programming.md) |
79 | | 15 | [Java Collections Framework](./15_Frameworks/frameworks.md) |
80 | | 16 | [First Contributions](./16_FirstContribution) |
81 | | 17 | [Stream API](./17_Stream_API/stream_api.md) |
82 | | 18 | [Multithreading (Parallel Programming)](./18_Multithreading/multithreading.md) |
83 |
84 | ## First Contributions
85 |
86 | Inside the `First Contributions` folder, you can contribute your Java code, exercises, or explanations related to any of the topics covered. We welcome your contributions to help others learn Java!
87 |
88 | Feel free to contribute to the repository and make this Hacktoberfest memorable for beginners looking to start their Java journey. Happy coding!
89 |
90 | ## License
91 |
92 | This repository is licensed under the [MIT License](LICENSE).
93 |
94 | ## Contributors
95 |
96 | We'd like to express our gratitude to all the contributors who have helped make this project better. Thank you for your valuable contributions!
97 |
98 | ### Past Contributors
99 |
100 | [](https://github.com/tangorishi)
101 | [](https://github.com/competitiveblood)
102 | [](https://github.com/dracocodess)
103 | [](https://github.com/Ankit-Saha08)
104 | [](https://github.com/Janani-Balasooriya)
105 | [](https://github.com/Sandaru-Dev)
106 | [](https://github.com/its-your-invi)
107 | [](https://github.com/SumitMangrati)
108 | [](https://github.com/LokeshYarramallu)
109 | [](https://github.com/itsyourap)
110 | [](https://github.com/jcgaming-official)
111 | [](https://github.com/arjunpndt)
112 |
113 | If you have contributed to this project and your image is not here, please let us know, and we'll be happy to add it!
114 |
115 |
116 |
117 |
118 |
119 |
--------------------------------------------------------------------------------